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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1427  ! raeburn     4: # $Id: loncommon.pm,v 1.1426 2024/01/10 20:07:37 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,
                   1177:         $suffix
1.36      matthew  1178:         ) = @_;
                   1179:     my $second = "document.$formname.$secondselectname";
                   1180:     my $first = "document.$formname.$firstselectname";
                   1181:     # output the javascript to do the changing
                   1182:     my $result = '';
1.776     bisitz   1183:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1184:     $result.="// <![CDATA[\n";
1.1245    raeburn  1185:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1186:     $" = '","';
                   1187:     my $debug = '';
                   1188:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1189:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1190:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1191:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1192:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1193:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1194:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1195:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1196:         }
1.36      matthew  1197:         $result.="\"@s2values\");\n";
1.1245    raeburn  1198:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1199:         my @s2texts;
                   1200:         foreach my $value (@s2values) {
1.1263    raeburn  1201:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1202:         }
                   1203:         $result.="\"@s2texts\");\n";
                   1204:     }
                   1205:     $"=' ';
                   1206:     $result.= <<"END";
                   1207: 
1.1245    raeburn  1208: function select1${suffix}_changed() {
1.36      matthew  1209:     // Determine new choice
1.1245    raeburn  1210:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1211:     // update select2
1.1245    raeburn  1212:     var values     = select2data${suffix}[newvalue].values;
                   1213:     var texts      = select2data${suffix}[newvalue].texts;
                   1214:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1215:     var i;
                   1216:     // out with the old
1.1245    raeburn  1217:     $second.options.length = 0;
                   1218:     // in with the new
1.36      matthew  1219:     for (i=0;i<values.length; i++) {
                   1220:         $second.options[i] = new Option(values[i]);
1.143     matthew  1221:         $second.options[i].value = values[i];
1.36      matthew  1222:         $second.options[i].text = texts[i];
                   1223:         if (values[i] == select2def) {
                   1224:             $second.options[i].selected = true;
                   1225:         }
                   1226:     }
                   1227: }
1.824     bisitz   1228: // ]]>
1.36      matthew  1229: </script>
                   1230: END
                   1231:     # output the initial values for the selection lists
1.1245    raeburn  1232:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1233:     my @order = sort(keys(%{$hashref}));
                   1234:     if (ref($menuorder) eq 'ARRAY') {
                   1235:         @order = @{$menuorder};
                   1236:     }
                   1237:     foreach my $value (@order) {
1.36      matthew  1238:         $result.="    <option value=\"$value\" ";
1.253     albertel 1239:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1240:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1241:     }
                   1242:     $result .= "</select>\n";
1.1400    raeburn  1243:     my %select2;
                   1244:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
                   1245:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
                   1246:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1247:         }
                   1248:     }
1.36      matthew  1249:     $result .= $middletext;
1.1115    raeburn  1250:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1251:     if ($onchangesecond) {
                   1252:         $result .= ' onchange="'.$onchangesecond.'"';
                   1253:     }
                   1254:     $result .= ">\n";
1.36      matthew  1255:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1256:     
                   1257:     my @secondorder = sort(keys(%select2));
                   1258:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1259:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1260:     }
                   1261:     foreach my $value (@secondorder) {
1.36      matthew  1262:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1263:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1264:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1265:     }
                   1266:     $result .= "</select>\n";
                   1267:     #    return $debug;
                   1268:     return $result;
                   1269: }   #  end of sub linked_select_forms {
                   1270: 
1.45      matthew  1271: =pod
1.44      bowersj2 1272: 
1.1381    raeburn  1273: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1274: 
1.112     bowersj2 1275: Returns a string corresponding to an HTML link to the given help
                   1276: $topic, where $topic corresponds to the name of a .tex file in
                   1277: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1278: spaces. 
                   1279: 
                   1280: $text will optionally be linked to the same topic, allowing you to
                   1281: link text in addition to the graphic. If you do not want to link
                   1282: text, but wish to specify one of the later parameters, pass an
                   1283: empty string. 
                   1284: 
                   1285: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1286: the link will not open a new window. If false, the link will open
                   1287: a new window using Javascript. (Default is false.) 
                   1288: 
                   1289: $width and $height are optional numerical parameters that will
                   1290: override the width and height of the popped up window, which may
1.973     raeburn  1291: be useful for certain help topics with big pictures included.
                   1292: 
                   1293: $imgid is the id of the img tag used for the help icon. This may be
                   1294: used in a javascript call to switch the image src.  See 
                   1295: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1296: 
1.1381    raeburn  1297: $links_target will optionally be set to a target (_top, _parent or _self).
                   1298: 
1.44      bowersj2 1299: =cut
                   1300: 
                   1301: sub help_open_topic {
1.1381    raeburn  1302:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1303:     $text = "" if (not defined $text);
1.44      bowersj2 1304:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1305:     $width = 500 if (not defined $width);
1.44      bowersj2 1306:     $height = 400 if (not defined $height);
                   1307:     my $filename = $topic;
                   1308:     $filename =~ s/ /_/g;
                   1309: 
1.48      bowersj2 1310:     my $template = "";
                   1311:     my $link;
1.572     banghart 1312:     
1.159     www      1313:     $topic=~s/\W/\_/g;
1.44      bowersj2 1314: 
1.572     banghart 1315:     if (!$stayOnPage) {
1.1033    www      1316: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1317:     } elsif ($stayOnPage eq 'popup') {
                   1318:         $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 1319:     } else {
1.48      bowersj2 1320: 	$link = "/adm/help/${filename}.hlp";
                   1321:     }
                   1322: 
                   1323:     # Add the text
1.1314    raeburn  1324:     my $target = ' target="_top"';
1.1381    raeburn  1325:     if ($links_target) {
                   1326:         $target = ' target="'.$links_target.'"';
                   1327:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1328:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1329:         $target = '';
1.1378    raeburn  1330:     }
1.1380    raeburn  1331:     if ($text ne "") {
1.763     bisitz   1332: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1333:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1334:                   .$text.'</a>';
1.48      bowersj2 1335:     }
                   1336: 
1.763     bisitz   1337:     # (Always) Add the graphic
1.179     matthew  1338:     my $title = &mt('Online Help');
1.667     raeburn  1339:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1340:     if ($imgid ne '') {
                   1341:         $imgid = ' id="'.$imgid.'"';
                   1342:     }
1.1314    raeburn  1343:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1344:               .'<img src="'.$helpicon.'" border="0"'
                   1345:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1346:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1347:               .' /></a>';
                   1348:     if ($text ne "") {	
                   1349:         $template.='</span>';
                   1350:     }
1.44      bowersj2 1351:     return $template;
                   1352: 
1.106     bowersj2 1353: }
                   1354: 
                   1355: # This is a quicky function for Latex cheatsheet editing, since it 
                   1356: # appears in at least four places
                   1357: sub helpLatexCheatsheet {
1.1037    www      1358:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1359:     my $out;
1.106     bowersj2 1360:     my $addOther = '';
1.732     raeburn  1361:     if ($topic) {
1.1037    www      1362: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1363:     }
                   1364:     $out = '<span>' # Start cheatsheet
                   1365: 	  .$addOther
                   1366:           .'<span>'
1.1037    www      1367: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1368: 	  .'</span> <span>'
1.1037    www      1369: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1370: 	  .'</span>';
1.732     raeburn  1371:     unless ($not_author) {
1.1186    kruse    1372:         $out .= '<span>'
                   1373:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1374:                .'</span> <span>'
1.1424    raeburn  1375:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.763     bisitz   1376: 	       .'</span>';
1.732     raeburn  1377:     }
1.763     bisitz   1378:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1379:     return $out;
1.172     www      1380: }
                   1381: 
1.430     albertel 1382: sub general_help {
                   1383:     my $helptopic='Student_Intro';
                   1384:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1385: 	$helptopic='Authoring_Intro';
1.907     raeburn  1386:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1387: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1388:     } elsif ($env{'request.role'}=~/^dc/) {
                   1389:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1390:     }
                   1391:     return $helptopic;
                   1392: }
                   1393: 
                   1394: sub update_help_link {
                   1395:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1396:     my $origurl = $ENV{'REQUEST_URI'};
                   1397:     $origurl=~s|^/~|/priv/|;
                   1398:     my $timestamp = time;
                   1399:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1400:         $$datum = &escape($$datum);
                   1401:     }
                   1402: 
                   1403:     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";
                   1404:     my $output .= <<"ENDOUTPUT";
                   1405: <script type="text/javascript">
1.824     bisitz   1406: // <![CDATA[
1.430     albertel 1407: banner_link = '$banner_link';
1.824     bisitz   1408: // ]]>
1.430     albertel 1409: </script>
                   1410: ENDOUTPUT
                   1411:     return $output;
                   1412: }
                   1413: 
                   1414: # now just updates the help link and generates a blue icon
1.193     raeburn  1415: sub help_open_menu {
1.1381    raeburn  1416:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1417: 	= @_;    
1.949     droeschl 1418:     $stayOnPage = 1;
1.430     albertel 1419:     my $output;
                   1420:     if ($component_help) {
                   1421: 	if (!$text) {
                   1422: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1423: 				       $width,$height,'',$links_target);
1.430     albertel 1424: 	} else {
                   1425: 	    my $help_text;
                   1426: 	    $help_text=&unescape($topic);
                   1427: 	    $output='<table><tr><td>'.
                   1428: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1429: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1430: 	}
                   1431:     }
                   1432:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1433:     return $output.$banner_link;
                   1434: }
                   1435: 
                   1436: sub top_nav_help {
1.1369    raeburn  1437:     my ($text,$linkattr) = @_;
1.436     albertel 1438:     $text = &mt($text);
1.949     droeschl 1439:     my $stay_on_page = 1;
                   1440: 
1.1168    raeburn  1441:     my ($link,$banner_link);
                   1442:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1443:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1444: 	                         : "javascript:helpMenu('open')";
                   1445:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1446:     }
1.201     raeburn  1447:     my $title = &mt('Get help');
1.1168    raeburn  1448:     if ($link) {
                   1449:         return <<"END";
1.436     albertel 1450: $banner_link
1.1369    raeburn  1451: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1452: END
1.1168    raeburn  1453:     } else {
                   1454:         return '&nbsp;'.$text.'&nbsp;';
                   1455:     }
1.436     albertel 1456: }
                   1457: 
                   1458: sub help_menu_js {
1.1154    raeburn  1459:     my ($httphost) = @_;
1.949     droeschl 1460:     my $stayOnPage = 1;
1.436     albertel 1461:     my $width = 620;
                   1462:     my $height = 600;
1.430     albertel 1463:     my $helptopic=&general_help();
1.1154    raeburn  1464:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1465:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1466:     my $start_page =
                   1467:         &Apache::loncommon::start_page('Help Menu', undef,
                   1468: 				       {'frameset'    => 1,
                   1469: 					'js_ready'    => 1,
1.1154    raeburn  1470:                                         'use_absolute' => $httphost,
1.331     albertel 1471: 					'add_entries' => {
1.1168    raeburn  1472: 					    'border' => '0', 
1.579     raeburn  1473: 					    'rows'   => "110,*",},});
1.331     albertel 1474:     my $end_page =
                   1475:         &Apache::loncommon::end_page({'frameset' => 1,
                   1476: 				      'js_ready' => 1,});
                   1477: 
1.436     albertel 1478:     my $template .= <<"ENDTEMPLATE";
                   1479: <script type="text/javascript">
1.877     bisitz   1480: // <![CDATA[
1.253     albertel 1481: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1482: var banner_link = '';
1.243     raeburn  1483: function helpMenu(target) {
                   1484:     var caller = this;
                   1485:     if (target == 'open') {
                   1486:         var newWindow = null;
                   1487:         try {
1.262     albertel 1488:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1489:         }
                   1490:         catch(error) {
                   1491:             writeHelp(caller);
                   1492:             return;
                   1493:         }
                   1494:         if (newWindow) {
                   1495:             caller = newWindow;
                   1496:         }
1.193     raeburn  1497:     }
1.243     raeburn  1498:     writeHelp(caller);
                   1499:     return;
                   1500: }
                   1501: function writeHelp(caller) {
1.1168    raeburn  1502:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1503:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1504:     caller.document.close();
                   1505:     caller.focus();
1.193     raeburn  1506: }
1.877     bisitz   1507: // END LON-CAPA Internal -->
1.253     albertel 1508: // ]]>
1.436     albertel 1509: </script>
1.193     raeburn  1510: ENDTEMPLATE
                   1511:     return $template;
                   1512: }
                   1513: 
1.172     www      1514: sub help_open_bug {
                   1515:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1516:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1517:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1518:     $text = "" if (not defined $text);
                   1519: 	$stayOnPage=1;
1.184     albertel 1520:     $width = 600 if (not defined $width);
                   1521:     $height = 600 if (not defined $height);
1.172     www      1522: 
                   1523:     $topic=~s/\W+/\+/g;
                   1524:     my $link='';
                   1525:     my $template='';
1.379     albertel 1526:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1527: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1528:     if (!$stayOnPage)
                   1529:     {
                   1530: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1531:     }
                   1532:     else
                   1533:     {
                   1534: 	$link = $url;
                   1535:     }
1.1314    raeburn  1536: 
1.1382    raeburn  1537:     my $target = '_top';
                   1538:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1539:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1540:         $target = '_blank';
1.1378    raeburn  1541:     }
1.1382    raeburn  1542: 
1.172     www      1543:     # Add the text
                   1544:     if ($text ne "")
                   1545:     {
                   1546: 	$template .= 
                   1547:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1548:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1549:     }
                   1550: 
                   1551:     # Add the graphic
1.179     matthew  1552:     my $title = &mt('Report a Bug');
1.215     albertel 1553:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1554:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1555:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1556: ENDTEMPLATE
                   1557:     if ($text ne '') { $template.='</td></tr></table>' };
                   1558:     return $template;
                   1559: 
                   1560: }
                   1561: 
                   1562: sub help_open_faq {
                   1563:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1564:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1565:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1566:     $text = "" if (not defined $text);
                   1567: 	$stayOnPage=1;
                   1568:     $width = 350 if (not defined $width);
                   1569:     $height = 400 if (not defined $height);
                   1570: 
                   1571:     $topic=~s/\W+/\+/g;
                   1572:     my $link='';
                   1573:     my $template='';
                   1574:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1575:     if (!$stayOnPage)
                   1576:     {
                   1577: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1578:     }
                   1579:     else
                   1580:     {
                   1581: 	$link = $url;
                   1582:     }
                   1583: 
                   1584:     # Add the text
                   1585:     if ($text ne "")
                   1586:     {
                   1587: 	$template .= 
1.173     www      1588:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1589:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1590:     }
                   1591: 
                   1592:     # Add the graphic
1.179     matthew  1593:     my $title = &mt('View the FAQ');
1.215     albertel 1594:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1595:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1596:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1597: ENDTEMPLATE
                   1598:     if ($text ne '') { $template.='</td></tr></table>' };
                   1599:     return $template;
                   1600: 
1.44      bowersj2 1601: }
1.37      matthew  1602: 
1.180     matthew  1603: ###############################################################
                   1604: ###############################################################
                   1605: 
1.45      matthew  1606: =pod
                   1607: 
1.648     raeburn  1608: =item * &change_content_javascript():
1.256     matthew  1609: 
                   1610: This and the next function allow you to create small sections of an
                   1611: otherwise static HTML page that you can update on the fly with
                   1612: Javascript, even in Netscape 4.
                   1613: 
                   1614: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1615: must be written to the HTML page once. It will prove the Javascript
                   1616: function "change(name, content)". Calling the change function with the
                   1617: name of the section 
                   1618: you want to update, matching the name passed to C<changable_area>, and
                   1619: the new content you want to put in there, will put the content into
                   1620: that area.
                   1621: 
                   1622: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1623: to contain room for the original contents. You need to "make space"
                   1624: for whatever changes you wish to make, and be B<sure> to check your
                   1625: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1626: it's adequate for updating a one-line status display, but little more.
                   1627: This script will set the space to 100% width, so you only need to
                   1628: worry about height in Netscape 4.
                   1629: 
                   1630: Modern browsers are much less limiting, and if you can commit to the
                   1631: user not using Netscape 4, this feature may be used freely with
                   1632: pretty much any HTML.
                   1633: 
                   1634: =cut
                   1635: 
                   1636: sub change_content_javascript {
                   1637:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1638:     if ($env{'browser.type'} eq 'netscape' &&
                   1639: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1640: 	return (<<NETSCAPE4);
                   1641: 	function change(name, content) {
                   1642: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1643: 	    doc.open();
                   1644: 	    doc.write(content);
                   1645: 	    doc.close();
                   1646: 	}
                   1647: NETSCAPE4
                   1648:     } else {
                   1649: 	# Otherwise, we need to use semi-standards-compliant code
                   1650: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1651: 	# is really scary, and every useful browser supports it
                   1652: 	return (<<DOMBASED);
                   1653: 	function change(name, content) {
                   1654: 	    element = document.getElementById(name);
                   1655: 	    element.innerHTML = content;
                   1656: 	}
                   1657: DOMBASED
                   1658:     }
                   1659: }
                   1660: 
                   1661: =pod
                   1662: 
1.648     raeburn  1663: =item * &changable_area($name,$origContent):
1.256     matthew  1664: 
                   1665: This provides a "changable area" that can be modified on the fly via
                   1666: the Javascript code provided in C<change_content_javascript>. $name is
                   1667: the name you will use to reference the area later; do not repeat the
                   1668: same name on a given HTML page more then once. $origContent is what
                   1669: the area will originally contain, which can be left blank.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: sub changable_area {
                   1674:     my ($name, $origContent) = @_;
                   1675: 
1.258     albertel 1676:     if ($env{'browser.type'} eq 'netscape' &&
                   1677: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1678: 	# If this is netscape 4, we need to use the Layer tag
                   1679: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1680:     } else {
                   1681: 	return "<span id='$name'>$origContent</span>";
                   1682:     }
                   1683: }
                   1684: 
                   1685: =pod
                   1686: 
1.648     raeburn  1687: =item * &viewport_geometry_js 
1.590     raeburn  1688: 
                   1689: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1690: 
                   1691: =cut
                   1692: 
                   1693: 
                   1694: sub viewport_geometry_js { 
                   1695:     return <<"GEOMETRY";
                   1696: var Geometry = {};
                   1697: function init_geometry() {
                   1698:     if (Geometry.init) { return };
                   1699:     Geometry.init=1;
                   1700:     if (window.innerHeight) {
                   1701:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1702:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1703:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1704:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1705:     }
                   1706:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1707:         Geometry.getViewportHeight =
                   1708:             function() { return document.documentElement.clientHeight; };
                   1709:         Geometry.getViewportWidth =
                   1710:             function() { return document.documentElement.clientWidth; };
                   1711: 
                   1712:         Geometry.getHorizontalScroll =
                   1713:             function() { return document.documentElement.scrollLeft; };
                   1714:         Geometry.getVerticalScroll =
                   1715:             function() { return document.documentElement.scrollTop; };
                   1716:     }
                   1717:     else if (document.body.clientHeight) {
                   1718:         Geometry.getViewportHeight =
                   1719:             function() { return document.body.clientHeight; };
                   1720:         Geometry.getViewportWidth =
                   1721:             function() { return document.body.clientWidth; };
                   1722:         Geometry.getHorizontalScroll =
                   1723:             function() { return document.body.scrollLeft; };
                   1724:         Geometry.getVerticalScroll =
                   1725:             function() { return document.body.scrollTop; };
                   1726:     }
                   1727: }
                   1728: 
                   1729: GEOMETRY
                   1730: }
                   1731: 
                   1732: =pod
                   1733: 
1.648     raeburn  1734: =item * &viewport_size_js()
1.590     raeburn  1735: 
                   1736: 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. 
                   1737: 
                   1738: =cut
                   1739: 
                   1740: sub viewport_size_js {
                   1741:     my $geometry = &viewport_geometry_js();
                   1742:     return <<"DIMS";
                   1743: 
                   1744: $geometry
                   1745: 
                   1746: function getViewportDims(width,height) {
                   1747:     init_geometry();
                   1748:     width.value = Geometry.getViewportWidth();
                   1749:     height.value = Geometry.getViewportHeight();
                   1750:     return;
                   1751: }
                   1752: 
                   1753: DIMS
                   1754: }
                   1755: 
                   1756: =pod
                   1757: 
1.648     raeburn  1758: =item * &resize_textarea_js()
1.565     albertel 1759: 
                   1760: emits the needed javascript to resize a textarea to be as big as possible
                   1761: 
                   1762: creates a function resize_textrea that takes two IDs first should be
                   1763: the id of the element to resize, second should be the id of a div that
                   1764: surrounds everything that comes after the textarea, this routine needs
                   1765: to be attached to the <body> for the onload and onresize events.
                   1766: 
                   1767: =cut
                   1768: 
                   1769: sub resize_textarea_js {
1.590     raeburn  1770:     my $geometry = &viewport_geometry_js();
1.565     albertel 1771:     return <<"RESIZE";
                   1772:     <script type="text/javascript">
1.824     bisitz   1773: // <![CDATA[
1.590     raeburn  1774: $geometry
1.565     albertel 1775: 
1.588     albertel 1776: function getX(element) {
                   1777:     var x = 0;
                   1778:     while (element) {
                   1779: 	x += element.offsetLeft;
                   1780: 	element = element.offsetParent;
                   1781:     }
                   1782:     return x;
                   1783: }
                   1784: function getY(element) {
                   1785:     var y = 0;
                   1786:     while (element) {
                   1787: 	y += element.offsetTop;
                   1788: 	element = element.offsetParent;
                   1789:     }
                   1790:     return y;
                   1791: }
                   1792: 
                   1793: 
1.565     albertel 1794: function resize_textarea(textarea_id,bottom_id) {
                   1795:     init_geometry();
                   1796:     var textarea        = document.getElementById(textarea_id);
                   1797:     //alert(textarea);
                   1798: 
1.588     albertel 1799:     var textarea_top    = getY(textarea);
1.565     albertel 1800:     var textarea_height = textarea.offsetHeight;
                   1801:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1802:     var bottom_top      = getY(bottom);
1.565     albertel 1803:     var bottom_height   = bottom.offsetHeight;
                   1804:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1805:     var fudge           = 23;
1.565     albertel 1806:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1807:     if (new_height < 300) {
                   1808: 	new_height = 300;
                   1809:     }
                   1810:     textarea.style.height=new_height+'px';
                   1811: }
1.824     bisitz   1812: // ]]>
1.565     albertel 1813: </script>
                   1814: RESIZE
                   1815: 
                   1816: }
                   1817: 
1.1205    golterma 1818: sub colorfuleditor_js {
1.1248    raeburn  1819:     my $browse_or_search;
                   1820:     my $respath;
                   1821:     my ($cnum,$cdom) = &crsauthor_url();
                   1822:     if ($cnum) {
                   1823:         $respath = "/res/$cdom/$cnum/";
                   1824:         my %js_lt = &Apache::lonlocal::texthash(
                   1825:             sunm => 'Sub-directory name',
                   1826:             save => 'Save page to make this permanent',
                   1827:         );
                   1828:         &js_escape(\%js_lt);
1.1400    raeburn  1829:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1830:         $browse_or_search = <<"END";
                   1831: 
1.1400    raeburn  1832:     $showfile_js
                   1833: 
1.1248    raeburn  1834:     function toggleChooser(form,element,titleid,only,search) {
                   1835:         var disp = 'none';
                   1836:         if (document.getElementById('chooser_'+element)) {
                   1837:             var curr = document.getElementById('chooser_'+element).style.display;
                   1838:             if (curr == 'none') {
                   1839:                 disp='inline';
                   1840:                 if (form.elements['chooser_'+element].length) {
                   1841:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1842:                         form.elements['chooser_'+element][i].checked = false;
                   1843:                     }
                   1844:                 }
                   1845:                 toggleResImport(form,element);
                   1846:             }
                   1847:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1848:             var dirsel = '';
                   1849:             var filesel = '';
                   1850:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1851:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1852:                 if (currcrsres == 'none') {
                   1853:                     dirsel = 'coursepath_'+element;
                   1854:                     var filesel = 'coursefile_'+element;
                   1855:                     var include;
                   1856:                     if (document.getElementById('crsres_include_'+element)) {
                   1857:                         include = document.getElementById('crsres_include_'+element).value;
                   1858:                     }
1.1402    raeburn  1859:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1860:                 }
                   1861:             }
                   1862:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1863:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1864:                 if (currcrsupload == 'none') {
                   1865:                     dirsel = 'crsauthorpath_'+element;
                   1866:                     filesel = '';
1.1402    raeburn  1867:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1868:                 }
                   1869:             }
1.1248    raeburn  1870:         }
                   1871:     }
                   1872: 
1.1400    raeburn  1873:     function toggleCrsFile(form,element) {
1.1248    raeburn  1874:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1875:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1876:             if (curr == 'none') {
1.1400    raeburn  1877:                 if (document.getElementById('coursepath_'+element)) {
                   1878:                     var numdirs;
                   1879:                     if (document.getElementById('coursepath_'+element).length) {
                   1880:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1881:                     }
1.1402    raeburn  1882:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1883:                         (document.getElementById('nocrsres_'+element))) {
                   1884:                         if (numdirs) {
                   1885:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1886:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1887:                         } else {
                   1888:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1889:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1890:                         }
                   1891:                     }
1.1248    raeburn  1892:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1893:                     if (numdirs > 1) {
1.1400    raeburn  1894:                         var selelem = form.elements['coursefile_'+element];
                   1895:                         var i, len = selelem.options.length -1;
                   1896:                         if (len >=0) {
                   1897:                             for (i = len; i >= 0; i--) {
                   1898:                                 selelem.remove(i);
                   1899:                             }
                   1900:                             selelem.options[0] = new Option('','');
                   1901:                         }
1.1248    raeburn  1902:                     }
                   1903:                 }
1.1400    raeburn  1904:             }
1.1248    raeburn  1905:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1906:         }
                   1907:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1908:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1909:             if (document.getElementById('uploadcrsres_'+element)) {
                   1910:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1911:             }
                   1912:         }
                   1913:         return;
                   1914:     }
                   1915: 
1.1400    raeburn  1916:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1917:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1918:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1919:         }
                   1920:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1921:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1922:             if (curr == 'none') {
1.1400    raeburn  1923:                 form.elements['newsubdir_'+element][0].checked = true;
                   1924:                 toggleNewsubdir(form,element);
                   1925:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1926:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1927:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1928:                 }
                   1929:             }
                   1930:         }
                   1931:         return;
                   1932:     }
                   1933: 
                   1934:     function toggleResImport(form,element) {
                   1935:         var choices = new Array('crsres','upload');
                   1936:         for (var i=0; i<choices.length; i++) {
                   1937:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1938:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1939:             }
                   1940:         }
                   1941:     }
                   1942: 
                   1943:     function toggleNewsubdir(form,element) {
                   1944:         var newsub = form.elements['newsubdir_'+element];
                   1945:         if (newsub) {
                   1946:             if (newsub.length) {
                   1947:                 for (var j=0; j<newsub.length; j++) {
                   1948:                     if (newsub[j].checked) {
                   1949:                         if (document.getElementById('newsubdirname_'+element)) {
                   1950:                             if (newsub[j].value == '1') {
                   1951:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1952:                                 if (document.getElementById('newsubdir_'+element)) {
                   1953:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1954:                                 }
                   1955:                             } else {
                   1956:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1957:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1958:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1959:                             }
                   1960:                         }
                   1961:                         break; 
                   1962:                     }
                   1963:                 }
                   1964:             }
                   1965:         }
                   1966:     }
                   1967: 
                   1968:     function updateCrsFile(form,element) {
                   1969:         var directory = form.elements['coursepath_'+element];
                   1970:         var filename = form.elements['coursefile_'+element];
                   1971:         var path = directory.options[directory.selectedIndex].value;
                   1972:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1973:         if (file != '') {
                   1974:             form.elements[element].value = '$respath';
                   1975:             if (path == '/') {
                   1976:                 form.elements[element].value += file;
                   1977:             } else {
                   1978:                 form.elements[element].value += path+'/'+file;
                   1979:             }
                   1980:             unClean();
                   1981:             if (document.getElementById('previewimg_'+element)) {
                   1982:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1983:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1984:             }
                   1985:             if (document.getElementById('showimg_'+element)) {
                   1986:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1987:             }
1.1248    raeburn  1988:         }
                   1989:         toggleChooser(form,element);
                   1990:         return;
                   1991:     }
                   1992: 
                   1993:     function uploadDone(suffix,name) {
                   1994:         if (name) {
                   1995: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1996:             unClean();
                   1997:             toggleChooser(document.forms["lonhomework"],suffix);
                   1998:         }
                   1999:     }
                   2000: 
                   2001: \$(document).ready(function(){
                   2002: 
                   2003:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2004:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2005:             var buttonId = this.id;
                   2006:             var suffix = buttonId.toString();
                   2007:             suffix = suffix.replace(/^crsupload_/,'');
                   2008:             event.preventDefault();
                   2009:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2010:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2011:             \$(this.form).submit();
                   2012:             document.lonhomework.target = '';
                   2013:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2014:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2015:             }
                   2016:             return false;
                   2017:         }
                   2018:     });
                   2019: });
                   2020: END
                   2021:     }
1.1205    golterma 2022:     return <<"COLORFULEDIT"
                   2023: <script type="text/javascript">
                   2024: // <![CDATA[>
                   2025:     function fold_box(curDepth, lastresource){
                   2026: 
                   2027:     // we need a list because there can be several blocks you need to fold in one tag
                   2028:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2029:     // but there is only one folding button per tag
                   2030:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2031: 
                   2032:         if(block.item(0).style.display == 'none'){
                   2033: 
                   2034:             foldbutton.value = '@{[&mt("Hide")]}';
                   2035:             for (i = 0; i < block.length; i++){
                   2036:                 block.item(i).style.display = '';
                   2037:             }
                   2038:         }else{
                   2039: 
                   2040:             foldbutton.value = '@{[&mt("Show")]}';
                   2041:             for (i = 0; i < block.length; i++){
                   2042:                 // block.item(i).style.visibility = 'collapse';
                   2043:                 block.item(i).style.display = 'none';
                   2044:             }
                   2045:         };
                   2046:         saveState(lastresource);
                   2047:     }
                   2048: 
                   2049:     function saveState (lastresource) {
                   2050: 
                   2051:         var tag_list = getTagList();
                   2052:         if(tag_list != null){
                   2053:             var timestamp = new Date().getTime();
                   2054:             var key = lastresource;
                   2055: 
                   2056:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2057:             // starting with timestamp
                   2058:             var value = timestamp+';';
                   2059: 
                   2060:             // building the list of key-value pairs
                   2061:             for(var i = 0; i < tag_list.length; i++){
                   2062:                 value += tag_list[i]+',';
                   2063:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2064:             }
                   2065: 
                   2066:             // only iterate whole storage if nothing to override
                   2067:             if(localStorage.getItem(key) == null){        
                   2068: 
                   2069:                 // prevent storage from growing large
                   2070:                 if(localStorage.length > 50){
                   2071:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2072:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2073:                     var oldest_key;
                   2074:                     
                   2075:                     for(var i = 1; i < localStorage.length; i++){
                   2076:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2077:                             oldest_key = localStorage.key(i);
                   2078:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2079:                         }
                   2080:                     }
                   2081:                     localStorage.removeItem(oldest_key);
                   2082:                 }
                   2083:             }
                   2084:             localStorage.setItem(key,value);
                   2085:         }
                   2086:     }
                   2087: 
                   2088:     // restore folding status of blocks (on page load)
                   2089:     function restoreState (lastresource) {
                   2090:         if(localStorage.getItem(lastresource) != null){
                   2091:             var key = lastresource;
                   2092:             var value = localStorage.getItem(key);
                   2093:             var regex_delTimestamp = /^\d+;/;
                   2094: 
                   2095:             value.replace(regex_delTimestamp, '');
                   2096: 
                   2097:             var valueArr = value.split(';');
                   2098:             var pairs;
                   2099:             var elements;
                   2100:             for (var i = 0; i < valueArr.length; i++){
                   2101:                 pairs = valueArr[i].split(',');
                   2102:                 elements = document.getElementsByName(pairs[0]);
                   2103: 
                   2104:                 for (var j = 0; j < elements.length; j++){  
                   2105:                     elements[j].style.display = pairs[1];
                   2106:                     if (pairs[1] == "none"){
                   2107:                         var regex_id = /([_\\d]+)\$/;
                   2108:                         regex_id.exec(pairs[0]);
                   2109:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2110:                     }
                   2111:                 }
                   2112:             }
                   2113:         }
                   2114:     }
                   2115: 
                   2116:     function getTagList () {
                   2117:         
                   2118:         var stringToSearch = document.lonhomework.innerHTML;
                   2119: 
                   2120:         var ret = new Array();
                   2121:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2122:         var tag_list = stringToSearch.match(regex_findBlock);
                   2123: 
                   2124:         if(tag_list != null){
                   2125:             for(var i = 0; i < tag_list.length; i++){            
                   2126:                 ret.push(tag_list[i].replace(/"/, ''));
                   2127:             }
                   2128:         }
                   2129:         return ret;
                   2130:     }
                   2131: 
                   2132:     function saveScrollPosition (resource) {
                   2133:         var tag_list = getTagList();
                   2134: 
                   2135:         // we dont always want to jump to the first block
                   2136:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2137:         if(\$(window).scrollTop() > 170){
                   2138:             if(tag_list != null){
                   2139:                 var result;
                   2140:                 for(var i = 0; i < tag_list.length; i++){
                   2141:                     if(isElementInViewport(tag_list[i])){
                   2142:                         result += tag_list[i]+';';
                   2143:                     }
                   2144:                 }
                   2145:                 sessionStorage.setItem('anchor_'+resource, result);
                   2146:             }
                   2147:         } else {
                   2148:             // we dont need to save zero, just delete the item to leave everything tidy
                   2149:             sessionStorage.removeItem('anchor_'+resource);
                   2150:         }
                   2151:     }
                   2152: 
                   2153:     function restoreScrollPosition(resource){
                   2154: 
                   2155:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2156:         if(elem != null){
                   2157:             var tag_list = elem.split(';');
                   2158:             var elem_list;
                   2159: 
                   2160:             for(var i = 0; i < tag_list.length; i++){
                   2161:                 elem_list = document.getElementsByName(tag_list[i]);
                   2162:                 
                   2163:                 if(elem_list.length > 0){
                   2164:                     elem = elem_list[0];
                   2165:                     break;
                   2166:                 }
                   2167:             }
                   2168:             elem.scrollIntoView();
                   2169:         }
                   2170:     }
                   2171: 
                   2172:     function isElementInViewport(el) {
                   2173: 
                   2174:         // change to last element instead of first
                   2175:         var elem = document.getElementsByName(el);
                   2176:         var rect = elem[0].getBoundingClientRect();
                   2177: 
                   2178:         return (
                   2179:             rect.top >= 0 &&
                   2180:             rect.left >= 0 &&
                   2181:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2182:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2183:         );
                   2184:     }
                   2185:     
                   2186:     function autosize(depth){
                   2187:         var cmInst = window['cm'+depth];
                   2188:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2189: 
                   2190:         // is fixed size, switching to dynamic
                   2191:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2192:             cmInst.setSize("","auto");
                   2193:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2194:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2195: 
                   2196:         // is dynamic size, switching to fixed
                   2197:         } else {
                   2198:             cmInst.setSize("","300px");
                   2199:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2200:             sessionStorage.removeItem("autosized_"+depth);
                   2201:         }
                   2202:     }
                   2203: 
1.1248    raeburn  2204: $browse_or_search
1.1205    golterma 2205: 
                   2206: // ]]>
                   2207: </script>
                   2208: COLORFULEDIT
                   2209: }
                   2210: 
                   2211: sub xmleditor_js {
                   2212:     return <<XMLEDIT
                   2213: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2214: <script type="text/javascript">
                   2215: // <![CDATA[>
                   2216: 
                   2217:     function saveScrollPosition (resource) {
                   2218: 
                   2219:         var scrollPos = \$(window).scrollTop();
                   2220:         sessionStorage.setItem(resource,scrollPos);
                   2221:     }
                   2222: 
                   2223:     function restoreScrollPosition(resource){
                   2224: 
                   2225:         var scrollPos = sessionStorage.getItem(resource);
                   2226:         \$(window).scrollTop(scrollPos);
                   2227:     }
                   2228: 
                   2229:     // unless internet explorer
                   2230:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2231: 
                   2232:         \$(document).ready(function() {
                   2233:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2234:         });
                   2235:     }
                   2236: 
                   2237:     // inserts text at cursor position into codemirror (xml editor only)
                   2238:     function insertText(text){
                   2239:         cm.focus();
                   2240:         var curPos = cm.getCursor();
                   2241:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2242:     }
                   2243: // ]]>
                   2244: </script>
                   2245: XMLEDIT
                   2246: }
                   2247: 
                   2248: sub insert_folding_button {
                   2249:     my $curDepth = $Apache::lonxml::curdepth;
                   2250:     my $lastresource = $env{'request.ambiguous'};
                   2251: 
                   2252:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2253:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2254: }
                   2255: 
1.1248    raeburn  2256: sub crsauthor_url {
                   2257:     my ($url) = @_;
                   2258:     if ($url eq '') {
                   2259:         $url = $ENV{'REQUEST_URI'};
                   2260:     }
                   2261:     my ($cnum,$cdom);
                   2262:     if ($env{'request.course.id'}) {
                   2263:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2264:         if ($audom ne '' && $auname ne '') {
                   2265:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2266:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2267:                 $cnum = $auname;
                   2268:                 $cdom = $audom;
                   2269:             }
                   2270:         }
                   2271:     }
                   2272:     return ($cnum,$cdom);
                   2273: }
                   2274: 
                   2275: sub import_crsauthor_form {
1.1400    raeburn  2276:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2277:     return (0) unless ($env{'request.course.id'});
                   2278:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2279:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2280:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2281:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2282:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2283:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2284: 
1.1248    raeburn  2285:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2286:         $is_home = 1;
                   2287:     }
1.1400    raeburn  2288:     $toppath = "/priv/$cdom/$cnum";
                   2289:     my $nonemptydir = 1;
                   2290:     my $js_only;
                   2291:     if ($only) {
                   2292:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2293:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2294:     }
                   2295:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2296:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2297:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2298:     my %lt = &Apache::lonlocal::texthash (
                   2299:         fnam => 'Filename',
                   2300:         dire => 'Directory',
1.1400    raeburn  2301:         se   => 'Select',
1.1248    raeburn  2302:     );
1.1402    raeburn  2303:     $output = $lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2304:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2305:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2306:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2307:     if ($files{'/'}) {
                   2308:         $output .= '<option value="/">/</option>'."\n";
                   2309:     }
1.1400    raeburn  2310:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2311:         next if ($key eq '/');
1.1400    raeburn  2312:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2313:     }
                   2314:     $output .= '</select><br />'."\n".
1.1402    raeburn  2315:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2316:                '<option value="" selected="selected"></option>'."\n".
1.1402    raeburn  2317:                '</select>'."\n".
                   2318:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2319:     return ($numdirs,$output);
                   2320: }
                   2321: 
                   2322: sub show_crsfiles_js {
                   2323:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2324:     my $se = &js_escape(&mt('Select'));
                   2325:     my $exclude;
                   2326:     if (ref($excluderef) eq 'HASH') {
                   2327:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2328:     }
                   2329:     my $js = <<"END";
                   2330: 
                   2331: 
1.1402    raeburn  2332:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2333:         var relpath = '';
                   2334:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2335:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2336:             if (currdir == '') {
                   2337:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2338:                     selelem = form.elements[filesel];
                   2339:                     var j, numfiles = selelem.options.length -1;
                   2340:                     if (numfiles >=0) {
                   2341:                         for (j = numfiles; j >= 0; j--) {
                   2342:                             selelem.remove(j);
                   2343:                         }
                   2344:                     }
                   2345:                     if (selelem.options.length == 0) {
                   2346:                         selelem.options[selelem.options.length] = new Option('','');
                   2347:                         selelem.selectedIndex = 0;
1.1248    raeburn  2348:                     }
                   2349:                 }
1.1400    raeburn  2350:                 return;
                   2351:             } else {
                   2352:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2353:             }
                   2354:         }
1.1400    raeburn  2355:         var http = new XMLHttpRequest();
                   2356:         var url = "/adm/courseauthor";
                   2357:         var crsrole = "$env{'request.role'}";
                   2358:         var exclude = '';
                   2359:         if (exc) {
                   2360:             exclude = '$exclude';
                   2361:         }
1.1402    raeburn  2362:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2363:         http.open("POST", url, true);
                   2364:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2365:         http.onreadystatechange = function() {
                   2366:             if (http.readyState == 4 && http.status == 200) {
                   2367:                 var data = JSON.parse(http.responseText);
                   2368:                 var selelem;
                   2369:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2370:                     if (Array.isArray(data.dirs)) {
                   2371:                         selelem = form.elements[dirsel];
                   2372:                         var i, numdirs = selelem.options.length -1;
                   2373:                         if (numdirs >=0) {
                   2374:                             for (i = numdirs; i >= 0; i--) {
                   2375:                                 selelem.remove(i);
                   2376:                             }
                   2377:                         }
                   2378:                         var len = data.dirs.length;
                   2379:                         if (len) {
1.1402    raeburn  2380:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2381:                             var j;
                   2382:                             for (j = 0; j < len; j++) {
                   2383:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2384:                             }
                   2385:                             selelem.selectedIndex = 0;
                   2386:                         }
                   2387:                         if (!setfile) {
                   2388:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2389:                                 selelem = form.elements[filesel];
                   2390:                                 var j, numfiles = selelem.options.length -1;
                   2391:                                 if (numfiles >=0) {
                   2392:                                     for (j = numfiles; j >= 0; j--) {
                   2393:                                         selelem.remove(j);
                   2394:                                     }
                   2395:                                 }
                   2396:                                 if (selelem.options.length == 0) {
                   2397:                                     selelem.options[selelem.options.length] = new Option('','');
                   2398:                                     selelem.selectedIndex = 0;
                   2399:                                 }
                   2400:                             }
                   2401:                         }
                   2402:                     }
                   2403:                 }
                   2404:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2405:                     selelem = form.elements[filesel];
                   2406:                     var i, numfiles = selelem.options.length -1;
                   2407:                     if (numfiles >=0) {
                   2408:                         for (i = numfiles; i >= 0; i--) {
                   2409:                             selelem.remove(i);
                   2410:                         }
                   2411:                     }
                   2412:                     var x;
                   2413:                     for (x in data.files) {
                   2414:                         if (Array.isArray(data.files[x])) {
                   2415:                             if (data.files[x].length > 1) {
                   2416:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2417:                             }
                   2418:                             var len = data.files[x].length;
                   2419:                             if (len) {
                   2420:                                 var k;
                   2421:                                 for (k = 0; k < len; k++) {
                   2422:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2423:                                 }
                   2424:                                 selelem.selectedIndex = 0;
                   2425:                             }
                   2426:                         }
                   2427:                     }
                   2428:                     if (selelem.options.length == 0) {
                   2429:                         selelem.options[selelem.options.length] = new Option('','');
                   2430:                         selelem.selectedIndex = 0;
                   2431:                     }
1.1248    raeburn  2432:                 }
                   2433:             }
                   2434:         }
1.1400    raeburn  2435:         http.send(params);
1.1248    raeburn  2436:     }
1.1400    raeburn  2437: END
1.1248    raeburn  2438: }
                   2439: 
1.1426    raeburn  2440: sub crsauthor_rights {
                   2441:     my ($rightsfile,$path,$docroot,$cnum,$cdom) = @_;
                   2442:     my $sourcerights = "$path/$rightsfile";
                   2443:     my $now = time;
                   2444:     if (!-e $sourcerights) {
                   2445:         my $cid = $cdom.'_'.$cnum;
                   2446:         if (!-e "$docroot/priv/$cdom") {
                   2447:             mkdir("$docroot/priv/$cdom",0755);
                   2448:         }
                   2449:         if (!-e "$docroot/priv/$cdom/$cnum") {
                   2450:             mkdir("$docroot/priv/$cdom/$cnum",0755);
                   2451:         }
                   2452:         if (open(my $fh,">$sourcerights")) {
                   2453:             print $fh <<END;
                   2454: <accessrule effect="deny" realm="" type="course" role="" />
                   2455: <accessrule effect="allow" realm="$cid" type="course" role="" />
                   2456: END
                   2457:             close($fh);
                   2458:         }
                   2459:     }
                   2460:     if (!-e "$sourcerights.meta") {
                   2461:         if (open(my $fh,">$sourcerights.meta")) {
                   2462:             my $author=$env{'environment.firstname'}.' '.
                   2463:                        $env{'environment.middlename'}.' '.
                   2464:                        $env{'environment.lastname'}.' '.
                   2465:                        $env{'environment.generation'};
                   2466:             $author =~ s/\s+$//;
                   2467:             print $fh <<"END";
                   2468: 
                   2469: <abstract></abstract>
                   2470: <author>$author</author>
                   2471: <authorspace>$cnum:$cdom</authorspace>
                   2472: <copyright>private</copyright>
                   2473: <creationdate>$now</creationdate>
                   2474: <customdistributionfile></customdistributionfile>
                   2475: <dependencies></dependencies>
                   2476: <domain>$cdom</domain>
                   2477: <highestgradelevel>0</highestgradelevel>
                   2478: <keywords></keywords>
                   2479: <language>notset </language>
                   2480: <lastrevisiondate>$now</lastrevisiondate>
                   2481: <lowestgradelevel>0</lowestgradelevel>
                   2482: <mime>rights</mime>
                   2483: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
                   2484: <notes></notes>
                   2485: <obsolete></obsolete>
                   2486: <obsoletereplacement></obsoletereplacement>
                   2487: <owner>$cnum:$cdom</owner>
                   2488: <rule>deny:::course,allow:$cid::course</rule>
                   2489: <sourceavail></sourceavail>
                   2490: <standards></standards>
                   2491: <subject></subject>
                   2492: <title>Course Authoring Rights</title>
                   2493: END
                   2494:             close($fh);
                   2495:         }
                   2496:     }
                   2497:     return;
                   2498: }
                   2499: 
1.565     albertel 2500: =pod
                   2501: 
1.1420    raeburn  2502: =item * &iframe_wrapper_headjs()
                   2503: 
1.1425    raeburn  2504: emits javascript containing two global vars to facilitate handling of resizing
                   2505: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2506: with standard LON-CAPA menus.
                   2507: 
                   2508: =cut
                   2509: 
1.1420    raeburn  2510: #
                   2511: # Where iframe is in use, if window.onload() executes before the custom resize function
                   2512: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2513: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2514: # do not obscure the Functions menu.
                   2515: #
                   2516: 
                   2517: sub iframe_wrapper_headjs {
                   2518:     return <<"ENDJS";
                   2519: <script type="text/javascript">
                   2520: // <![CDATA[
                   2521: var LCnotready = 0;
                   2522: var LCresizedef = 0;
                   2523: // ]]>
                   2524: </script>
                   2525: 
                   2526: ENDJS
                   2527: 
                   2528: }
                   2529: 
                   2530: =pod
                   2531: 
                   2532: =item * &iframe_wrapper_resizejs()
                   2533: 
1.1425    raeburn  2534: emits javascript used to handle resizing for a page containing
                   2535: an iframe, to ensure that the iframe does not obscure any
                   2536: standard LON-CAPA menu items.
                   2537: 
                   2538: =back
                   2539: 
                   2540: =cut
                   2541: 
1.1420    raeburn  2542: #
                   2543: # jQuery to use when iframe is in use and a page resize occurs.
                   2544: # This script will ensure that the iframe does not obscure any
                   2545: # standard LON-CAPA inline menus (primary, secondary, and/or
                   2546: # breadcrumbs and Functions menus. Expects javascript from
                   2547: # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2548: # e.g., by inclusion in second arg passed to &start_page().
                   2549: #
                   2550: 
                   2551: sub iframe_wrapper_resizejs {
                   2552:     my $offset = 5;
                   2553:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2554:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2555:         $offset = 0;
                   2556:     }
                   2557:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2558:     \$(document).ready( function() {
                   2559:         \$(window).unbind('resize').resize(function(){
                   2560:             var header = null;
                   2561:             var offset = $offset;
                   2562:             var height = 0;
                   2563:             var hdrtop = 0;
1.1421    raeburn  2564:             if (\$('div.LC_menus_content:first').length) {
                   2565:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2566:                     header = \$('div.LC_menus_content:first');
1.1423    raeburn  2567:                     offset = 12;
1.1421    raeburn  2568:                 }
                   2569:             } else if (\$('div.LC_head_subbox:first').length) {
1.1420    raeburn  2570:                 header = \$('div.LC_head_subbox:first');
                   2571:                 offset = 9;
                   2572:             } else {
                   2573:                 if (\$('#LC_breadcrumbs').length) {
                   2574:                     header = \$('#LC_breadcrumbs');
                   2575:                 }
                   2576:             }
                   2577:             if (header != null && header.length) {
                   2578:                 height = header.height();
                   2579:                 hdrtop = header.position().top;
                   2580:             }
                   2581:             var pos = height + hdrtop + offset;
                   2582:             \$('.LC_iframecontainer').css('top', pos);
                   2583:         });
                   2584:         LCresizedef = 1;
                   2585:         if (LCnotready == 1) {
                   2586:             LCnotready = 0;
                   2587:             \$(window).trigger('resize');
                   2588:         }
                   2589:     });
                   2590:     window.onload = function(){
                   2591:          if (LCresizedef) {
                   2592:              LCnotready = 0;
                   2593:              \$(window).trigger('resize');
                   2594:          } else {
                   2595:              LCnotready = 1;
                   2596:          }
                   2597:     };
                   2598: SCRIPT
                   2599: 
                   2600: }
                   2601: 
                   2602: =pod
                   2603: 
1.256     matthew  2604: =head1 Excel and CSV file utility routines
                   2605: 
                   2606: =cut
                   2607: 
                   2608: ###############################################################
                   2609: ###############################################################
                   2610: 
                   2611: =pod
                   2612: 
1.1162    raeburn  2613: =over 4
                   2614: 
1.648     raeburn  2615: =item * &csv_translate($text) 
1.37      matthew  2616: 
1.185     www      2617: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2618: format.
                   2619: 
                   2620: =cut
                   2621: 
1.180     matthew  2622: ###############################################################
                   2623: ###############################################################
1.37      matthew  2624: sub csv_translate {
                   2625:     my $text = shift;
                   2626:     $text =~ s/\"/\"\"/g;
1.209     albertel 2627:     $text =~ s/\n/ /g;
1.37      matthew  2628:     return $text;
                   2629: }
1.180     matthew  2630: 
                   2631: ###############################################################
                   2632: ###############################################################
                   2633: 
                   2634: =pod
                   2635: 
1.648     raeburn  2636: =item * &define_excel_formats()
1.180     matthew  2637: 
                   2638: Define some commonly used Excel cell formats.
                   2639: 
                   2640: Currently supported formats:
                   2641: 
                   2642: =over 4
                   2643: 
                   2644: =item header
                   2645: 
                   2646: =item bold
                   2647: 
                   2648: =item h1
                   2649: 
                   2650: =item h2
                   2651: 
                   2652: =item h3
                   2653: 
1.256     matthew  2654: =item h4
                   2655: 
                   2656: =item i
                   2657: 
1.180     matthew  2658: =item date
                   2659: 
                   2660: =back
                   2661: 
                   2662: Inputs: $workbook
                   2663: 
                   2664: Returns: $format, a hash reference.
                   2665: 
1.1057    foxr     2666: 
1.180     matthew  2667: =cut
                   2668: 
                   2669: ###############################################################
                   2670: ###############################################################
                   2671: sub define_excel_formats {
                   2672:     my ($workbook) = @_;
                   2673:     my $format;
                   2674:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2675:                                                 bottom    => 1,
                   2676:                                                 align     => 'center');
                   2677:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2678:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2679:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2680:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2681:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2682:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2683:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2684:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2685:     return $format;
                   2686: }
                   2687: 
                   2688: ###############################################################
                   2689: ###############################################################
1.113     bowersj2 2690: 
                   2691: =pod
                   2692: 
1.648     raeburn  2693: =item * &create_workbook()
1.255     matthew  2694: 
                   2695: Create an Excel worksheet.  If it fails, output message on the
                   2696: request object and return undefs.
                   2697: 
                   2698: Inputs: Apache request object
                   2699: 
                   2700: Returns (undef) on failure, 
                   2701:     Excel worksheet object, scalar with filename, and formats 
                   2702:     from &Apache::loncommon::define_excel_formats on success
                   2703: 
                   2704: =cut
                   2705: 
                   2706: ###############################################################
                   2707: ###############################################################
                   2708: sub create_workbook {
                   2709:     my ($r) = @_;
                   2710:         #
                   2711:     # Create the excel spreadsheet
                   2712:     my $filename = '/prtspool/'.
1.258     albertel 2713:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2714:         time.'_'.rand(1000000000).'.xls';
                   2715:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2716:     if (! defined($workbook)) {
                   2717:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2718:         $r->print(
                   2719:             '<p class="LC_error">'
                   2720:            .&mt('Problems occurred in creating the new Excel file.')
                   2721:            .' '.&mt('This error has been logged.')
                   2722:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2723:            .'</p>'
                   2724:         );
1.255     matthew  2725:         return (undef);
                   2726:     }
                   2727:     #
1.1014    foxr     2728:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2729:     #
                   2730:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2731:     return ($workbook,$filename,$format);
                   2732: }
                   2733: 
                   2734: ###############################################################
                   2735: ###############################################################
                   2736: 
                   2737: =pod
                   2738: 
1.648     raeburn  2739: =item * &create_text_file()
1.113     bowersj2 2740: 
1.542     raeburn  2741: Create a file to write to and eventually make available to the user.
1.256     matthew  2742: If file creation fails, outputs an error message on the request object and 
                   2743: return undefs.
1.113     bowersj2 2744: 
1.256     matthew  2745: Inputs: Apache request object, and file suffix
1.113     bowersj2 2746: 
1.256     matthew  2747: Returns (undef) on failure, 
                   2748:     Filehandle and filename on success.
1.113     bowersj2 2749: 
                   2750: =cut
                   2751: 
1.256     matthew  2752: ###############################################################
                   2753: ###############################################################
                   2754: sub create_text_file {
                   2755:     my ($r,$suffix) = @_;
                   2756:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2757:     my $fh;
                   2758:     my $filename = '/prtspool/'.
1.258     albertel 2759:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2760:         time.'_'.rand(1000000000).'.'.$suffix;
                   2761:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2762:     if (! defined($fh)) {
                   2763:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2764:         $r->print(
                   2765:             '<p class="LC_error">'
                   2766:            .&mt('Problems occurred in creating the output file.')
                   2767:            .' '.&mt('This error has been logged.')
                   2768:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2769:            .'</p>'
                   2770:         );
1.113     bowersj2 2771:     }
1.256     matthew  2772:     return ($fh,$filename)
1.113     bowersj2 2773: }
                   2774: 
                   2775: 
1.256     matthew  2776: =pod 
1.113     bowersj2 2777: 
                   2778: =back
                   2779: 
                   2780: =cut
1.37      matthew  2781: 
                   2782: ###############################################################
1.33      matthew  2783: ##        Home server <option> list generating code          ##
                   2784: ###############################################################
1.35      matthew  2785: 
1.169     www      2786: # ------------------------------------------
                   2787: 
                   2788: sub domain_select {
1.1289    raeburn  2789:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2790:     my @possdoms;
                   2791:     if (ref($incdoms) eq 'ARRAY') {
                   2792:         @possdoms = @{$incdoms};
                   2793:     } else {
                   2794:         @possdoms = &Apache::lonnet::all_domains();
                   2795:     }
                   2796: 
1.169     www      2797:     my %domains=map { 
1.514     albertel 2798: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2799:     } @possdoms;
                   2800: 
                   2801:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2802:         foreach my $dom (@{$excdoms}) {
                   2803:             delete($domains{$dom});
                   2804:         }
                   2805:     }
                   2806: 
1.169     www      2807:     if ($multiple) {
                   2808: 	$domains{''}=&mt('Any domain');
1.550     albertel 2809: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2810: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2811:     } else {
1.550     albertel 2812: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2813: 	return &select_form($name,$value,\%domains);
1.169     www      2814:     }
                   2815: }
                   2816: 
1.282     albertel 2817: #-------------------------------------------
                   2818: 
                   2819: =pod
                   2820: 
1.519     raeburn  2821: =head1 Routines for form select boxes
                   2822: 
                   2823: =over 4
                   2824: 
1.648     raeburn  2825: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2826: 
                   2827: Returns a string containing a <select> element int multiple mode
                   2828: 
                   2829: 
                   2830: Args:
                   2831:   $name - name of the <select> element
1.506     raeburn  2832:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2833:   $size - number of rows long the select element is
1.283     albertel 2834:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2835:           (shown text should already have been &mt())
1.506     raeburn  2836:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2837: 
1.282     albertel 2838: =cut
                   2839: 
                   2840: #-------------------------------------------
1.169     www      2841: sub multiple_select_form {
1.284     albertel 2842:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2843:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2844:     my $output='';
1.191     matthew  2845:     if (! defined($size)) {
                   2846:         $size = 4;
1.283     albertel 2847:         if (scalar(keys(%$hash))<4) {
                   2848:             $size = scalar(keys(%$hash));
1.191     matthew  2849:         }
                   2850:     }
1.734     bisitz   2851:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2852:     my @order;
1.506     raeburn  2853:     if (ref($order) eq 'ARRAY')  {
                   2854:         @order = @{$order};
                   2855:     } else {
                   2856:         @order = sort(keys(%$hash));
1.501     banghart 2857:     }
                   2858:     if (exists($$hash{'select_form_order'})) {
                   2859:         @order = @{$$hash{'select_form_order'}};
                   2860:     }
                   2861:         
1.284     albertel 2862:     foreach my $key (@order) {
1.356     albertel 2863:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2864:         $output.='selected="selected" ' if ($selected{$key});
                   2865:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2866:     }
                   2867:     $output.="</select>\n";
                   2868:     return $output;
                   2869: }
                   2870: 
1.88      www      2871: #-------------------------------------------
                   2872: 
                   2873: =pod
                   2874: 
1.1254    raeburn  2875: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2876: 
                   2877: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2878: allow a user to select options from a ref to a hash containing:
                   2879: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2880: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2881: An optional arg -- $readonly -- if true will cause the select form
                   2882: to be disabled, e.g., for the case where an instructor has a section-
                   2883: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2884: 
1.88      www      2885: See lonrights.pm for an example invocation and use.
                   2886: 
                   2887: =cut
                   2888: 
                   2889: #-------------------------------------------
                   2890: sub select_form {
1.1228    raeburn  2891:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2892:     return unless (ref($hashref) eq 'HASH');
                   2893:     if ($onchange) {
                   2894:         $onchange = ' onchange="'.$onchange.'"';
                   2895:     }
1.1228    raeburn  2896:     my $disabled;
                   2897:     if ($readonly) {
                   2898:         $disabled = ' disabled="disabled"';
                   2899:     }
                   2900:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2901:     my @keys;
1.970     raeburn  2902:     if (exists($hashref->{'select_form_order'})) {
                   2903: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2904:     } else {
1.970     raeburn  2905: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2906:     }
1.356     albertel 2907:     foreach my $key (@keys) {
                   2908:         $selectform.=
                   2909: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2910:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2911:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2912:     }
                   2913:     $selectform.="</select>";
                   2914:     return $selectform;
                   2915: }
                   2916: 
1.475     www      2917: # For display filters
                   2918: 
                   2919: sub display_filter {
1.1074    raeburn  2920:     my ($context) = @_;
1.475     www      2921:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2922:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2923:     my $phraseinput = 'hidden';
                   2924:     my $includeinput = 'hidden';
                   2925:     my ($checked,$includetypestext);
                   2926:     if ($env{'form.displayfilter'} eq 'containing') {
                   2927:         $phraseinput = 'text'; 
                   2928:         if ($context eq 'parmslog') {
                   2929:             $includeinput = 'checkbox';
                   2930:             if ($env{'form.includetypes'}) {
                   2931:                 $checked = ' checked="checked"';
                   2932:             }
                   2933:             $includetypestext = &mt('Include parameter types');
                   2934:         }
                   2935:     } else {
                   2936:         $includetypestext = '&nbsp;';
                   2937:     }
                   2938:     my ($additional,$secondid,$thirdid);
                   2939:     if ($context eq 'parmslog') {
                   2940:         $additional = 
                   2941:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2942:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2943:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2944:             '</label>';
                   2945:         $secondid = 'includetypes';
                   2946:         $thirdid = 'includetypestext';
                   2947:     }
                   2948:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2949:                                                     '$secondid','$thirdid')";
                   2950:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2951: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2952: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2953: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2954:            &mt('Filter: [_1]',
1.477     www      2955: 	   &select_form($env{'form.displayfilter'},
                   2956: 			'displayfilter',
1.970     raeburn  2957: 			{'currentfolder' => 'Current folder/page',
1.477     www      2958: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2959: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2960: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2961:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2962:                          '" />'.$additional;
                   2963: }
                   2964: 
                   2965: sub display_filter_js {
                   2966:     my $includetext = &mt('Include parameter types');
                   2967:     return <<"ENDJS";
                   2968:   
                   2969: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2970:     var firstType = 'hidden';
                   2971:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2972:         firstType = 'text';
                   2973:     }
                   2974:     firstObject = document.getElementById(firstid);
                   2975:     if (typeof(firstObject) == 'object') {
                   2976:         if (firstObject.type != firstType) {
                   2977:             changeInputType(firstObject,firstType);
                   2978:         }
                   2979:     }
                   2980:     if (context == 'parmslog') {
                   2981:         var secondType = 'hidden';
                   2982:         if (firstType == 'text') {
                   2983:             secondType = 'checkbox';
                   2984:         }
                   2985:         secondObject = document.getElementById(secondid);  
                   2986:         if (typeof(secondObject) == 'object') {
                   2987:             if (secondObject.type != secondType) {
                   2988:                 changeInputType(secondObject,secondType);
                   2989:             }
                   2990:         }
                   2991:         var textItem = document.getElementById(thirdid);
                   2992:         var currtext = textItem.innerHTML;
                   2993:         var newtext;
                   2994:         if (firstType == 'text') {
                   2995:             newtext = '$includetext';
                   2996:         } else {
                   2997:             newtext = '&nbsp;';
                   2998:         }
                   2999:         if (currtext != newtext) {
                   3000:             textItem.innerHTML = newtext;
                   3001:         }
                   3002:     }
                   3003:     return;
                   3004: }
                   3005: 
                   3006: function changeInputType(oldObject,newType) {
                   3007:     var newObject = document.createElement('input');
                   3008:     newObject.type = newType;
                   3009:     if (oldObject.size) {
                   3010:         newObject.size = oldObject.size;
                   3011:     }
                   3012:     if (oldObject.value) {
                   3013:         newObject.value = oldObject.value;
                   3014:     }
                   3015:     if (oldObject.name) {
                   3016:         newObject.name = oldObject.name;
                   3017:     }
                   3018:     if (oldObject.id) {
                   3019:         newObject.id = oldObject.id;
                   3020:     }
                   3021:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   3022:     return;
                   3023: }
                   3024: 
                   3025: ENDJS
1.475     www      3026: }
                   3027: 
1.167     www      3028: sub gradeleveldescription {
                   3029:     my $gradelevel=shift;
                   3030:     my %gradelevels=(0 => 'Not specified',
                   3031: 		     1 => 'Grade 1',
                   3032: 		     2 => 'Grade 2',
                   3033: 		     3 => 'Grade 3',
                   3034: 		     4 => 'Grade 4',
                   3035: 		     5 => 'Grade 5',
                   3036: 		     6 => 'Grade 6',
                   3037: 		     7 => 'Grade 7',
                   3038: 		     8 => 'Grade 8',
                   3039: 		     9 => 'Grade 9',
                   3040: 		     10 => 'Grade 10',
                   3041: 		     11 => 'Grade 11',
                   3042: 		     12 => 'Grade 12',
                   3043: 		     13 => 'Grade 13',
                   3044: 		     14 => '100 Level',
                   3045: 		     15 => '200 Level',
                   3046: 		     16 => '300 Level',
                   3047: 		     17 => '400 Level',
                   3048: 		     18 => 'Graduate Level');
                   3049:     return &mt($gradelevels{$gradelevel});
                   3050: }
                   3051: 
1.163     www      3052: sub select_level_form {
                   3053:     my ($deflevel,$name)=@_;
                   3054:     unless ($deflevel) { $deflevel=0; }
1.167     www      3055:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   3056:     for (my $i=0; $i<=18; $i++) {
                   3057:         $selectform.="<option value=\"$i\" ".
1.253     albertel 3058:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      3059:                 ">".&gradeleveldescription($i)."</option>\n";
                   3060:     }
                   3061:     $selectform.="</select>";
                   3062:     return $selectform;
1.163     www      3063: }
1.167     www      3064: 
1.35      matthew  3065: #-------------------------------------------
                   3066: 
1.45      matthew  3067: =pod
                   3068: 
1.1256    raeburn  3069: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  3070: 
                   3071: Returns a string containing a <select name='$name' size='1'> form to 
                   3072: allow a user to select the domain to preform an operation in.  
                   3073: See loncreateuser.pm for an example invocation and use.
                   3074: 
1.90      www      3075: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   3076: selected");
                   3077: 
1.743     raeburn  3078: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   3079: 
1.910     raeburn  3080: 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.
                   3081: 
1.1121    raeburn  3082: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   3083: 
                   3084: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  3085: 
1.1256    raeburn  3086: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   3087: 
1.35      matthew  3088: =cut
                   3089: 
                   3090: #-------------------------------------------
1.34      matthew  3091: sub select_dom_form {
1.1256    raeburn  3092:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  3093:     if ($onchange) {
1.874     raeburn  3094:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  3095:     }
1.1256    raeburn  3096:     if ($disabled) {
                   3097:         $disabled = ' disabled="disabled"';
                   3098:     }
1.1121    raeburn  3099:     my (@domains,%exclude);
1.910     raeburn  3100:     if (ref($incdoms) eq 'ARRAY') {
                   3101:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   3102:     } else {
                   3103:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   3104:     }
1.90      www      3105:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  3106:     if (ref($excdoms) eq 'ARRAY') {
                   3107:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   3108:     }
1.1256    raeburn  3109:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 3110:     foreach my $dom (@domains) {
1.1121    raeburn  3111:         next if ($exclude{$dom});
1.356     albertel 3112:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  3113:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   3114:         if ($showdomdesc) {
                   3115:             if ($dom ne '') {
                   3116:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3117:                 if ($domdesc ne '') {
                   3118:                     $selectdomain .= ' ('.$domdesc.')';
                   3119:                 }
                   3120:             } 
                   3121:         }
                   3122:         $selectdomain .= "</option>\n";
1.34      matthew  3123:     }
                   3124:     $selectdomain.="</select>";
                   3125:     return $selectdomain;
                   3126: }
                   3127: 
1.35      matthew  3128: #-------------------------------------------
                   3129: 
1.45      matthew  3130: =pod
                   3131: 
1.648     raeburn  3132: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  3133: 
1.586     raeburn  3134: input: 4 arguments (two required, two optional) - 
                   3135:     $domain - domain of new user
                   3136:     $name - name of form element
                   3137:     $default - Value of 'default' causes a default item to be first 
                   3138:                             option, and selected by default. 
                   3139:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   3140:                             if 1 server found, or default, if 0 found.
1.594     raeburn  3141: output: returns 2 items: 
1.586     raeburn  3142: (a) form element which contains either:
                   3143:    (i) <select name="$name">
                   3144:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   3145:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   3146:        </select>
                   3147:        form item if there are multiple library servers in $domain, or
                   3148:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   3149:        if there is only one library server in $domain.
                   3150: 
                   3151: (b) number of library servers found.
                   3152: 
                   3153: See loncreateuser.pm for example of use.
1.35      matthew  3154: 
                   3155: =cut
                   3156: 
                   3157: #-------------------------------------------
1.586     raeburn  3158: sub home_server_form_item {
                   3159:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3160:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3161:     my $result;
                   3162:     my $numlib = keys(%servers);
                   3163:     if ($numlib > 1) {
                   3164:         $result .= '<select name="'.$name.'" />'."\n";
                   3165:         if ($default) {
1.804     bisitz   3166:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3167:                        '</option>'."\n";
                   3168:         }
                   3169:         foreach my $hostid (sort(keys(%servers))) {
                   3170:             $result.= '<option value="'.$hostid.'">'.
                   3171: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3172:         }
                   3173:         $result .= '</select>'."\n";
                   3174:     } elsif ($numlib == 1) {
                   3175:         my $hostid;
                   3176:         foreach my $item (keys(%servers)) {
                   3177:             $hostid = $item;
                   3178:         }
                   3179:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3180:                    $hostid.'" />';
                   3181:                    if (!$hide) {
                   3182:                        $result .= $hostid.' '.$servers{$hostid};
                   3183:                    }
                   3184:                    $result .= "\n";
                   3185:     } elsif ($default) {
                   3186:         $result .= '<input type="hidden" name="'.$name.
                   3187:                    '" value="default" />';
                   3188:                    if (!$hide) {
                   3189:                        $result .= &mt('default');
                   3190:                    }
                   3191:                    $result .= "\n";
1.33      matthew  3192:     }
1.586     raeburn  3193:     return ($result,$numlib);
1.33      matthew  3194: }
1.112     bowersj2 3195: 
                   3196: =pod
                   3197: 
1.534     albertel 3198: =back 
                   3199: 
1.112     bowersj2 3200: =cut
1.87      matthew  3201: 
                   3202: ###############################################################
1.112     bowersj2 3203: ##                  Decoding User Agent                      ##
1.87      matthew  3204: ###############################################################
                   3205: 
                   3206: =pod
                   3207: 
1.112     bowersj2 3208: =head1 Decoding the User Agent
                   3209: 
                   3210: =over 4
                   3211: 
                   3212: =item * &decode_user_agent()
1.87      matthew  3213: 
                   3214: Inputs: $r
                   3215: 
                   3216: Outputs:
                   3217: 
                   3218: =over 4
                   3219: 
1.112     bowersj2 3220: =item * $httpbrowser
1.87      matthew  3221: 
1.112     bowersj2 3222: =item * $clientbrowser
1.87      matthew  3223: 
1.112     bowersj2 3224: =item * $clientversion
1.87      matthew  3225: 
1.112     bowersj2 3226: =item * $clientmathml
1.87      matthew  3227: 
1.112     bowersj2 3228: =item * $clientunicode
1.87      matthew  3229: 
1.112     bowersj2 3230: =item * $clientos
1.87      matthew  3231: 
1.1137    raeburn  3232: =item * $clientmobile
                   3233: 
1.1141    raeburn  3234: =item * $clientinfo
                   3235: 
1.1194    raeburn  3236: =item * $clientosversion
                   3237: 
1.87      matthew  3238: =back
                   3239: 
1.157     matthew  3240: =back 
                   3241: 
1.87      matthew  3242: =cut
                   3243: 
                   3244: ###############################################################
                   3245: ###############################################################
                   3246: sub decode_user_agent {
1.247     albertel 3247:     my ($r)=@_;
1.87      matthew  3248:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3249:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3250:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3251:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3252:     my $clientbrowser='unknown';
                   3253:     my $clientversion='0';
                   3254:     my $clientmathml='';
                   3255:     my $clientunicode='0';
1.1137    raeburn  3256:     my $clientmobile=0;
1.1194    raeburn  3257:     my $clientosversion='';
1.87      matthew  3258:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3259:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3260: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3261: 	    $clientbrowser=$bname;
                   3262:             $httpbrowser=~/$vreg/i;
                   3263: 	    $clientversion=$1;
                   3264:             $clientmathml=($clientversion>=$minv);
                   3265:             $clientunicode=($clientversion>=$univ);
                   3266: 	}
                   3267:     }
                   3268:     my $clientos='unknown';
1.1141    raeburn  3269:     my $clientinfo;
1.87      matthew  3270:     if (($httpbrowser=~/linux/i) ||
                   3271:         ($httpbrowser=~/unix/i) ||
                   3272:         ($httpbrowser=~/ux/i) ||
                   3273:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3274:     if (($httpbrowser=~/vax/i) ||
                   3275:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3276:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3277:     if (($httpbrowser=~/mac/i) ||
                   3278:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3279:     if ($httpbrowser=~/win/i) {
                   3280:         $clientos='win';
                   3281:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3282:             $clientosversion = $1;
                   3283:         }
                   3284:     }
1.87      matthew  3285:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3286:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3287:         $clientmobile=lc($1);
                   3288:     }
1.1141    raeburn  3289:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3290:         $clientinfo = 'firefox-'.$1;
                   3291:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3292:         $clientinfo = 'chromeframe-'.$1;
                   3293:     }
1.87      matthew  3294:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3295:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3296:             $clientosversion);
1.87      matthew  3297: }
                   3298: 
1.32      matthew  3299: ###############################################################
                   3300: ##    Authentication changing form generation subroutines    ##
                   3301: ###############################################################
                   3302: ##
                   3303: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3304: ## hash, and have reasonable default values.
                   3305: ##
                   3306: ##    formname = the name given in the <form> tag.
1.35      matthew  3307: #-------------------------------------------
                   3308: 
1.45      matthew  3309: =pod
                   3310: 
1.112     bowersj2 3311: =head1 Authentication Routines
                   3312: 
                   3313: =over 4
                   3314: 
1.648     raeburn  3315: =item * &authform_xxxxxx()
1.35      matthew  3316: 
                   3317: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3318: handle some of the conveniences required for authentication forms.  
                   3319: This is not an optimal method, but it works.  
                   3320: 
                   3321: =over 4
                   3322: 
1.112     bowersj2 3323: =item * authform_header
1.35      matthew  3324: 
1.112     bowersj2 3325: =item * authform_authorwarning
1.35      matthew  3326: 
1.112     bowersj2 3327: =item * authform_nochange
1.35      matthew  3328: 
1.112     bowersj2 3329: =item * authform_kerberos
1.35      matthew  3330: 
1.112     bowersj2 3331: =item * authform_internal
1.35      matthew  3332: 
1.112     bowersj2 3333: =item * authform_filesystem
1.35      matthew  3334: 
1.1310    raeburn  3335: =item * authform_lti
                   3336: 
1.35      matthew  3337: =back
                   3338: 
1.648     raeburn  3339: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3340: 
1.35      matthew  3341: =cut
                   3342: 
                   3343: #-------------------------------------------
1.32      matthew  3344: sub authform_header{  
                   3345:     my %in = (
                   3346:         formname => 'cu',
1.80      albertel 3347:         kerb_def_dom => '',
1.32      matthew  3348:         @_,
                   3349:     );
                   3350:     $in{'formname'} = 'document.' . $in{'formname'};
                   3351:     my $result='';
1.80      albertel 3352: 
                   3353: #---------------------------------------------- Code for upper case translation
                   3354:     my $Javascript_toUpperCase;
                   3355:     unless ($in{kerb_def_dom}) {
                   3356:         $Javascript_toUpperCase =<<"END";
                   3357:         switch (choice) {
                   3358:            case 'krb': currentform.elements[choicearg].value =
                   3359:                currentform.elements[choicearg].value.toUpperCase();
                   3360:                break;
                   3361:            default:
                   3362:         }
                   3363: END
                   3364:     } else {
                   3365:         $Javascript_toUpperCase = "";
                   3366:     }
                   3367: 
1.165     raeburn  3368:     my $radioval = "'nochange'";
1.591     raeburn  3369:     if (defined($in{'curr_authtype'})) {
                   3370:         if ($in{'curr_authtype'} ne '') {
                   3371:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3372:         }
1.174     matthew  3373:     }
1.165     raeburn  3374:     my $argfield = 'null';
1.591     raeburn  3375:     if (defined($in{'mode'})) {
1.165     raeburn  3376:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3377:             if (defined($in{'curr_autharg'})) {
                   3378:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3379:                     $argfield = "'$in{'curr_autharg'}'";
                   3380:                 }
                   3381:             }
                   3382:         }
                   3383:     }
                   3384: 
1.32      matthew  3385:     $result.=<<"END";
                   3386: var current = new Object();
1.165     raeburn  3387: current.radiovalue = $radioval;
                   3388: current.argfield = $argfield;
1.32      matthew  3389: 
                   3390: function changed_radio(choice,currentform) {
                   3391:     var choicearg = choice + 'arg';
                   3392:     // If a radio button in changed, we need to change the argfield
                   3393:     if (current.radiovalue != choice) {
                   3394:         current.radiovalue = choice;
                   3395:         if (current.argfield != null) {
                   3396:             currentform.elements[current.argfield].value = '';
                   3397:         }
                   3398:         if (choice == 'nochange') {
                   3399:             current.argfield = null;
                   3400:         } else {
                   3401:             current.argfield = choicearg;
                   3402:             switch(choice) {
                   3403:                 case 'krb': 
                   3404:                     currentform.elements[current.argfield].value = 
                   3405:                         "$in{'kerb_def_dom'}";
                   3406:                 break;
                   3407:               default:
                   3408:                 break;
                   3409:             }
                   3410:         }
                   3411:     }
                   3412:     return;
                   3413: }
1.22      www      3414: 
1.32      matthew  3415: function changed_text(choice,currentform) {
                   3416:     var choicearg = choice + 'arg';
                   3417:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3418:         $Javascript_toUpperCase
1.32      matthew  3419:         // clear old field
                   3420:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3421:             currentform.elements[current.argfield].value = '';
                   3422:         }
                   3423:         current.argfield = choicearg;
                   3424:     }
                   3425:     set_auth_radio_buttons(choice,currentform);
                   3426:     return;
1.20      www      3427: }
1.32      matthew  3428: 
                   3429: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3430:     var numauthchoices = currentform.login.length;
                   3431:     if (typeof numauthchoices  == "undefined") {
                   3432:         return;
                   3433:     } 
1.32      matthew  3434:     var i=0;
1.986     raeburn  3435:     while (i < numauthchoices) {
1.32      matthew  3436:         if (currentform.login[i].value == newvalue) { break; }
                   3437:         i++;
                   3438:     }
1.986     raeburn  3439:     if (i == numauthchoices) {
1.32      matthew  3440:         return;
                   3441:     }
                   3442:     current.radiovalue = newvalue;
                   3443:     currentform.login[i].checked = true;
                   3444:     return;
                   3445: }
                   3446: END
                   3447:     return $result;
                   3448: }
                   3449: 
1.1106    raeburn  3450: sub authform_authorwarning {
1.32      matthew  3451:     my $result='';
1.144     matthew  3452:     $result='<i>'.
                   3453:         &mt('As a general rule, only authors or co-authors should be '.
                   3454:             'filesystem authenticated '.
                   3455:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3456:     return $result;
                   3457: }
                   3458: 
1.1106    raeburn  3459: sub authform_nochange {
1.32      matthew  3460:     my %in = (
                   3461:               formname => 'document.cu',
                   3462:               kerb_def_dom => 'MSU.EDU',
                   3463:               @_,
                   3464:           );
1.1106    raeburn  3465:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3466:     my $result;
1.1104    raeburn  3467:     if (!$authnum) {
1.1105    raeburn  3468:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3469:     } else {
                   3470:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3471:                   '<input type="radio" name="login" value="nochange" '.
                   3472:                   'checked="checked" onclick="'.
1.281     albertel 3473:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3474: 	    '</label>';
1.586     raeburn  3475:     }
1.32      matthew  3476:     return $result;
                   3477: }
                   3478: 
1.591     raeburn  3479: sub authform_kerberos {
1.32      matthew  3480:     my %in = (
                   3481:               formname => 'document.cu',
                   3482:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3483:               kerb_def_auth => 'krb4',
1.32      matthew  3484:               @_,
                   3485:               );
1.586     raeburn  3486:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3487:         $autharg,$jscall,$disabled);
1.1106    raeburn  3488:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3489:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3490:        $check5 = ' checked="checked"';
1.80      albertel 3491:     } else {
1.772     bisitz   3492:        $check4 = ' checked="checked"';
1.80      albertel 3493:     }
1.1259    raeburn  3494:     if ($in{'readonly'}) {
                   3495:         $disabled = ' disabled="disabled"';
                   3496:     }
1.165     raeburn  3497:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3498:     if (defined($in{'curr_authtype'})) {
                   3499:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3500:             $krbcheck = ' checked="checked"';
1.623     raeburn  3501:             if (defined($in{'mode'})) {
                   3502:                 if ($in{'mode'} eq 'modifyuser') {
                   3503:                     $krbcheck = '';
                   3504:                 }
                   3505:             }
1.591     raeburn  3506:             if (defined($in{'curr_kerb_ver'})) {
                   3507:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3508:                     $check5 = ' checked="checked"';
1.591     raeburn  3509:                     $check4 = '';
                   3510:                 } else {
1.772     bisitz   3511:                     $check4 = ' checked="checked"';
1.591     raeburn  3512:                     $check5 = '';
                   3513:                 }
1.586     raeburn  3514:             }
1.591     raeburn  3515:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3516:                 $krbarg = $in{'curr_autharg'};
                   3517:             }
1.586     raeburn  3518:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3519:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3520:                     $result = 
                   3521:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3522:         $in{'curr_autharg'},$krbver);
                   3523:                 } else {
                   3524:                     $result =
                   3525:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3526:                 }
                   3527:                 return $result; 
                   3528:             }
                   3529:         }
                   3530:     } else {
                   3531:         if ($authnum == 1) {
1.784     bisitz   3532:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3533:         }
                   3534:     }
1.586     raeburn  3535:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3536:         return;
1.587     raeburn  3537:     } elsif ($authtype eq '') {
1.591     raeburn  3538:         if (defined($in{'mode'})) {
1.587     raeburn  3539:             if ($in{'mode'} eq 'modifycourse') {
                   3540:                 if ($authnum == 1) {
1.1259    raeburn  3541:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3542:                 }
                   3543:             }
                   3544:         }
1.586     raeburn  3545:     }
                   3546:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3547:     if ($authtype eq '') {
                   3548:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3549:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3550:                     $krbcheck.$disabled.' />';
1.586     raeburn  3551:     }
                   3552:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3553:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3554:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3555:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3556:          $in{'curr_authtype'} eq 'krb4')) {
                   3557:         $result .= &mt
1.144     matthew  3558:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3559:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3560:          '<label>'.$authtype,
1.281     albertel 3561:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3562:              'value="'.$krbarg.'" '.
1.1259    raeburn  3563:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3564:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3565:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3566: 	 '</label>');
1.586     raeburn  3567:     } elsif ($can_assign{'krb4'}) {
                   3568:         $result .= &mt
                   3569:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3570:          '[_3] Version 4 [_4]',
                   3571:          '<label>'.$authtype,
                   3572:          '</label><input type="text" size="10" name="krbarg" '.
                   3573:              'value="'.$krbarg.'" '.
1.1259    raeburn  3574:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3575:          '<label><input type="hidden" name="krbver" value="4" />',
                   3576:          '</label>');
                   3577:     } elsif ($can_assign{'krb5'}) {
                   3578:         $result .= &mt
                   3579:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3580:          '[_3] Version 5 [_4]',
                   3581:          '<label>'.$authtype,
                   3582:          '</label><input type="text" size="10" name="krbarg" '.
                   3583:              'value="'.$krbarg.'" '.
1.1259    raeburn  3584:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3585:          '<label><input type="hidden" name="krbver" value="5" />',
                   3586:          '</label>');
                   3587:     }
1.32      matthew  3588:     return $result;
                   3589: }
                   3590: 
1.1106    raeburn  3591: sub authform_internal {
1.586     raeburn  3592:     my %in = (
1.32      matthew  3593:                 formname => 'document.cu',
                   3594:                 kerb_def_dom => 'MSU.EDU',
                   3595:                 @_,
                   3596:                 );
1.1259    raeburn  3597:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3598:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3599:     if ($in{'readonly'}) {
                   3600:         $disabled = ' disabled="disabled"';
                   3601:     }
1.591     raeburn  3602:     if (defined($in{'curr_authtype'})) {
                   3603:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3604:             if ($can_assign{'int'}) {
1.772     bisitz   3605:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3606:                 if (defined($in{'mode'})) {
                   3607:                     if ($in{'mode'} eq 'modifyuser') {
                   3608:                         $intcheck = '';
                   3609:                     }
                   3610:                 }
1.591     raeburn  3611:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3612:                     $intarg = $in{'curr_autharg'};
                   3613:                 }
                   3614:             } else {
                   3615:                 $result = &mt('Currently internally authenticated.');
                   3616:                 return $result;
1.165     raeburn  3617:             }
                   3618:         }
1.586     raeburn  3619:     } else {
                   3620:         if ($authnum == 1) {
1.784     bisitz   3621:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3622:         }
                   3623:     }
                   3624:     if (!$can_assign{'int'}) {
                   3625:         return;
1.587     raeburn  3626:     } elsif ($authtype eq '') {
1.591     raeburn  3627:         if (defined($in{'mode'})) {
1.587     raeburn  3628:             if ($in{'mode'} eq 'modifycourse') {
                   3629:                 if ($authnum == 1) {
1.1259    raeburn  3630:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3631:                 }
                   3632:             }
                   3633:         }
1.165     raeburn  3634:     }
1.586     raeburn  3635:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3636:     if ($authtype eq '') {
                   3637:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3638:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3639:     }
1.605     bisitz   3640:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3641:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3642:     $result = &mt
1.144     matthew  3643:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3644:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3645:     $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  3646:     return $result;
                   3647: }
                   3648: 
1.1104    raeburn  3649: sub authform_local {
1.32      matthew  3650:     my %in = (
                   3651:               formname => 'document.cu',
                   3652:               kerb_def_dom => 'MSU.EDU',
                   3653:               @_,
                   3654:               );
1.1259    raeburn  3655:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3656:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3657:     if ($in{'readonly'}) {
                   3658:         $disabled = ' disabled="disabled"';
                   3659:     } 
1.591     raeburn  3660:     if (defined($in{'curr_authtype'})) {
                   3661:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3662:             if ($can_assign{'loc'}) {
1.772     bisitz   3663:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3664:                 if (defined($in{'mode'})) {
                   3665:                     if ($in{'mode'} eq 'modifyuser') {
                   3666:                         $loccheck = '';
                   3667:                     }
                   3668:                 }
1.591     raeburn  3669:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3670:                     $locarg = $in{'curr_autharg'};
                   3671:                 }
                   3672:             } else {
                   3673:                 $result = &mt('Currently using local (institutional) authentication.');
                   3674:                 return $result;
1.165     raeburn  3675:             }
                   3676:         }
1.586     raeburn  3677:     } else {
                   3678:         if ($authnum == 1) {
1.784     bisitz   3679:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3680:         }
                   3681:     }
                   3682:     if (!$can_assign{'loc'}) {
                   3683:         return;
1.587     raeburn  3684:     } elsif ($authtype eq '') {
1.591     raeburn  3685:         if (defined($in{'mode'})) {
1.587     raeburn  3686:             if ($in{'mode'} eq 'modifycourse') {
                   3687:                 if ($authnum == 1) {
1.1259    raeburn  3688:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3689:                 }
                   3690:             }
                   3691:         }
1.165     raeburn  3692:     }
1.586     raeburn  3693:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3694:     if ($authtype eq '') {
                   3695:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3696:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3697:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3698:     }
                   3699:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3700:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3701:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3702:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3703:     return $result;
                   3704: }
                   3705: 
1.1106    raeburn  3706: sub authform_filesystem {
1.32      matthew  3707:     my %in = (
                   3708:               formname => 'document.cu',
                   3709:               kerb_def_dom => 'MSU.EDU',
                   3710:               @_,
                   3711:               );
1.1259    raeburn  3712:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3713:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3714:     if ($in{'readonly'}) {
                   3715:         $disabled = ' disabled="disabled"';
                   3716:     }
1.591     raeburn  3717:     if (defined($in{'curr_authtype'})) {
                   3718:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3719:             if ($can_assign{'fsys'}) {
1.772     bisitz   3720:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3721:                 if (defined($in{'mode'})) {
                   3722:                     if ($in{'mode'} eq 'modifyuser') {
                   3723:                         $fsyscheck = '';
                   3724:                     }
                   3725:                 }
1.586     raeburn  3726:             } else {
                   3727:                 $result = &mt('Currently Filesystem Authenticated.');
                   3728:                 return $result;
1.1259    raeburn  3729:             }
1.586     raeburn  3730:         }
                   3731:     } else {
                   3732:         if ($authnum == 1) {
1.784     bisitz   3733:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3734:         }
                   3735:     }
                   3736:     if (!$can_assign{'fsys'}) {
                   3737:         return;
1.587     raeburn  3738:     } elsif ($authtype eq '') {
1.591     raeburn  3739:         if (defined($in{'mode'})) {
1.587     raeburn  3740:             if ($in{'mode'} eq 'modifycourse') {
                   3741:                 if ($authnum == 1) {
1.1259    raeburn  3742:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3743:                 }
                   3744:             }
                   3745:         }
1.586     raeburn  3746:     }
                   3747:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3748:     if ($authtype eq '') {
                   3749:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3750:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3751:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3752:     }
1.1310    raeburn  3753:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3754:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3755:     $result = &mt
1.144     matthew  3756:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3757:          '<label>'.$authtype,'</label>'.$autharg);
                   3758:     return $result;
                   3759: }
                   3760: 
                   3761: sub authform_lti {
                   3762:     my %in = (
                   3763:               formname => 'document.cu',
                   3764:               kerb_def_dom => 'MSU.EDU',
                   3765:               @_,
                   3766:               );
                   3767:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3768:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3769:     if ($in{'readonly'}) {
                   3770:         $disabled = ' disabled="disabled"';
                   3771:     }
                   3772:     if (defined($in{'curr_authtype'})) {
                   3773:         if ($in{'curr_authtype'} eq 'lti') {
                   3774:             if ($can_assign{'lti'}) {
                   3775:                 $lticheck = 'checked="checked" ';
                   3776:                 if (defined($in{'mode'})) {
                   3777:                     if ($in{'mode'} eq 'modifyuser') {
                   3778:                         $lticheck = '';
                   3779:                     }
                   3780:                 }
                   3781:             } else {
                   3782:                 $result = &mt('Currently LTI Authenticated.');
                   3783:                 return $result;
                   3784:             }
                   3785:         }
                   3786:     } else {
                   3787:         if ($authnum == 1) {
                   3788:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3789:         }
                   3790:     }
                   3791:     if (!$can_assign{'lti'}) {
                   3792:         return;
                   3793:     } elsif ($authtype eq '') {
                   3794:         if (defined($in{'mode'})) {
                   3795:             if ($in{'mode'} eq 'modifycourse') {
                   3796:                 if ($authnum == 1) {
                   3797:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3798:                 }
                   3799:             }
                   3800:         }
                   3801:     }
                   3802:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3803:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3804:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3805:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3806:                     $jscall.'"'.$disabled.' />';
                   3807:     }
                   3808:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3809:     if ($authtype) {
                   3810:         $result = &mt('[_1] LTI Authenticated',
                   3811:                       '<label>'.$authtype.'</label>'.$autharg);
                   3812:     } else {
                   3813:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3814:                   $autharg;
                   3815:     }
1.32      matthew  3816:     return $result;
                   3817: }
                   3818: 
1.586     raeburn  3819: sub get_assignable_auth {
                   3820:     my ($dom) = @_;
                   3821:     if ($dom eq '') {
                   3822:         $dom = $env{'request.role.domain'};
                   3823:     }
                   3824:     my %can_assign = (
                   3825:                           krb4 => 1,
                   3826:                           krb5 => 1,
                   3827:                           int  => 1,
                   3828:                           loc  => 1,
1.1310    raeburn  3829:                           lti  => 1,
1.586     raeburn  3830:                      );
                   3831:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3832:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3833:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3834:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3835:             my $context;
                   3836:             if ($env{'request.role'} =~ /^au/) {
                   3837:                 $context = 'author';
1.1259    raeburn  3838:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3839:                 $context = 'domain';
                   3840:             } elsif ($env{'request.course.id'}) {
                   3841:                 $context = 'course';
                   3842:             }
                   3843:             if ($context) {
                   3844:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3845:                    %can_assign = %{$authhash->{$context}}; 
                   3846:                 }
                   3847:             }
                   3848:         }
                   3849:     }
                   3850:     my $authnum = 0;
                   3851:     foreach my $key (keys(%can_assign)) {
                   3852:         if ($can_assign{$key}) {
                   3853:             $authnum ++;
                   3854:         }
                   3855:     }
                   3856:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3857:         $authnum --;
                   3858:     }
                   3859:     return ($authnum,%can_assign);
                   3860: }
                   3861: 
1.1331    raeburn  3862: sub check_passwd_rules {
                   3863:     my ($domain,$plainpass) = @_;
                   3864:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3865:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3866:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3867:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3868:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3869:             if ($passwdconf{'min'} > $min) {
                   3870:                 $min = $passwdconf{'min'};
                   3871:             }
1.1331    raeburn  3872:         }
                   3873:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3874:             $max = $passwdconf{'max'};
                   3875:         }
                   3876:         @chars = @{$passwdconf{'chars'}};
                   3877:     }
                   3878:     if (($min) && (length($plainpass) < $min)) {
                   3879:         push(@brokerule,'min');
                   3880:     }
                   3881:     if (($max) && (length($plainpass) > $max)) {
                   3882:         push(@brokerule,'max');
                   3883:     }
                   3884:     if (@chars) {
                   3885:         my %rules;
                   3886:         map { $rules{$_} = 1; } @chars;
                   3887:         if ($rules{'uc'}) {
                   3888:             unless ($plainpass =~ /[A-Z]/) {
                   3889:                 push(@brokerule,'uc');
                   3890:             }
                   3891:         }
                   3892:         if ($rules{'lc'}) {
1.1332    raeburn  3893:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3894:                 push(@brokerule,'lc');
                   3895:             }
                   3896:         }
                   3897:         if ($rules{'num'}) {
                   3898:             unless ($plainpass =~ /\d/) {
                   3899:                 push(@brokerule,'num');
                   3900:             }
                   3901:         }
                   3902:         if ($rules{'spec'}) {
                   3903:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3904:                 push(@brokerule,'spec');
                   3905:             }
                   3906:         }
                   3907:     }
                   3908:     if (@brokerule) {
                   3909:         my %rulenames = &Apache::lonlocal::texthash(
                   3910:             uc   => 'At least one upper case letter',
                   3911:             lc   => 'At least one lower case letter',
                   3912:             num  => 'At least one number',
                   3913:             spec => 'At least one non-alphanumeric',
                   3914:         );
                   3915:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3916:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3917:         $rulenames{'num'} .= ': 0123456789';
                   3918:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3919:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3920:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3921:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3922:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3923:             if (grep(/^$rule$/,@brokerule)) {
                   3924:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3925:             }
                   3926:         }
                   3927:         $warning .= '</ul>';
                   3928:     }
1.1332    raeburn  3929:     if (wantarray) {
                   3930:         return @brokerule;
                   3931:     }
1.1331    raeburn  3932:     return $warning;
                   3933: }
                   3934: 
1.1376    raeburn  3935: sub passwd_validation_js {
1.1377    raeburn  3936:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3937:     my (%passwdconf,$alertmsg);
                   3938:     if ($context eq 'linkprot') {
                   3939:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3940:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3941:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3942:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3943:             }
                   3944:         }
                   3945:         if ($id eq 'add') {
                   3946:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3947:         } elsif ($id =~ /^\d+$/) {
                   3948:             my $pos = $id+1;
                   3949:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3950:         } else {
                   3951:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3952:         }
                   3953:     } else {
                   3954:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3955:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3956:     }
1.1376    raeburn  3957:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3958:     $numrules = 0;
                   3959:     $min = $Apache::lonnet::passwdmin;
                   3960:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3961:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3962:             if ($passwdconf{'min'} > $min) {
                   3963:                 $min = $passwdconf{'min'};
                   3964:             }
                   3965:         }
                   3966:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3967:             $max = $passwdconf{'max'};
                   3968:             $numrules ++;
                   3969:         }
                   3970:         @chars = @{$passwdconf{'chars'}};
                   3971:         if (@chars) {
                   3972:             $numrules ++;
                   3973:         }
                   3974:     }
                   3975:     if ($min > 0) {
                   3976:         $numrules ++;
                   3977:     }
                   3978:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3979:         if ($min) {
                   3980:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3981:         }
                   3982:         if ($max) {
                   3983:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3984:         }
                   3985:         my (@charalerts,@charrules);
                   3986:         if (@chars) {
                   3987:             if (grep(/^uc$/,@chars)) {
                   3988:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3989:                 push(@charrules,'uc');
                   3990:             }
                   3991:             if (grep(/^lc$/,@chars)) {
                   3992:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3993:                 push(@charrules,'lc');
                   3994:             }
                   3995:             if (grep(/^num$/,@chars)) {
                   3996:                 push(@charalerts,&mt('contain at least one number'));
                   3997:                 push(@charrules,'num');
                   3998:             }
                   3999:             if (grep(/^spec$/,@chars)) {
                   4000:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   4001:                 push(@charrules,'spec');
                   4002:             }
                   4003:         }
                   4004:         $intargjs = qq|            var rulesmsg = '';\n|.
                   4005:                     qq|            var currpwval = $currpasswdval;\n|;
                   4006:             if ($min) {
                   4007:                 $intargjs .= qq|
                   4008:             if (currpwval.length < $min) {
                   4009:                 rulesmsg += ' - $alert{min}';
                   4010:             }
                   4011: |;
                   4012:             }
                   4013:             if ($max) {
                   4014:                 $intargjs .= qq|
                   4015:             if (currpwval.length > $max) {
                   4016:                 rulesmsg += ' - $alert{max}';
                   4017:             }
                   4018: |;
                   4019:             }
                   4020:             if (@chars > 0) {
                   4021:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   4022:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   4023:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   4024:                              qq|            var charrules = new Array($charrulestr);\n|.
                   4025:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   4026:                 my %rules;
                   4027:                 map { $rules{$_} = 1; } @chars;
                   4028:                 if ($rules{'uc'}) {
                   4029:                     $intargjs .= qq|
                   4030:             var ucRegExp = /[A-Z]/;
                   4031:             if (!ucRegExp.test(currpwval)) {
                   4032:                 brokerules.push('uc');
                   4033:             }
                   4034: |;
                   4035:                 }
                   4036:                 if ($rules{'lc'}) {
                   4037:                     $intargjs .= qq|
                   4038:             var lcRegExp = /[a-z]/;
                   4039:             if (!lcRegExp.test(currpwval)) {
                   4040:                 brokerules.push('lc');
                   4041:             }
                   4042: |;
                   4043:                 }
                   4044:                 if ($rules{'num'}) {
                   4045:                      $intargjs .= qq|
                   4046:             var numRegExp = /[0-9]/;
                   4047:             if (!numRegExp.test(currpwval)) {
                   4048:                 brokerules.push('num');
                   4049:             }
                   4050: |;
                   4051:                 }
                   4052:                 if ($rules{'spec'}) {
                   4053:                      $intargjs .= q|
                   4054:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   4055:             if (!specRegExp.test(currpwval)) {
                   4056:                 brokerules.push('spec');
                   4057:             }
                   4058: |;
                   4059:                 }
                   4060:                 $intargjs .= qq|
                   4061:             if (brokerules.length > 0) {
                   4062:                 for (var i=0; i<brokerules.length; i++) {
                   4063:                     for (var j=0; j<charrules.length; j++) {
                   4064:                         if (brokerules[i] == charrules[j]) {
                   4065:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   4066:                             break;
                   4067:                         }
                   4068:                     }
                   4069:                 }
                   4070:             }
                   4071: |;
                   4072:             }
                   4073:             $intargjs .= qq|
                   4074:             if (rulesmsg != '') {
                   4075:                 rulesmsg = '$alertmsg'+rulesmsg;
                   4076:                 alert(rulesmsg);
                   4077:                 return false;
                   4078:             }
                   4079: |;
                   4080:     }
                   4081:     return ($numrules,$intargjs);
                   4082: }
                   4083: 
1.80      albertel 4084: ###############################################################
                   4085: ##    Get Kerberos Defaults for Domain                 ##
                   4086: ###############################################################
                   4087: ##
                   4088: ## Returns default kerberos version and an associated argument
                   4089: ## as listed in file domain.tab. If not listed, provides
                   4090: ## appropriate default domain and kerberos version.
                   4091: ##
                   4092: #-------------------------------------------
                   4093: 
                   4094: =pod
                   4095: 
1.648     raeburn  4096: =item * &get_kerberos_defaults()
1.80      albertel 4097: 
                   4098: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  4099: version and domain. If not found, it defaults to version 4 and the 
                   4100: domain of the server.
1.80      albertel 4101: 
1.648     raeburn  4102: =over 4
                   4103: 
1.80      albertel 4104: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   4105: 
1.648     raeburn  4106: =back
                   4107: 
                   4108: =back
                   4109: 
1.80      albertel 4110: =cut
                   4111: 
                   4112: #-------------------------------------------
                   4113: sub get_kerberos_defaults {
                   4114:     my $domain=shift;
1.641     raeburn  4115:     my ($krbdef,$krbdefdom);
                   4116:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   4117:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   4118:         $krbdef = $domdefaults{'auth_def'};
                   4119:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   4120:     } else {
1.80      albertel 4121:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   4122:         my $krbdefdom=$1;
                   4123:         $krbdefdom=~tr/a-z/A-Z/;
                   4124:         $krbdef = "krb4";
                   4125:     }
                   4126:     return ($krbdef,$krbdefdom);
                   4127: }
1.112     bowersj2 4128: 
1.32      matthew  4129: 
1.46      matthew  4130: ###############################################################
                   4131: ##                Thesaurus Functions                        ##
                   4132: ###############################################################
1.20      www      4133: 
1.46      matthew  4134: =pod
1.20      www      4135: 
1.112     bowersj2 4136: =head1 Thesaurus Functions
                   4137: 
                   4138: =over 4
                   4139: 
1.648     raeburn  4140: =item * &initialize_keywords()
1.46      matthew  4141: 
                   4142: Initializes the package variable %Keywords if it is empty.  Uses the
                   4143: package variable $thesaurus_db_file.
                   4144: 
                   4145: =cut
                   4146: 
                   4147: ###################################################
                   4148: 
                   4149: sub initialize_keywords {
                   4150:     return 1 if (scalar keys(%Keywords));
                   4151:     # If we are here, %Keywords is empty, so fill it up
                   4152:     #   Make sure the file we need exists...
                   4153:     if (! -e $thesaurus_db_file) {
                   4154:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   4155:                                  " failed because it does not exist");
                   4156:         return 0;
                   4157:     }
                   4158:     #   Set up the hash as a database
                   4159:     my %thesaurus_db;
                   4160:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4161:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4162:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4163:                                  $thesaurus_db_file);
                   4164:         return 0;
                   4165:     } 
                   4166:     #  Get the average number of appearances of a word.
                   4167:     my $avecount = $thesaurus_db{'average.count'};
                   4168:     #  Put keywords (those that appear > average) into %Keywords
                   4169:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4170:         my ($count,undef) = split /:/,$data;
                   4171:         $Keywords{$word}++ if ($count > $avecount);
                   4172:     }
                   4173:     untie %thesaurus_db;
                   4174:     # Remove special values from %Keywords.
1.356     albertel 4175:     foreach my $value ('total.count','average.count') {
                   4176:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4177:   }
1.46      matthew  4178:     return 1;
                   4179: }
                   4180: 
                   4181: ###################################################
                   4182: 
                   4183: =pod
                   4184: 
1.648     raeburn  4185: =item * &keyword($word)
1.46      matthew  4186: 
                   4187: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4188: than the average number of times in the thesaurus database.  Calls 
                   4189: &initialize_keywords
                   4190: 
                   4191: =cut
                   4192: 
                   4193: ###################################################
1.20      www      4194: 
                   4195: sub keyword {
1.46      matthew  4196:     return if (!&initialize_keywords());
                   4197:     my $word=lc(shift());
                   4198:     $word=~s/\W//g;
                   4199:     return exists($Keywords{$word});
1.20      www      4200: }
1.46      matthew  4201: 
                   4202: ###############################################################
                   4203: 
                   4204: =pod 
1.20      www      4205: 
1.648     raeburn  4206: =item * &get_related_words()
1.46      matthew  4207: 
1.160     matthew  4208: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4209: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4210: will be returned.  The order of the words returned is determined by the
                   4211: database which holds them.
                   4212: 
                   4213: Uses global $thesaurus_db_file.
                   4214: 
1.1057    foxr     4215: 
1.46      matthew  4216: =cut
                   4217: 
                   4218: ###############################################################
                   4219: sub get_related_words {
                   4220:     my $keyword = shift;
                   4221:     my %thesaurus_db;
                   4222:     if (! -e $thesaurus_db_file) {
                   4223:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4224:                                  "failed because the file does not exist");
                   4225:         return ();
                   4226:     }
                   4227:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4228:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4229:         return ();
                   4230:     } 
                   4231:     my @Words=();
1.429     www      4232:     my $count=0;
1.46      matthew  4233:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4234: 	# The first element is the number of times
                   4235: 	# the word appears.  We do not need it now.
1.429     www      4236: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4237: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4238: 	my $threshold=$mostfrequentcount/10;
                   4239:         foreach my $possibleword (@RelatedWords) {
                   4240:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4241:             if ($wordcount>$threshold) {
                   4242: 		push(@Words,$word);
                   4243:                 $count++;
                   4244:                 if ($count>10) { last; }
                   4245: 	    }
1.20      www      4246:         }
                   4247:     }
1.46      matthew  4248:     untie %thesaurus_db;
                   4249:     return @Words;
1.14      harris41 4250: }
1.1090    foxr     4251: ###############################################################
                   4252: #
                   4253: #  Spell checking
                   4254: #
                   4255: 
                   4256: =pod
                   4257: 
1.1142    raeburn  4258: =back
                   4259: 
1.1090    foxr     4260: =head1 Spell checking
                   4261: 
                   4262: =over 4
                   4263: 
                   4264: =item * &check_spelling($wordlist $language)
                   4265: 
                   4266: Takes a string containing words and feeds it to an external
                   4267: spellcheck program via a pipeline. Returns a string containing
                   4268: them mis-spelled words.
                   4269: 
                   4270: Parameters:
                   4271: 
                   4272: =over 4
                   4273: 
                   4274: =item - $wordlist
                   4275: 
                   4276: String that will be fed into the spellcheck program.
                   4277: 
                   4278: =item - $language
                   4279: 
                   4280: Language string that specifies the language for which the spell
                   4281: check will be performed.
                   4282: 
                   4283: =back
                   4284: 
                   4285: =back
                   4286: 
                   4287: Note: This sub assumes that aspell is installed.
                   4288: 
                   4289: 
                   4290: =cut
                   4291: 
1.46      matthew  4292: 
1.1090    foxr     4293: sub check_spelling {
                   4294:     my ($wordlist, $language) = @_;
1.1091    foxr     4295:     my @misspellings;
                   4296:     
                   4297:     # Generate the speller and set the langauge.
                   4298:     # if explicitly selected:
1.1090    foxr     4299: 
1.1091    foxr     4300:     my $speller = Text::Aspell->new;
1.1090    foxr     4301:     if ($language) {
1.1091    foxr     4302: 	$speller->set_option('lang', $language);
1.1090    foxr     4303:     }
                   4304: 
1.1091    foxr     4305:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4306: 
1.1091    foxr     4307:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4308: 
1.1091    foxr     4309:     foreach my $word (@words) {
                   4310: 	if(! $speller->check($word)) {
                   4311: 	    push(@misspellings, $word);
1.1090    foxr     4312: 	}
                   4313:     }
1.1091    foxr     4314:     return join(' ', @misspellings);
                   4315:     
1.1090    foxr     4316: }
                   4317: 
1.61      www      4318: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4319: =pod
                   4320: 
1.112     bowersj2 4321: =head1 User Name Functions
                   4322: 
                   4323: =over 4
                   4324: 
1.648     raeburn  4325: =item * &plainname($uname,$udom,$first)
1.81      albertel 4326: 
1.112     bowersj2 4327: Takes a users logon name and returns it as a string in
1.226     albertel 4328: "first middle last generation" form 
                   4329: if $first is set to 'lastname' then it returns it as
                   4330: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4331: 
                   4332: =cut
1.61      www      4333: 
1.295     www      4334: 
1.81      albertel 4335: ###############################################################
1.61      www      4336: sub plainname {
1.226     albertel 4337:     my ($uname,$udom,$first)=@_;
1.537     albertel 4338:     return if (!defined($uname) || !defined($udom));
1.295     www      4339:     my %names=&getnames($uname,$udom);
1.226     albertel 4340:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4341: 					  $names{'middlename'},
                   4342: 					  $names{'lastname'},
                   4343: 					  $names{'generation'},$first);
                   4344:     $name=~s/^\s+//;
1.62      www      4345:     $name=~s/\s+$//;
                   4346:     $name=~s/\s+/ /g;
1.353     albertel 4347:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4348:     return $name;
1.61      www      4349: }
1.66      www      4350: 
                   4351: # -------------------------------------------------------------------- Nickname
1.81      albertel 4352: =pod
                   4353: 
1.648     raeburn  4354: =item * &nickname($uname,$udom)
1.81      albertel 4355: 
                   4356: Gets a users name and returns it as a string as
                   4357: 
                   4358: "&quot;nickname&quot;"
1.66      www      4359: 
1.81      albertel 4360: if the user has a nickname or
                   4361: 
                   4362: "first middle last generation"
                   4363: 
                   4364: if the user does not
                   4365: 
                   4366: =cut
1.66      www      4367: 
                   4368: sub nickname {
                   4369:     my ($uname,$udom)=@_;
1.537     albertel 4370:     return if (!defined($uname) || !defined($udom));
1.295     www      4371:     my %names=&getnames($uname,$udom);
1.68      albertel 4372:     my $name=$names{'nickname'};
1.66      www      4373:     if ($name) {
                   4374:        $name='&quot;'.$name.'&quot;'; 
                   4375:     } else {
                   4376:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4377: 	     $names{'lastname'}.' '.$names{'generation'};
                   4378:        $name=~s/\s+$//;
                   4379:        $name=~s/\s+/ /g;
                   4380:     }
                   4381:     return $name;
                   4382: }
                   4383: 
1.295     www      4384: sub getnames {
                   4385:     my ($uname,$udom)=@_;
1.537     albertel 4386:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4387:     if ($udom eq 'public' && $uname eq 'public') {
                   4388: 	return ('lastname' => &mt('Public'));
                   4389:     }
1.295     www      4390:     my $id=$uname.':'.$udom;
                   4391:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4392:     if ($cached) {
                   4393: 	return %{$names};
                   4394:     } else {
                   4395: 	my %loadnames=&Apache::lonnet::get('environment',
                   4396:                     ['firstname','middlename','lastname','generation','nickname'],
                   4397: 					 $udom,$uname);
                   4398: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4399: 	return %loadnames;
                   4400:     }
                   4401: }
1.61      www      4402: 
1.542     raeburn  4403: # -------------------------------------------------------------------- getemails
1.648     raeburn  4404: 
1.542     raeburn  4405: =pod
                   4406: 
1.648     raeburn  4407: =item * &getemails($uname,$udom)
1.542     raeburn  4408: 
                   4409: Gets a user's email information and returns it as a hash with keys:
                   4410: notification, critnotification, permanentemail
                   4411: 
                   4412: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4413: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4414:  
1.648     raeburn  4415: 
1.542     raeburn  4416: =cut
                   4417: 
1.648     raeburn  4418: 
1.466     albertel 4419: sub getemails {
                   4420:     my ($uname,$udom)=@_;
                   4421:     if ($udom eq 'public' && $uname eq 'public') {
                   4422: 	return;
                   4423:     }
1.467     www      4424:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4425:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4426:     my $id=$uname.':'.$udom;
                   4427:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4428:     if ($cached) {
                   4429: 	return %{$names};
                   4430:     } else {
                   4431: 	my %loadnames=&Apache::lonnet::get('environment',
                   4432:                     			   ['notification','critnotification',
                   4433: 					    'permanentemail'],
                   4434: 					   $udom,$uname);
                   4435: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4436: 	return %loadnames;
                   4437:     }
                   4438: }
                   4439: 
1.551     albertel 4440: sub flush_email_cache {
                   4441:     my ($uname,$udom)=@_;
                   4442:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4443:     if (!$uname) { $uname=$env{'user.name'};   }
                   4444:     return if ($udom eq 'public' && $uname eq 'public');
                   4445:     my $id=$uname.':'.$udom;
                   4446:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4447: }
                   4448: 
1.728     raeburn  4449: # -------------------------------------------------------------------- getlangs
                   4450: 
                   4451: =pod
                   4452: 
                   4453: =item * &getlangs($uname,$udom)
                   4454: 
                   4455: Gets a user's language preference and returns it as a hash with key:
                   4456: language.
                   4457: 
                   4458: =cut
                   4459: 
                   4460: 
                   4461: sub getlangs {
                   4462:     my ($uname,$udom) = @_;
                   4463:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4464:     if (!$uname) { $uname=$env{'user.name'};   }
                   4465:     my $id=$uname.':'.$udom;
                   4466:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4467:     if ($cached) {
                   4468:         return %{$langs};
                   4469:     } else {
                   4470:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4471:                                            $udom,$uname);
                   4472:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4473:         return %loadlangs;
                   4474:     }
                   4475: }
                   4476: 
                   4477: sub flush_langs_cache {
                   4478:     my ($uname,$udom)=@_;
                   4479:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4480:     if (!$uname) { $uname=$env{'user.name'};   }
                   4481:     return if ($udom eq 'public' && $uname eq 'public');
                   4482:     my $id=$uname.':'.$udom;
                   4483:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4484: }
                   4485: 
1.61      www      4486: # ------------------------------------------------------------------ Screenname
1.81      albertel 4487: 
                   4488: =pod
                   4489: 
1.648     raeburn  4490: =item * &screenname($uname,$udom)
1.81      albertel 4491: 
                   4492: Gets a users screenname and returns it as a string
                   4493: 
                   4494: =cut
1.61      www      4495: 
                   4496: sub screenname {
                   4497:     my ($uname,$udom)=@_;
1.258     albertel 4498:     if ($uname eq $env{'user.name'} &&
                   4499: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4500:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4501:     return $names{'screenname'};
1.62      www      4502: }
                   4503: 
1.212     albertel 4504: 
1.802     bisitz   4505: # ------------------------------------------------------------- Confirm Wrapper
                   4506: =pod
                   4507: 
1.1142    raeburn  4508: =item * &confirmwrapper($message)
1.802     bisitz   4509: 
                   4510: Wrap messages about completion of operation in box
                   4511: 
                   4512: =cut
                   4513: 
                   4514: sub confirmwrapper {
                   4515:     my ($message)=@_;
                   4516:     if ($message) {
                   4517:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4518:                .$message."\n"
                   4519:                .'</div>'."\n";
                   4520:     } else {
                   4521:         return $message;
                   4522:     }
                   4523: }
                   4524: 
1.62      www      4525: # ------------------------------------------------------------- Message Wrapper
                   4526: 
                   4527: sub messagewrapper {
1.369     www      4528:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4529:     return 
1.441     albertel 4530:         '<a href="/adm/email?compose=individual&amp;'.
                   4531:         'recname='.$username.'&amp;recdom='.$domain.
                   4532: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4533:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4534: }
1.802     bisitz   4535: 
1.74      www      4536: # --------------------------------------------------------------- Notes Wrapper
                   4537: 
                   4538: sub noteswrapper {
                   4539:     my ($link,$un,$do)=@_;
                   4540:     return 
1.896     amueller 4541: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4542: }
1.802     bisitz   4543: 
1.62      www      4544: # ------------------------------------------------------------- Aboutme Wrapper
                   4545: 
                   4546: sub aboutmewrapper {
1.1070    raeburn  4547:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4548:     if (!defined($username)  && !defined($domain)) {
                   4549:         return;
                   4550:     }
1.1096    raeburn  4551:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4552: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4553: }
                   4554: 
                   4555: # ------------------------------------------------------------ Syllabus Wrapper
                   4556: 
                   4557: sub syllabuswrapper {
1.707     bisitz   4558:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4559:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4560: }
1.14      harris41 4561: 
1.1397    raeburn  4562: # -----------------------------------------------------------------------------
                   4563: 
1.1396    raeburn  4564: sub aboutme_on {
                   4565:     my ($uname,$udom)=@_;
                   4566:     unless ($uname) { $uname=$env{'user.name'}; }
                   4567:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4568:     return if ($udom eq 'public' && $uname eq 'public');
                   4569:     my $hashkey=$uname.':'.$udom;
                   4570:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4571:     if ($cached) {
                   4572:         return $aboutme;
                   4573:     }
                   4574:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4575:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4576:     return $aboutme;
                   4577: }
                   4578: 
                   4579: sub devalidate_aboutme_cache {
                   4580:     my ($uname,$udom)=@_;
                   4581:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4582:     if (!$uname) { $uname=$env{'user.name'};   }
                   4583:     return if ($udom eq 'public' && $uname eq 'public');
                   4584:     my $id=$uname.':'.$udom;
                   4585:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4586: }
                   4587: 
1.208     matthew  4588: sub track_student_link {
1.887     raeburn  4589:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4590:     my $link ="/adm/trackstudent?";
1.208     matthew  4591:     my $title = 'View recent activity';
                   4592:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4593:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4594:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4595:         $title .= ' of this student';
1.268     albertel 4596:     } 
1.208     matthew  4597:     if (defined($target) && $target !~ /^\s*$/) {
                   4598:         $target = qq{target="$target"};
                   4599:     } else {
                   4600:         $target = '';
                   4601:     }
1.268     albertel 4602:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4603:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4604:     $title = &mt($title);
                   4605:     $linktext = &mt($linktext);
1.448     albertel 4606:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4607: 	&help_open_topic('View_recent_activity');
1.208     matthew  4608: }
                   4609: 
1.781     raeburn  4610: sub slot_reservations_link {
                   4611:     my ($linktext,$sname,$sdom,$target) = @_;
                   4612:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4613:     my $title = 'View slot reservation history';
                   4614:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4615:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4616:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4617:         $title .= ' of this student';
                   4618:     }
                   4619:     if (defined($target) && $target !~ /^\s*$/) {
                   4620:         $target = qq{target="$target"};
                   4621:     } else {
                   4622:         $target = '';
                   4623:     }
                   4624:     $title = &mt($title);
                   4625:     $linktext = &mt($linktext);
                   4626:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4627: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4628: 
                   4629: }
                   4630: 
1.508     www      4631: # ===================================================== Display a student photo
                   4632: 
                   4633: 
1.509     albertel 4634: sub student_image_tag {
1.508     www      4635:     my ($domain,$user)=@_;
                   4636:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4637:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4638: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4639:     } else {
                   4640: 	return '';
                   4641:     }
                   4642: }
                   4643: 
1.112     bowersj2 4644: =pod
                   4645: 
                   4646: =back
                   4647: 
                   4648: =head1 Access .tab File Data
                   4649: 
                   4650: =over 4
                   4651: 
1.648     raeburn  4652: =item * &languageids() 
1.112     bowersj2 4653: 
                   4654: returns list of all language ids
                   4655: 
                   4656: =cut
                   4657: 
1.14      harris41 4658: sub languageids {
1.16      harris41 4659:     return sort(keys(%language));
1.14      harris41 4660: }
                   4661: 
1.112     bowersj2 4662: =pod
                   4663: 
1.648     raeburn  4664: =item * &languagedescription() 
1.112     bowersj2 4665: 
                   4666: returns description of a specified language id
                   4667: 
                   4668: =cut
                   4669: 
1.14      harris41 4670: sub languagedescription {
1.125     www      4671:     my $code=shift;
                   4672:     return  ($supported_language{$code}?'* ':'').
                   4673:             $language{$code}.
1.126     www      4674: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4675: }
                   4676: 
1.1048    foxr     4677: =pod
                   4678: 
                   4679: =item * &plainlanguagedescription
                   4680: 
                   4681: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4682: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4683: 
                   4684: =cut
                   4685: 
1.145     www      4686: sub plainlanguagedescription {
                   4687:     my $code=shift;
                   4688:     return $language{$code};
                   4689: }
                   4690: 
1.1048    foxr     4691: =pod
                   4692: 
                   4693: =item * &supportedlanguagecode
                   4694: 
                   4695: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4696: code.
                   4697: 
                   4698: =cut
                   4699: 
1.145     www      4700: sub supportedlanguagecode {
                   4701:     my $code=shift;
                   4702:     return $supported_language{$code};
1.97      www      4703: }
                   4704: 
1.112     bowersj2 4705: =pod
                   4706: 
1.1048    foxr     4707: =item * &latexlanguage()
                   4708: 
                   4709: Given a language key code returns the correspondnig language to use
                   4710: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4711: is no supported hyphenation for the language code.
                   4712: 
                   4713: =cut
                   4714: 
                   4715: sub latexlanguage {
                   4716:     my $code = shift;
                   4717:     return $latex_language{$code};
                   4718: }
                   4719: 
                   4720: =pod
                   4721: 
                   4722: =item * &latexhyphenation()
                   4723: 
                   4724: Same as above but what's supplied is the language as it might be stored
                   4725: in the metadata.
                   4726: 
                   4727: =cut
                   4728: 
                   4729: sub latexhyphenation {
                   4730:     my $key = shift;
                   4731:     return $latex_language_bykey{$key};
                   4732: }
                   4733: 
                   4734: =pod
                   4735: 
1.648     raeburn  4736: =item * &copyrightids() 
1.112     bowersj2 4737: 
                   4738: returns list of all copyrights
                   4739: 
                   4740: =cut
                   4741: 
                   4742: sub copyrightids {
                   4743:     return sort(keys(%cprtag));
                   4744: }
                   4745: 
                   4746: =pod
                   4747: 
1.648     raeburn  4748: =item * &copyrightdescription() 
1.112     bowersj2 4749: 
                   4750: returns description of a specified copyright id
                   4751: 
                   4752: =cut
                   4753: 
                   4754: sub copyrightdescription {
1.166     www      4755:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4756: }
1.197     matthew  4757: 
                   4758: =pod
                   4759: 
1.648     raeburn  4760: =item * &source_copyrightids() 
1.192     taceyjo1 4761: 
                   4762: returns list of all source copyrights
                   4763: 
                   4764: =cut
                   4765: 
                   4766: sub source_copyrightids {
                   4767:     return sort(keys(%scprtag));
                   4768: }
                   4769: 
                   4770: =pod
                   4771: 
1.648     raeburn  4772: =item * &source_copyrightdescription() 
1.192     taceyjo1 4773: 
                   4774: returns description of a specified source copyright id
                   4775: 
                   4776: =cut
                   4777: 
                   4778: sub source_copyrightdescription {
                   4779:     return &mt($scprtag{shift(@_)});
                   4780: }
1.112     bowersj2 4781: 
                   4782: =pod
                   4783: 
1.648     raeburn  4784: =item * &filecategories() 
1.112     bowersj2 4785: 
                   4786: returns list of all file categories
                   4787: 
                   4788: =cut
                   4789: 
                   4790: sub filecategories {
                   4791:     return sort(keys(%category_extensions));
                   4792: }
                   4793: 
                   4794: =pod
                   4795: 
1.648     raeburn  4796: =item * &filecategorytypes() 
1.112     bowersj2 4797: 
                   4798: returns list of file types belonging to a given file
                   4799: category
                   4800: 
                   4801: =cut
                   4802: 
                   4803: sub filecategorytypes {
1.356     albertel 4804:     my ($cat) = @_;
1.1248    raeburn  4805:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4806:         return @{$category_extensions{lc($cat)}};
                   4807:     } else {
                   4808:         return ();
                   4809:     }
1.112     bowersj2 4810: }
                   4811: 
                   4812: =pod
                   4813: 
1.648     raeburn  4814: =item * &fileembstyle() 
1.112     bowersj2 4815: 
                   4816: returns embedding style for a specified file type
                   4817: 
                   4818: =cut
                   4819: 
                   4820: sub fileembstyle {
                   4821:     return $fe{lc(shift(@_))};
1.169     www      4822: }
                   4823: 
1.351     www      4824: sub filemimetype {
                   4825:     return $fm{lc(shift(@_))};
                   4826: }
                   4827: 
1.169     www      4828: 
                   4829: sub filecategoryselect {
                   4830:     my ($name,$value)=@_;
1.189     matthew  4831:     return &select_form($value,$name,
1.970     raeburn  4832:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4833: }
                   4834: 
                   4835: =pod
                   4836: 
1.648     raeburn  4837: =item * &filedescription() 
1.112     bowersj2 4838: 
                   4839: returns description for a specified file type
                   4840: 
                   4841: =cut
                   4842: 
                   4843: sub filedescription {
1.188     matthew  4844:     my $file_description = $fd{lc(shift())};
                   4845:     $file_description =~ s:([\[\]]):~$1:g;
                   4846:     return &mt($file_description);
1.112     bowersj2 4847: }
                   4848: 
                   4849: =pod
                   4850: 
1.648     raeburn  4851: =item * &filedescriptionex() 
1.112     bowersj2 4852: 
                   4853: returns description for a specified file type with
                   4854: extra formatting
                   4855: 
                   4856: =cut
                   4857: 
                   4858: sub filedescriptionex {
                   4859:     my $ex=shift;
1.188     matthew  4860:     my $file_description = $fd{lc($ex)};
                   4861:     $file_description =~ s:([\[\]]):~$1:g;
                   4862:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4863: }
                   4864: 
                   4865: # End of .tab access
                   4866: =pod
                   4867: 
                   4868: =back
                   4869: 
                   4870: =cut
                   4871: 
                   4872: # ------------------------------------------------------------------ File Types
                   4873: sub fileextensions {
                   4874:     return sort(keys(%fe));
                   4875: }
                   4876: 
1.97      www      4877: # ----------------------------------------------------------- Display Languages
                   4878: # returns a hash with all desired display languages
                   4879: #
                   4880: 
                   4881: sub display_languages {
                   4882:     my %languages=();
1.695     raeburn  4883:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4884: 	$languages{$lang}=1;
1.97      www      4885:     }
                   4886:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4887:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4888: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4889: 	    $languages{$lang}=1;
1.97      www      4890:         }
                   4891:     }
                   4892:     return %languages;
1.14      harris41 4893: }
                   4894: 
1.582     albertel 4895: sub languages {
                   4896:     my ($possible_langs) = @_;
1.695     raeburn  4897:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4898:     if (!ref($possible_langs)) {
                   4899: 	if( wantarray ) {
                   4900: 	    return @preferred_langs;
                   4901: 	} else {
                   4902: 	    return $preferred_langs[0];
                   4903: 	}
                   4904:     }
                   4905:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4906:     my @preferred_possibilities;
                   4907:     foreach my $preferred_lang (@preferred_langs) {
                   4908: 	if (exists($possibilities{$preferred_lang})) {
                   4909: 	    push(@preferred_possibilities, $preferred_lang);
                   4910: 	}
                   4911:     }
                   4912:     if( wantarray ) {
                   4913: 	return @preferred_possibilities;
                   4914:     }
                   4915:     return $preferred_possibilities[0];
                   4916: }
                   4917: 
1.742     raeburn  4918: sub user_lang {
                   4919:     my ($touname,$toudom,$fromcid) = @_;
                   4920:     my @userlangs;
                   4921:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4922:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4923:                     $env{'course.'.$fromcid.'.languages'}));
                   4924:     } else {
                   4925:         my %langhash = &getlangs($touname,$toudom);
                   4926:         if ($langhash{'languages'} ne '') {
                   4927:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4928:         } else {
                   4929:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4930:             if ($domdefs{'lang_def'} ne '') {
                   4931:                 @userlangs = ($domdefs{'lang_def'});
                   4932:             }
                   4933:         }
                   4934:     }
                   4935:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4936:     my $user_lh = Apache::localize->get_handle(@languages);
                   4937:     return $user_lh;
                   4938: }
                   4939: 
                   4940: 
1.112     bowersj2 4941: ###############################################################
                   4942: ##               Student Answer Attempts                     ##
                   4943: ###############################################################
                   4944: 
                   4945: =pod
                   4946: 
                   4947: =head1 Alternate Problem Views
                   4948: 
                   4949: =over 4
                   4950: 
1.648     raeburn  4951: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4952:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4953: 
                   4954: Return string with previous attempt on problem. Arguments:
                   4955: 
                   4956: =over 4
                   4957: 
                   4958: =item * $symb: Problem, including path
                   4959: 
                   4960: =item * $username: username of the desired student
                   4961: 
                   4962: =item * $domain: domain of the desired student
1.14      harris41 4963: 
1.112     bowersj2 4964: =item * $course: Course ID
1.14      harris41 4965: 
1.112     bowersj2 4966: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4967:     something
1.14      harris41 4968: 
1.112     bowersj2 4969: =item * $regexp: if string matches this regexp, the string will be
                   4970:     sent to $gradesub
1.14      harris41 4971: 
1.112     bowersj2 4972: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4973: 
1.1199    raeburn  4974: =item * $usec: section of the desired student
                   4975: 
                   4976: =item * $identifier: counter for student (multiple students one problem) or 
                   4977:     problem (one student; whole sequence).
                   4978: 
1.112     bowersj2 4979: =back
1.14      harris41 4980: 
1.112     bowersj2 4981: The output string is a table containing all desired attempts, if any.
1.16      harris41 4982: 
1.112     bowersj2 4983: =cut
1.1       albertel 4984: 
                   4985: sub get_previous_attempt {
1.1199    raeburn  4986:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4987:   my $prevattempts='';
1.43      ng       4988:   no strict 'refs';
1.1       albertel 4989:   if ($symb) {
1.3       albertel 4990:     my (%returnhash)=
                   4991:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4992:     if ($returnhash{'version'}) {
                   4993:       my %lasthash=();
                   4994:       my $version;
                   4995:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4996:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4997:             if ($key =~ /\.rawrndseed$/) {
                   4998:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4999:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   5000:             } else {
                   5001:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   5002:             }
1.19      harris41 5003:         }
1.1       albertel 5004:       }
1.596     albertel 5005:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   5006:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  5007:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  5008:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 5009:       foreach my $key (sort(keys(%lasthash))) {
                   5010: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       5011: 	if ($#parts > 0) {
1.31      albertel 5012: 	  my $data=$parts[-1];
1.989     raeburn  5013:           next if ($data eq 'foilorder');
1.31      albertel 5014: 	  pop(@parts);
1.1010    www      5015:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  5016:           if ($data eq 'type') {
                   5017:               unless ($showsurv) {
                   5018:                   my $id = join(',',@parts);
                   5019:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  5020:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   5021:                       $lasthidden{$ign.'.'.$id} = 1;
                   5022:                   }
1.945     raeburn  5023:               }
1.1199    raeburn  5024:               if ($identifier ne '') {
                   5025:                   my $id = join(',',@parts);
                   5026:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   5027:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   5028:                       $hidestatus{$ign.'.'.$id} = 1;
                   5029:                   }
                   5030:               }
                   5031:           } elsif ($data eq 'regrader') {
                   5032:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  5033:                   my $id = join(',',@parts);
                   5034:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  5035:               }
1.1010    www      5036:           } 
1.31      albertel 5037: 	} else {
1.41      ng       5038: 	  if ($#parts == 0) {
                   5039: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   5040: 	  } else {
                   5041: 	    $prevattempts.='<th>'.$ign.'</th>';
                   5042: 	  }
1.31      albertel 5043: 	}
1.16      harris41 5044:       }
1.596     albertel 5045:       $prevattempts.=&end_data_table_header_row();
1.40      ng       5046:       if ($getattempt eq '') {
1.1199    raeburn  5047:         my (%solved,%resets,%probstatus);
1.1200    raeburn  5048:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   5049:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   5050:                 foreach my $id (keys(%regraded)) {
                   5051:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   5052:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   5053:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   5054:                         push(@{$resets{$id}},$version);
1.1199    raeburn  5055:                     }
                   5056:                 }
                   5057:             }
1.1200    raeburn  5058:         }
                   5059: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  5060:             my (@hidden,@unsolved);
1.945     raeburn  5061:             if (%typeparts) {
                   5062:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  5063:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   5064:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  5065:                         push(@hidden,$id);
1.1199    raeburn  5066:                     } elsif ($identifier ne '') {
                   5067:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   5068:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   5069:                                 ($hidestatus{$id})) {
1.1200    raeburn  5070:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  5071:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   5072:                                 push(@{$solved{$id}},$version);
                   5073:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   5074:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   5075:                                 my $skip;
                   5076:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   5077:                                     foreach my $reset (@{$resets{$id}}) {
                   5078:                                         if ($reset > $solved{$id}[-1]) {
                   5079:                                             $skip=1;
                   5080:                                             last;
                   5081:                                         }
                   5082:                                     }
                   5083:                                 }
                   5084:                                 unless ($skip) {
                   5085:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   5086:                                     push(@unsolved,$partslist);
                   5087:                                 }
                   5088:                             }
                   5089:                         }
1.945     raeburn  5090:                     }
                   5091:                 }
                   5092:             }
                   5093:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  5094:                            '<td>'.&mt('Transaction [_1]',$version);
                   5095:             if (@unsolved) {
                   5096:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   5097:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   5098:                                  &mt('Hide').'</label></span>';
                   5099:             }
                   5100:             $prevattempts .= '</td>';
1.945     raeburn  5101:             if (@hidden) {
                   5102:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5103:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  5104:                     my $hide;
                   5105:                     foreach my $id (@hidden) {
                   5106:                         if ($key =~ /^\Q$id\E/) {
                   5107:                             $hide = 1;
                   5108:                             last;
                   5109:                         }
                   5110:                     }
                   5111:                     if ($hide) {
                   5112:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5113:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5114:                             my $value = &format_previous_attempt_value($key,
                   5115:                                              $returnhash{$version.':'.$key});
1.1173    kruse    5116:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5117:                         } else {
                   5118:                             $prevattempts.='<td>&nbsp;</td>';
                   5119:                         }
                   5120:                     } else {
                   5121:                         if ($key =~ /\./) {
1.1212    raeburn  5122:                             my $value = $returnhash{$version.':'.$key};
                   5123:                             if ($key =~ /\.rndseed$/) {
                   5124:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5125:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5126:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5127:                                 }
                   5128:                             }
                   5129:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5130:                                            '&nbsp;</td>';
1.945     raeburn  5131:                         } else {
                   5132:                             $prevattempts.='<td>&nbsp;</td>';
                   5133:                         }
                   5134:                     }
                   5135:                 }
                   5136:             } else {
                   5137: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5138:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  5139:                     my $value = $returnhash{$version.':'.$key};
                   5140:                     if ($key =~ /\.rndseed$/) {
                   5141:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5142:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5143:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5144:                         }
                   5145:                     }
                   5146:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5147:                                    '&nbsp;</td>';
1.945     raeburn  5148: 	        }
                   5149:             }
                   5150: 	    $prevattempts.=&end_data_table_row();
1.40      ng       5151: 	 }
1.1       albertel 5152:       }
1.945     raeburn  5153:       my @currhidden = keys(%lasthidden);
1.596     albertel 5154:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 5155:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5156:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  5157:           if (%typeparts) {
                   5158:               my $hidden;
                   5159:               foreach my $id (@currhidden) {
                   5160:                   if ($key =~ /^\Q$id\E/) {
                   5161:                       $hidden = 1;
                   5162:                       last;
                   5163:                   }
                   5164:               }
                   5165:               if ($hidden) {
                   5166:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5167:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5168:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5169:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5170:                           $value = &$gradesub($value);
                   5171:                       }
1.1173    kruse    5172:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5173:                   } else {
                   5174:                       $prevattempts.='<td>&nbsp;</td>';
                   5175:                   }
                   5176:               } else {
                   5177:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5178:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5179:                       $value = &$gradesub($value);
                   5180:                   }
1.1173    kruse    5181:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5182:               }
                   5183:           } else {
                   5184: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5185: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5186:                   $value = &$gradesub($value);
                   5187:               }
1.1173    kruse    5188: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5189:           }
1.16      harris41 5190:       }
1.596     albertel 5191:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5192:     } else {
1.1305    raeburn  5193:       my $msg;
                   5194:       if ($symb =~ /ext\.tool$/) {
                   5195:           $msg = &mt('No grade passed back.');
                   5196:       } else {
                   5197:           $msg = &mt('Nothing submitted - no attempts.');
                   5198:       }
1.596     albertel 5199:       $prevattempts=
                   5200: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5201: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5202: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5203:     }
                   5204:   } else {
1.596     albertel 5205:     $prevattempts=
                   5206: 	  &start_data_table().&start_data_table_row().
                   5207: 	  '<td>'.&mt('No data.').'</td>'.
                   5208: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5209:   }
1.10      albertel 5210: }
                   5211: 
1.581     albertel 5212: sub format_previous_attempt_value {
                   5213:     my ($key,$value) = @_;
1.1011    www      5214:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5215:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5216:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5217:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5218:     } elsif ($key =~ /answerstring$/) {
                   5219:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5220:         my @answer = %answers;
                   5221:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5222:         my @anskeys = sort(keys(%answers));
                   5223:         if (@anskeys == 1) {
                   5224:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5225:             if ($answer =~ m{\0}) {
                   5226:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5227:             }
                   5228:             my $tag_internal_answer_name = 'INTERNAL';
                   5229:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5230:                 $value = $answer; 
                   5231:             } else {
                   5232:                 $value = $anskeys[0].'='.$answer;
                   5233:             }
                   5234:         } else {
                   5235:             foreach my $ans (@anskeys) {
                   5236:                 my $answer = $answers{$ans};
1.1001    raeburn  5237:                 if ($answer =~ m{\0}) {
                   5238:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5239:                 }
                   5240:                 $value .=  $ans.'='.$answer.'<br />';;
                   5241:             } 
                   5242:         }
1.581     albertel 5243:     } else {
1.1173    kruse    5244:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5245:     }
                   5246:     return $value;
                   5247: }
                   5248: 
                   5249: 
1.107     albertel 5250: sub relative_to_absolute {
                   5251:     my ($url,$output)=@_;
                   5252:     my $parser=HTML::TokeParser->new(\$output);
                   5253:     my $token;
                   5254:     my $thisdir=$url;
                   5255:     my @rlinks=();
                   5256:     while ($token=$parser->get_token) {
                   5257: 	if ($token->[0] eq 'S') {
                   5258: 	    if ($token->[1] eq 'a') {
                   5259: 		if ($token->[2]->{'href'}) {
                   5260: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5261: 		}
                   5262: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5263: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5264: 	    } elsif ($token->[1] eq 'base') {
                   5265: 		$thisdir=$token->[2]->{'href'};
                   5266: 	    }
                   5267: 	}
                   5268:     }
                   5269:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5270:     foreach my $link (@rlinks) {
1.726     raeburn  5271: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5272: 		($link=~/^\//) ||
                   5273: 		($link=~/^javascript:/i) ||
                   5274: 		($link=~/^mailto:/i) ||
                   5275: 		($link=~/^\#/)) {
                   5276: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5277: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5278: 	}
                   5279:     }
                   5280: # -------------------------------------------------- Deal with Applet codebases
                   5281:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5282:     return $output;
                   5283: }
                   5284: 
1.112     bowersj2 5285: =pod
                   5286: 
1.648     raeburn  5287: =item * &get_student_view()
1.112     bowersj2 5288: 
                   5289: show a snapshot of what student was looking at
                   5290: 
                   5291: =cut
                   5292: 
1.10      albertel 5293: sub get_student_view {
1.186     albertel 5294:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5295:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5296:   my (%form);
1.10      albertel 5297:   my @elements=('symb','courseid','domain','username');
                   5298:   foreach my $element (@elements) {
1.186     albertel 5299:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5300:   }
1.186     albertel 5301:   if (defined($moreenv)) {
                   5302:       %form=(%form,%{$moreenv});
                   5303:   }
1.236     albertel 5304:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5305:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5306:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5307:       $feedurl =~ s{^/adm/wrapper}{};
                   5308:   }
1.650     www      5309:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5310:   $userview=~s/\<body[^\>]*\>//gi;
                   5311:   $userview=~s/\<\/body\>//gi;
                   5312:   $userview=~s/\<html\>//gi;
                   5313:   $userview=~s/\<\/html\>//gi;
                   5314:   $userview=~s/\<head\>//gi;
                   5315:   $userview=~s/\<\/head\>//gi;
                   5316:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5317:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5318:   if (wantarray) {
                   5319:      return ($userview,$response);
                   5320:   } else {
                   5321:      return $userview;
                   5322:   }
                   5323: }
                   5324: 
                   5325: sub get_student_view_with_retries {
                   5326:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5327: 
                   5328:     my $ok = 0;                 # True if we got a good response.
                   5329:     my $content;
                   5330:     my $response;
                   5331: 
                   5332:     # Try to get the student_view done. within the retries count:
                   5333:     
                   5334:     do {
                   5335:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5336:          $ok      = $response->is_success;
                   5337:          if (!$ok) {
                   5338:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5339:          }
                   5340:          $retries--;
                   5341:     } while (!$ok && ($retries > 0));
                   5342:     
                   5343:     if (!$ok) {
                   5344:        $content = '';          # On error return an empty content.
                   5345:     }
1.651     www      5346:     if (wantarray) {
                   5347:        return ($content, $response);
                   5348:     } else {
                   5349:        return $content;
                   5350:     }
1.11      albertel 5351: }
                   5352: 
1.1349    raeburn  5353: sub css_links {
                   5354:     my ($currsymb,$level) = @_;
                   5355:     my ($links,@symbs,%cssrefs,%httpref);
                   5356:     if ($level eq 'map') {
                   5357:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5358:         if (ref($navmap)) {
                   5359:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5360:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5361:             foreach my $res (@resources) {
                   5362:                 if (ref($res) && $res->symb()) {
                   5363:                     push(@symbs,$res->symb());
                   5364:                 }
                   5365:             }
                   5366:         }
                   5367:     } else {
                   5368:         @symbs = ($currsymb);
                   5369:     }
                   5370:     foreach my $symb (@symbs) {
                   5371:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5372:         if ($css_href =~ /\S/) {
                   5373:             unless ($css_href =~ m{https?://}) {
                   5374:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5375:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5376:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5377:                 unless ($css_href =~ m{^/}) {
                   5378:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5379:                 }
                   5380:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5381:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5382:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5383:                         my $thisurl = $proburl;
                   5384:                         if ($env{'httpref.'.$proburl}) {
                   5385:                             $thisurl = $env{'httpref.'.$proburl};
                   5386:                         }
                   5387:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5388:                     }
                   5389:                 }
                   5390:             }
                   5391:             $cssrefs{$css_href} = 1;
                   5392:         }
                   5393:     }
                   5394:     if (keys(%httpref)) {
                   5395:         &Apache::lonnet::appenv(\%httpref);
                   5396:     }
                   5397:     if (keys(%cssrefs)) {
                   5398:         foreach my $css_href (keys(%cssrefs)) {
                   5399:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5400:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5401:         }
                   5402:     }
                   5403:     return $links;
                   5404: }
                   5405: 
1.112     bowersj2 5406: =pod
                   5407: 
1.648     raeburn  5408: =item * &get_student_answers() 
1.112     bowersj2 5409: 
                   5410: show a snapshot of how student was answering problem
                   5411: 
                   5412: =cut
                   5413: 
1.11      albertel 5414: sub get_student_answers {
1.100     sakharuk 5415:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5416:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5417:   my (%moreenv);
1.11      albertel 5418:   my @elements=('symb','courseid','domain','username');
                   5419:   foreach my $element (@elements) {
1.186     albertel 5420:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5421:   }
1.186     albertel 5422:   $moreenv{'grade_target'}='answer';
                   5423:   %moreenv=(%form,%moreenv);
1.497     raeburn  5424:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5425:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5426:   return $userview;
1.1       albertel 5427: }
1.116     albertel 5428: 
                   5429: =pod
                   5430: 
                   5431: =item * &submlink()
                   5432: 
1.242     albertel 5433: Inputs: $text $uname $udom $symb $target
1.116     albertel 5434: 
                   5435: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5436: 
                   5437: =cut
                   5438: 
                   5439: ###############################################
                   5440: sub submlink {
1.242     albertel 5441:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5442:     if (!($uname && $udom)) {
                   5443: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5444: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5445: 	if (!$symb) { $symb=$cursymb; }
                   5446:     }
1.254     matthew  5447:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5448:     $symb=&escape($symb);
1.960     bisitz   5449:     if ($target) { $target=" target=\"$target\""; }
                   5450:     return
                   5451:         '<a href="/adm/grades?command=submission'.
                   5452:         '&amp;symb='.$symb.
                   5453:         '&amp;student='.$uname.
                   5454:         '&amp;userdom='.$udom.'"'.
                   5455:         $target.'>'.$text.'</a>';
1.242     albertel 5456: }
                   5457: ##############################################
                   5458: 
                   5459: =pod
                   5460: 
                   5461: =item * &pgrdlink()
                   5462: 
                   5463: Inputs: $text $uname $udom $symb $target
                   5464: 
                   5465: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5466: 
                   5467: =cut
                   5468: 
                   5469: ###############################################
                   5470: sub pgrdlink {
                   5471:     my $link=&submlink(@_);
                   5472:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5473:     return $link;
                   5474: }
                   5475: ##############################################
                   5476: 
                   5477: =pod
                   5478: 
                   5479: =item * &pprmlink()
                   5480: 
                   5481: Inputs: $text $uname $udom $symb $target
                   5482: 
                   5483: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5484: student and a specific resource
1.242     albertel 5485: 
                   5486: =cut
                   5487: 
                   5488: ###############################################
                   5489: sub pprmlink {
                   5490:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5491:     if (!($uname && $udom)) {
                   5492: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5493: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5494: 	if (!$symb) { $symb=$cursymb; }
                   5495:     }
1.254     matthew  5496:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5497:     $symb=&escape($symb);
1.242     albertel 5498:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5499:     return '<a href="/adm/parmset?command=set&amp;'.
                   5500: 	'symb='.$symb.'&amp;uname='.$uname.
                   5501: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5502: }
                   5503: ##############################################
1.37      matthew  5504: 
1.112     bowersj2 5505: =pod
                   5506: 
                   5507: =back
                   5508: 
                   5509: =cut
                   5510: 
1.37      matthew  5511: ###############################################
1.51      www      5512: 
                   5513: 
                   5514: sub timehash {
1.687     raeburn  5515:     my ($thistime) = @_;
                   5516:     my $timezone = &Apache::lonlocal::gettimezone();
                   5517:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5518:                      ->set_time_zone($timezone);
                   5519:     my $wday = $dt->day_of_week();
                   5520:     if ($wday == 7) { $wday = 0; }
                   5521:     return ( 'second' => $dt->second(),
                   5522:              'minute' => $dt->minute(),
                   5523:              'hour'   => $dt->hour(),
                   5524:              'day'     => $dt->day_of_month(),
                   5525:              'month'   => $dt->month(),
                   5526:              'year'    => $dt->year(),
                   5527:              'weekday' => $wday,
                   5528:              'dayyear' => $dt->day_of_year(),
                   5529:              'dlsav'   => $dt->is_dst() );
1.51      www      5530: }
                   5531: 
1.370     www      5532: sub utc_string {
                   5533:     my ($date)=@_;
1.371     www      5534:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5535: }
                   5536: 
1.51      www      5537: sub maketime {
                   5538:     my %th=@_;
1.687     raeburn  5539:     my ($epoch_time,$timezone,$dt);
                   5540:     $timezone = &Apache::lonlocal::gettimezone();
                   5541:     eval {
                   5542:         $dt = DateTime->new( year   => $th{'year'},
                   5543:                              month  => $th{'month'},
                   5544:                              day    => $th{'day'},
                   5545:                              hour   => $th{'hour'},
                   5546:                              minute => $th{'minute'},
                   5547:                              second => $th{'second'},
                   5548:                              time_zone => $timezone,
                   5549:                          );
                   5550:     };
                   5551:     if (!$@) {
                   5552:         $epoch_time = $dt->epoch;
                   5553:         if ($epoch_time) {
                   5554:             return $epoch_time;
                   5555:         }
                   5556:     }
1.51      www      5557:     return POSIX::mktime(
                   5558:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5559:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5560: }
                   5561: 
                   5562: #########################################
1.51      www      5563: 
                   5564: sub findallcourses {
1.482     raeburn  5565:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5566:     my %roles;
                   5567:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5568:     my %courses;
1.51      www      5569:     my $now=time;
1.482     raeburn  5570:     if (!defined($uname)) {
                   5571:         $uname = $env{'user.name'};
                   5572:     }
                   5573:     if (!defined($udom)) {
                   5574:         $udom = $env{'user.domain'};
                   5575:     }
                   5576:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5577:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5578:         if (!%roles) {
                   5579:             %roles = (
                   5580:                        cc => 1,
1.907     raeburn  5581:                        co => 1,
1.482     raeburn  5582:                        in => 1,
                   5583:                        ep => 1,
                   5584:                        ta => 1,
                   5585:                        cr => 1,
                   5586:                        st => 1,
                   5587:              );
                   5588:         }
                   5589:         foreach my $entry (keys(%roleshash)) {
                   5590:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5591:             if ($trole =~ /^cr/) { 
                   5592:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5593:             } else {
                   5594:                 next if (!exists($roles{$trole}));
                   5595:             }
                   5596:             if ($tend) {
                   5597:                 next if ($tend < $now);
                   5598:             }
                   5599:             if ($tstart) {
                   5600:                 next if ($tstart > $now);
                   5601:             }
1.1058    raeburn  5602:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5603:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5604:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5605:             if ($secpart eq '') {
                   5606:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5607:                 $sec = 'none';
1.1058    raeburn  5608:                 $value .= $cnum.'/';
1.482     raeburn  5609:             } else {
                   5610:                 $cnum = $cnumpart;
                   5611:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5612:                 $value .= $cnum.'/'.$sec;
                   5613:             }
                   5614:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5615:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5616:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5617:                 }
                   5618:             } else {
                   5619:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5620:             }
1.482     raeburn  5621:         }
                   5622:     } else {
                   5623:         foreach my $key (keys(%env)) {
1.483     albertel 5624: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5625:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5626: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5627: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5628: 	        next if (%roles && !exists($roles{$role}));
                   5629: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5630:                 my $active=1;
                   5631:                 if ($starttime) {
                   5632: 		    if ($now<$starttime) { $active=0; }
                   5633:                 }
                   5634:                 if ($endtime) {
                   5635:                     if ($now>$endtime) { $active=0; }
                   5636:                 }
                   5637:                 if ($active) {
1.1058    raeburn  5638:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5639:                     if ($sec eq '') {
                   5640:                         $sec = 'none';
1.1058    raeburn  5641:                     } else {
                   5642:                         $value .= $sec;
                   5643:                     }
                   5644:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5645:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5646:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5647:                         }
                   5648:                     } else {
                   5649:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5650:                     }
1.474     raeburn  5651:                 }
                   5652:             }
1.51      www      5653:         }
                   5654:     }
1.474     raeburn  5655:     return %courses;
1.51      www      5656: }
1.37      matthew  5657: 
1.54      www      5658: ###############################################
1.474     raeburn  5659: 
                   5660: sub blockcheck {
1.1372    raeburn  5661:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5662:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5663:         my ($has_evb,$check_ipaccess);
                   5664:         my $dom = $env{'user.domain'};
                   5665:         if ($env{'request.course.id'}) {
                   5666:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5667:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5668:             my $checkrole = "cm./$cdom/$cnum";
                   5669:             my $sec = $env{'request.course.sec'};
                   5670:             if ($sec ne '') {
                   5671:                 $checkrole .= "/$sec";
                   5672:             }
                   5673:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5674:                 ($env{'request.role'} !~ /^st/)) {
                   5675:                 $has_evb = 1;
                   5676:             }
                   5677:             unless ($has_evb) {
                   5678:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5679:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5680:                     if ($udom eq $cdom) {
                   5681:                         $check_ipaccess = 1;
                   5682:                     }
                   5683:                 }
                   5684:             }
1.1375    raeburn  5685:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5686:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5687:             my $checkrole;
                   5688:             if ($env{'request.role.domain'} eq '') {
                   5689:                 $checkrole = "cm./$env{'user.domain'}/";
                   5690:             } else {
                   5691:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5692:             }
                   5693:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5694:                 $has_evb = 1;
                   5695:             }
1.1372    raeburn  5696:         }
                   5697:         unless ($has_evb || $check_ipaccess) {
                   5698:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5699:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5700:                 $dom = $udom;
                   5701:             }
                   5702:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5703:                 $check_ipaccess = 1;
                   5704:             } else {
                   5705:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5706:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5707:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5708:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5709:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5710:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5711:                         $check_ipaccess = 1;
                   5712:                     }
                   5713:                 }
                   5714:             }
                   5715:         }
                   5716:         if ($check_ipaccess) {
                   5717:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5718:             unless (defined($cached)) {
                   5719:                 my %domconfig =
                   5720:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5721:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5722:             }
                   5723:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5724:                 foreach my $id (keys(%{$ipaccessref})) {
                   5725:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5726:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5727:                         if ($range) {
                   5728:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5729:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5730:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5731:                                         return ('','','',$id,$dom);
                   5732:                                         last;
                   5733:                                     }
                   5734:                                 }
                   5735:                             }
                   5736:                         }
                   5737:                     }
                   5738:                 }
                   5739:             }
                   5740:         }
1.1373    raeburn  5741:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5742:             return ();
                   5743:         }
1.1372    raeburn  5744:     }
1.1189    raeburn  5745:     if (defined($udom) && defined($uname)) {
                   5746:         # If uname and udom are for a course, check for blocks in the course.
                   5747:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5748:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5749:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5750:             return ($startblock,$endblock,$triggerblock);
                   5751:         }
                   5752:     } else {
1.490     raeburn  5753:         $udom = $env{'user.domain'};
                   5754:         $uname = $env{'user.name'};
                   5755:     }
                   5756: 
1.502     raeburn  5757:     my $startblock = 0;
                   5758:     my $endblock = 0;
1.1062    raeburn  5759:     my $triggerblock = '';
1.1373    raeburn  5760:     my %live_courses;
                   5761:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5762:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5763:     }
1.474     raeburn  5764: 
1.490     raeburn  5765:     # If uname is for a user, and activity is course-specific, i.e.,
                   5766:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5767: 
1.490     raeburn  5768:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5769:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5770:          $activity eq 'search' || $activity eq 'reinit' ||
                   5771:          $activity eq 'alert') &&
1.1189    raeburn  5772:         ($env{'request.course.id'})) {
1.490     raeburn  5773:         foreach my $key (keys(%live_courses)) {
                   5774:             if ($key ne $env{'request.course.id'}) {
                   5775:                 delete($live_courses{$key});
                   5776:             }
                   5777:         }
                   5778:     }
                   5779: 
                   5780:     my $otheruser = 0;
                   5781:     my %own_courses;
                   5782:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5783:         # Resource belongs to user other than current user.
                   5784:         $otheruser = 1;
                   5785:         # Gather courses for current user
                   5786:         %own_courses = 
                   5787:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5788:     }
                   5789: 
                   5790:     # Gather active course roles - course coordinator, instructor, 
                   5791:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5792: 
                   5793:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5794:         my ($cdom,$cnum);
                   5795:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5796:             $cdom = $env{'course.'.$course.'.domain'};
                   5797:             $cnum = $env{'course.'.$course.'.num'};
                   5798:         } else {
1.490     raeburn  5799:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5800:         }
                   5801:         my $no_ownblock = 0;
                   5802:         my $no_userblock = 0;
1.533     raeburn  5803:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5804:             # Check if current user has 'evb' priv for this
                   5805:             if (defined($own_courses{$course})) {
                   5806:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5807:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5808:                     if ($sec ne 'none') {
                   5809:                         $checkrole .= '/'.$sec;
                   5810:                     }
                   5811:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5812:                         $no_ownblock = 1;
                   5813:                         last;
                   5814:                     }
                   5815:                 }
                   5816:             }
                   5817:             # if they have 'evb' priv and are currently not playing student
                   5818:             next if (($no_ownblock) &&
                   5819:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5820:         }
1.474     raeburn  5821:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5822:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5823:             if ($sec ne 'none') {
1.482     raeburn  5824:                 $checkrole .= '/'.$sec;
1.474     raeburn  5825:             }
1.490     raeburn  5826:             if ($otheruser) {
                   5827:                 # Resource belongs to user other than current user.
                   5828:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5829:                 my (%allroles,%userroles);
                   5830:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5831:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5832:                         my ($trole,$tdom,$tnum,$tsec);
                   5833:                         if ($entry =~ /^cr/) {
                   5834:                             ($trole,$tdom,$tnum,$tsec) = 
                   5835:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5836:                         } else {
                   5837:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5838:                         }
                   5839:                         my ($spec,$area,$trest);
                   5840:                         $area = '/'.$tdom.'/'.$tnum;
                   5841:                         $trest = $tnum;
                   5842:                         if ($tsec ne '') {
                   5843:                             $area .= '/'.$tsec;
                   5844:                             $trest .= '/'.$tsec;
                   5845:                         }
                   5846:                         $spec = $trole.'.'.$area;
                   5847:                         if ($trole =~ /^cr/) {
                   5848:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5849:                                                               $tdom,$spec,$trest,$area);
                   5850:                         } else {
                   5851:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5852:                                                                 $tdom,$spec,$trest,$area);
                   5853:                         }
                   5854:                     }
1.1276    raeburn  5855:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5856:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5857:                         if ($1) {
                   5858:                             $no_userblock = 1;
                   5859:                             last;
                   5860:                         }
1.486     raeburn  5861:                     }
                   5862:                 }
1.490     raeburn  5863:             } else {
                   5864:                 # Resource belongs to current user
                   5865:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5866:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5867:                     $no_ownblock = 1;
                   5868:                     last;
                   5869:                 }
1.474     raeburn  5870:             }
                   5871:         }
                   5872:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5873:         next if (($no_ownblock) &&
1.491     albertel 5874:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5875:         next if ($no_userblock);
1.474     raeburn  5876: 
1.1303    raeburn  5877:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5878:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5879: 
1.1062    raeburn  5880:         my ($start,$end,$trigger) = 
1.1347    raeburn  5881:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5882:         if (($start != 0) && 
                   5883:             (($startblock == 0) || ($startblock > $start))) {
                   5884:             $startblock = $start;
1.1062    raeburn  5885:             if ($trigger ne '') {
                   5886:                 $triggerblock = $trigger;
                   5887:             }
1.502     raeburn  5888:         }
                   5889:         if (($end != 0)  &&
                   5890:             (($endblock == 0) || ($endblock < $end))) {
                   5891:             $endblock = $end;
1.1062    raeburn  5892:             if ($trigger ne '') {
                   5893:                 $triggerblock = $trigger;
                   5894:             }
1.502     raeburn  5895:         }
1.490     raeburn  5896:     }
1.1062    raeburn  5897:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5898: }
                   5899: 
                   5900: sub get_blocks {
1.1347    raeburn  5901:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5902:     my $startblock = 0;
                   5903:     my $endblock = 0;
1.1062    raeburn  5904:     my $triggerblock = '';
1.490     raeburn  5905:     my $course = $cdom.'_'.$cnum;
                   5906:     $setters->{$course} = {};
                   5907:     $setters->{$course}{'staff'} = [];
                   5908:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5909:     $setters->{$course}{'triggers'} = [];
                   5910:     my (@blockers,%triggered);
                   5911:     my $now = time;
                   5912:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5913:     if ($activity eq 'docs') {
1.1348    raeburn  5914:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5915:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5916:             $blocked = 1;
                   5917:             $nosymbcache = 1;
1.1348    raeburn  5918:             $noenccheck = 1;
1.1347    raeburn  5919:         }
1.1348    raeburn  5920:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5921:         foreach my $block (@blockers) {
                   5922:             if ($block =~ /^firstaccess____(.+)$/) {
                   5923:                 my $item = $1;
                   5924:                 my $type = 'map';
                   5925:                 my $timersymb = $item;
                   5926:                 if ($item eq 'course') {
                   5927:                     $type = 'course';
                   5928:                 } elsif ($item =~ /___\d+___/) {
                   5929:                     $type = 'resource';
                   5930:                 } else {
                   5931:                     $timersymb = &Apache::lonnet::symbread($item);
                   5932:                 }
                   5933:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5934:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5935:                 $triggered{$block} = {
                   5936:                                        start => $start,
                   5937:                                        end   => $end,
                   5938:                                        type  => $type,
                   5939:                                      };
                   5940:             }
                   5941:         }
                   5942:     } else {
                   5943:         foreach my $block (keys(%commblocks)) {
                   5944:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5945:                 my ($start,$end) = ($1,$2);
                   5946:                 if ($start <= time && $end >= time) {
                   5947:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5948:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5949:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5950:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5951:                                     push(@blockers,$block);
                   5952:                                 }
                   5953:                             }
                   5954:                         }
                   5955:                     }
                   5956:                 }
                   5957:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5958:                 my $item = $1;
                   5959:                 my $timersymb = $item; 
                   5960:                 my $type = 'map';
                   5961:                 if ($item eq 'course') {
                   5962:                     $type = 'course';
                   5963:                 } elsif ($item =~ /___\d+___/) {
                   5964:                     $type = 'resource';
                   5965:                 } else {
                   5966:                     $timersymb = &Apache::lonnet::symbread($item);
                   5967:                 }
                   5968:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5969:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5970:                 if ($start && $end) {
                   5971:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5972:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5973:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5974:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5975:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5976:                                         push(@blockers,$block);
                   5977:                                         $triggered{$block} = {
                   5978:                                                                start => $start,
                   5979:                                                                end   => $end,
                   5980:                                                                type  => $type,
                   5981:                                                              };
                   5982:                                     }
                   5983:                                 }
                   5984:                             }
1.1062    raeburn  5985:                         }
                   5986:                     }
1.490     raeburn  5987:                 }
1.1062    raeburn  5988:             }
                   5989:         }
                   5990:     }
                   5991:     foreach my $blocker (@blockers) {
                   5992:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5993:             &parse_block_record($commblocks{$blocker});
                   5994:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5995:         my ($start,$end,$triggertype);
                   5996:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5997:             ($start,$end) = ($1,$2);
                   5998:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5999:             $start = $triggered{$blocker}{'start'};
                   6000:             $end = $triggered{$blocker}{'end'};
                   6001:             $triggertype = $triggered{$blocker}{'type'};
                   6002:         }
                   6003:         if ($start) {
                   6004:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6005:             if ($triggertype) {
                   6006:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6007:             } else {
                   6008:                 push(@{$$setters{$course}{'triggers'}},0);
                   6009:             }
                   6010:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6011:                 $startblock = $start;
                   6012:                 if ($triggertype) {
                   6013:                     $triggerblock = $blocker;
1.474     raeburn  6014:                 }
                   6015:             }
1.1062    raeburn  6016:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6017:                $endblock = $end;
                   6018:                if ($triggertype) {
                   6019:                    $triggerblock = $blocker;
                   6020:                }
                   6021:             }
1.474     raeburn  6022:         }
                   6023:     }
1.1062    raeburn  6024:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6025: }
                   6026: 
                   6027: sub parse_block_record {
                   6028:     my ($record) = @_;
                   6029:     my ($setuname,$setudom,$title,$blocks);
                   6030:     if (ref($record) eq 'HASH') {
                   6031:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6032:         $title = &unescape($record->{'event'});
                   6033:         $blocks = $record->{'blocks'};
                   6034:     } else {
                   6035:         my @data = split(/:/,$record,3);
                   6036:         if (scalar(@data) eq 2) {
                   6037:             $title = $data[1];
                   6038:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6039:         } else {
                   6040:             ($setuname,$setudom,$title) = @data;
                   6041:         }
                   6042:         $blocks = { 'com' => 'on' };
                   6043:     }
                   6044:     return ($setuname,$setudom,$title,$blocks);
                   6045: }
                   6046: 
1.854     kalberla 6047: sub blocking_status {
1.1372    raeburn  6048:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6049:     my %setters;
1.890     droeschl 6050: 
1.1061    raeburn  6051: # check for active blocking
1.1372    raeburn  6052:     if ($clientip eq '') {
                   6053:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6054:     }
                   6055:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6056:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6057:     my $blocked = 0;
1.1372    raeburn  6058:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6059:         $blocked = 1;
                   6060:     }
1.890     droeschl 6061: 
1.1061    raeburn  6062: # caller just wants to know whether a block is active
                   6063:     if (!wantarray) { return $blocked; }
                   6064: 
                   6065: # build a link to a popup window containing the details
                   6066:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6067: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6068:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6069:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6070:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6071:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6072:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6073:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6074:         if ($symb) {
                   6075:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6076:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6077:         }
1.1062    raeburn  6078:     }
1.1061    raeburn  6079: 
                   6080:     my $output .= <<'END_MYBLOCK';
                   6081: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6082:     var options = "width=" + w + ",height=" + h + ",";
                   6083:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6084:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6085:     var newWin = window.open(url, wdwName, options);
                   6086:     newWin.focus();
                   6087: }
1.890     droeschl 6088: END_MYBLOCK
1.854     kalberla 6089: 
1.1061    raeburn  6090:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6091:   
1.1061    raeburn  6092:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6093:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6094:     my $class = 'LC_comblock';
1.1062    raeburn  6095:     if ($activity eq 'docs') {
                   6096:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6097:         $class = '';
1.1063    raeburn  6098:     } elsif ($activity eq 'printout') {
                   6099:         $text = &mt('Printing Blocked');
1.1232    raeburn  6100:     } elsif ($activity eq 'passwd') {
                   6101:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6102:     } elsif ($activity eq 'grades') {
                   6103:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6104:     } elsif ($activity eq 'search') {
                   6105:         $text = &mt('Search Blocked');
1.1282    raeburn  6106:     } elsif ($activity eq 'alert') {
                   6107:         $text = &mt('Checking Critical Messages Blocked');
                   6108:     } elsif ($activity eq 'reinit') {
                   6109:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6110:     } elsif ($activity eq 'about') {
                   6111:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6112:     } elsif ($activity eq 'wishlist') {
                   6113:         $text = &mt('Access to Stored Links Blocked');
                   6114:     } elsif ($activity eq 'annotate') {
                   6115:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6116:     }
1.1061    raeburn  6117:     $output .= <<"END_BLOCK";
1.1217    raeburn  6118: <div class='$class'>
1.869     kalberla 6119:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6120:   title='$text'>
                   6121:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6122:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6123:   title='$text'>$text</a>
1.867     kalberla 6124: </div>
                   6125: 
                   6126: END_BLOCK
1.474     raeburn  6127: 
1.1061    raeburn  6128:     return ($blocked, $output);
1.854     kalberla 6129: }
1.490     raeburn  6130: 
1.60      matthew  6131: ###############################################
                   6132: 
1.682     raeburn  6133: sub check_ip_acc {
1.1201    raeburn  6134:     my ($acc,$clientip)=@_;
1.682     raeburn  6135:     &Apache::lonxml::debug("acc is $acc");
                   6136:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6137:         return 1;
                   6138:     }
1.1339    raeburn  6139:     my ($ip,$allowed);
                   6140:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6141:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6142:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6143:     } else {
1.1350    raeburn  6144:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6145:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6146:     }
1.682     raeburn  6147: 
                   6148:     my $name;
1.1219    raeburn  6149:     my %access = (
                   6150:                      allowfrom => 1,
                   6151:                      denyfrom  => 0,
                   6152:                  );
                   6153:     my @allows;
                   6154:     my @denies;
                   6155:     foreach my $item (split(',',$acc)) {
                   6156:         $item =~ s/^\s*//;
                   6157:         $item =~ s/\s*$//;
                   6158:         my $pattern;
                   6159:         if ($item =~ /^\!(.+)$/) {
                   6160:             push(@denies,$1);
                   6161:         } else {
                   6162:             push(@allows,$item);
                   6163:         }
                   6164:    }
                   6165:    my $numdenies = scalar(@denies);
                   6166:    my $numallows = scalar(@allows);
                   6167:    my $count = 0;
                   6168:    foreach my $pattern (@denies,@allows) {
                   6169:         $count ++; 
                   6170:         my $acctype = 'allowfrom';
                   6171:         if ($count <= $numdenies) {
                   6172:             $acctype = 'denyfrom';
                   6173:         }
1.682     raeburn  6174:         if ($pattern =~ /\*$/) {
                   6175:             #35.8.*
                   6176:             $pattern=~s/\*//;
1.1219    raeburn  6177:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6178:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6179:             #35.8.3.[34-56]
                   6180:             my $low=$2;
                   6181:             my $high=$3;
                   6182:             $pattern=$1;
                   6183:             if ($ip =~ /^\Q$pattern\E/) {
                   6184:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6185:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6186:             }
                   6187:         } elsif ($pattern =~ /^\*/) {
                   6188:             #*.msu.edu
                   6189:             $pattern=~s/\*//;
                   6190:             if (!defined($name)) {
                   6191:                 use Socket;
                   6192:                 my $netaddr=inet_aton($ip);
                   6193:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6194:             }
1.1219    raeburn  6195:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6196:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6197:             #127.0.0.1
1.1219    raeburn  6198:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6199:         } else {
                   6200:             #some.name.com
                   6201:             if (!defined($name)) {
                   6202:                 use Socket;
                   6203:                 my $netaddr=inet_aton($ip);
                   6204:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6205:             }
1.1219    raeburn  6206:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6207:         }
                   6208:         if ($allowed =~ /^(0|1)$/) { last; }
                   6209:     }
                   6210:     if ($allowed eq '') {
                   6211:         if ($numdenies && !$numallows) {
                   6212:             $allowed = 1;
                   6213:         } else {
                   6214:             $allowed = 0;
1.682     raeburn  6215:         }
                   6216:     }
                   6217:     return $allowed;
                   6218: }
                   6219: 
                   6220: ###############################################
                   6221: 
1.60      matthew  6222: =pod
                   6223: 
1.112     bowersj2 6224: =head1 Domain Template Functions
                   6225: 
                   6226: =over 4
                   6227: 
                   6228: =item * &determinedomain()
1.60      matthew  6229: 
                   6230: Inputs: $domain (usually will be undef)
                   6231: 
1.63      www      6232: Returns: Determines which domain should be used for designs
1.60      matthew  6233: 
                   6234: =cut
1.54      www      6235: 
1.60      matthew  6236: ###############################################
1.63      www      6237: sub determinedomain {
                   6238:     my $domain=shift;
1.531     albertel 6239:     if (! $domain) {
1.60      matthew  6240:         # Determine domain if we have not been given one
1.893     raeburn  6241:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6242:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6243:         if ($env{'request.role.domain'}) { 
                   6244:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6245:         }
                   6246:     }
1.63      www      6247:     return $domain;
                   6248: }
                   6249: ###############################################
1.517     raeburn  6250: 
1.518     albertel 6251: sub devalidate_domconfig_cache {
                   6252:     my ($udom)=@_;
                   6253:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6254: }
                   6255: 
                   6256: # ---------------------- Get domain configuration for a domain
                   6257: sub get_domainconf {
                   6258:     my ($udom) = @_;
                   6259:     my $cachetime=1800;
                   6260:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6261:     if (defined($cached)) { return %{$result}; }
                   6262: 
                   6263:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6264: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6265:     my (%designhash,%legacy);
1.518     albertel 6266:     if (keys(%domconfig) > 0) {
                   6267:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6268:             if (keys(%{$domconfig{'login'}})) {
                   6269:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6270:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6271:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6272:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6273:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6274:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6275:                                         if ($key eq 'loginvia') {
                   6276:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6277:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6278:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6279:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6280: 
                   6281:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6282:                                                 } else {
                   6283:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6284:                                                 }
1.948     raeburn  6285:                                             }
1.1208    raeburn  6286:                                         } elsif ($key eq 'headtag') {
                   6287:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6288:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6289:                                             }
1.946     raeburn  6290:                                         }
1.1208    raeburn  6291:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6292:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6293:                                         }
1.946     raeburn  6294:                                     }
                   6295:                                 }
                   6296:                             }
1.1366    raeburn  6297:                         } elsif ($key eq 'saml') {
                   6298:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6299:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6300:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6301:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6302:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6303:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6304:                                         }
                   6305:                                     }
                   6306:                                 }
                   6307:                             }
1.946     raeburn  6308:                         } else {
                   6309:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6310:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6311:                                     $domconfig{'login'}{$key}{$img};
                   6312:                             }
1.699     raeburn  6313:                         }
                   6314:                     } else {
                   6315:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6316:                     }
1.632     raeburn  6317:                 }
                   6318:             } else {
                   6319:                 $legacy{'login'} = 1;
1.518     albertel 6320:             }
1.632     raeburn  6321:         } else {
                   6322:             $legacy{'login'} = 1;
1.518     albertel 6323:         }
                   6324:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6325:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6326:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6327:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6328:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6329:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6330:                         }
1.518     albertel 6331:                     }
                   6332:                 }
1.632     raeburn  6333:             } else {
                   6334:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6335:             }
1.632     raeburn  6336:         } else {
                   6337:             $legacy{'rolecolors'} = 1;
1.518     albertel 6338:         }
1.948     raeburn  6339:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6340:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6341:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6342:             }
                   6343:         }
1.632     raeburn  6344:         if (keys(%legacy) > 0) {
                   6345:             my %legacyhash = &get_legacy_domconf($udom);
                   6346:             foreach my $item (keys(%legacyhash)) {
                   6347:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6348:                     if ($legacy{'login'}) { 
                   6349:                         $designhash{$item} = $legacyhash{$item};
                   6350:                     }
                   6351:                 } else {
                   6352:                     if ($legacy{'rolecolors'}) {
                   6353:                         $designhash{$item} = $legacyhash{$item};
                   6354:                     }
1.518     albertel 6355:                 }
                   6356:             }
                   6357:         }
1.632     raeburn  6358:     } else {
                   6359:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6360:     }
                   6361:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6362: 				  $cachetime);
                   6363:     return %designhash;
                   6364: }
                   6365: 
1.632     raeburn  6366: sub get_legacy_domconf {
                   6367:     my ($udom) = @_;
                   6368:     my %legacyhash;
                   6369:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6370:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6371:     if (-e $designfile) {
1.1317    raeburn  6372:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6373:             while (my $line = <$fh>) {
                   6374:                 next if ($line =~ /^\#/);
                   6375:                 chomp($line);
                   6376:                 my ($key,$val)=(split(/\=/,$line));
                   6377:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6378:             }
                   6379:             close($fh);
                   6380:         }
                   6381:     }
1.1026    raeburn  6382:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6383:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6384:     }
                   6385:     return %legacyhash;
                   6386: }
                   6387: 
1.63      www      6388: =pod
                   6389: 
1.112     bowersj2 6390: =item * &domainlogo()
1.63      www      6391: 
                   6392: Inputs: $domain (usually will be undef)
                   6393: 
                   6394: Returns: A link to a domain logo, if the domain logo exists.
                   6395: If the domain logo does not exist, a description of the domain.
                   6396: 
                   6397: =cut
1.112     bowersj2 6398: 
1.63      www      6399: ###############################################
                   6400: sub domainlogo {
1.517     raeburn  6401:     my $domain = &determinedomain(shift);
1.518     albertel 6402:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6403:     # See if there is a logo
                   6404:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6405:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6406:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6407: 	    if ($imgsrc =~ m{^/res/}) {
                   6408: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6409: 		&Apache::lonnet::repcopy($local_name);
                   6410: 	    }
                   6411: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6412:         }
                   6413:         my $alttext = $domain;
                   6414:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6415:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6416:         }
                   6417:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6418:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6419:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6420:     } else {
1.60      matthew  6421:         return '';
1.59      www      6422:     }
                   6423: }
1.63      www      6424: ##############################################
                   6425: 
                   6426: =pod
                   6427: 
1.112     bowersj2 6428: =item * &designparm()
1.63      www      6429: 
                   6430: Inputs: $which parameter; $domain (usually will be undef)
                   6431: 
                   6432: Returns: value of designparamter $which
                   6433: 
                   6434: =cut
1.112     bowersj2 6435: 
1.397     albertel 6436: 
1.400     albertel 6437: ##############################################
1.397     albertel 6438: sub designparm {
                   6439:     my ($which,$domain)=@_;
                   6440:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6441:         return $env{'environment.color.'.$which};
1.96      www      6442:     }
1.63      www      6443:     $domain=&determinedomain($domain);
1.1016    raeburn  6444:     my %domdesign;
                   6445:     unless ($domain eq 'public') {
                   6446:         %domdesign = &get_domainconf($domain);
                   6447:     }
1.520     raeburn  6448:     my $output;
1.517     raeburn  6449:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6450:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6451:     } else {
1.520     raeburn  6452:         $output = $defaultdesign{$which};
                   6453:     }
                   6454:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6455:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6456:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6457:             if ($output =~ m{^/res/}) {
                   6458:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6459:                 &Apache::lonnet::repcopy($local_name);
                   6460:             }
1.520     raeburn  6461:             $output = &lonhttpdurl($output);
                   6462:         }
1.63      www      6463:     }
1.520     raeburn  6464:     return $output;
1.63      www      6465: }
1.59      www      6466: 
1.822     bisitz   6467: ##############################################
                   6468: =pod
                   6469: 
1.832     bisitz   6470: =item * &authorspace()
                   6471: 
1.1028    raeburn  6472: Inputs: $url (usually will be undef).
1.832     bisitz   6473: 
1.1132    raeburn  6474: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6475:          directory being viewed (or for which action is being taken). 
                   6476:          If $url is provided, and begins /priv/<domain>/<uname>
                   6477:          the path will be that portion of the $context argument.
                   6478:          Otherwise the path will be for the author space of the current
                   6479:          user when the current role is author, or for that of the 
                   6480:          co-author/assistant co-author space when the current role 
                   6481:          is co-author or assistant co-author.
1.832     bisitz   6482: 
                   6483: =cut
                   6484: 
                   6485: sub authorspace {
1.1028    raeburn  6486:     my ($url) = @_;
                   6487:     if ($url ne '') {
                   6488:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6489:            return $1;
                   6490:         }
                   6491:     }
1.832     bisitz   6492:     my $caname = '';
1.1024    www      6493:     my $cadom = '';
1.1028    raeburn  6494:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6495:         ($cadom,$caname) =
1.832     bisitz   6496:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6497:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6498:         $caname = $env{'user.name'};
1.1024    www      6499:         $cadom = $env{'user.domain'};
1.832     bisitz   6500:     }
1.1028    raeburn  6501:     if (($caname ne '') && ($cadom ne '')) {
                   6502:         return "/priv/$cadom/$caname/";
                   6503:     }
                   6504:     return;
1.832     bisitz   6505: }
                   6506: 
                   6507: ##############################################
                   6508: =pod
                   6509: 
1.822     bisitz   6510: =item * &head_subbox()
                   6511: 
                   6512: Inputs: $content (contains HTML code with page functions, etc.)
                   6513: 
                   6514: Returns: HTML div with $content
                   6515:          To be included in page header
                   6516: 
                   6517: =cut
                   6518: 
                   6519: sub head_subbox {
                   6520:     my ($content)=@_;
                   6521:     my $output =
1.993     raeburn  6522:         '<div class="LC_head_subbox">'
1.822     bisitz   6523:        .$content
                   6524:        .'</div>'
                   6525: }
                   6526: 
                   6527: ##############################################
                   6528: =pod
                   6529: 
                   6530: =item * &CSTR_pageheader()
                   6531: 
1.1026    raeburn  6532: Input: (optional) filename from which breadcrumb trail is built.
                   6533:        In most cases no input as needed, as $env{'request.filename'}
                   6534:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6535:        frameset flag
                   6536:        If page header is being requested for use in a frameset, then
                   6537:        the second (option) argument -- frameset will be true, and
                   6538:        the target attribute set for links should be target="_parent".
1.1407    raeburn  6539:        If $title is supplied as the thitd arg, that will be used to 
                   6540:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6541: 
                   6542: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6543:          To be included on Authoring Space pages
1.822     bisitz   6544: 
                   6545: =cut
                   6546: 
                   6547: sub CSTR_pageheader {
1.1407    raeburn  6548:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6549:     if ($trailfile eq '') {
                   6550:         $trailfile = $env{'request.filename'};
                   6551:     }
                   6552: 
                   6553: # this is for resources; directories have customtitle, and crumbs
                   6554: # and select recent are created in lonpubdir.pm
                   6555: 
                   6556:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6557:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6558:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6559:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6560:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6561: 
                   6562:     my $parentpath = '';
                   6563:     my $lastitem = '';
                   6564:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6565:         $parentpath = $1;
                   6566:         $lastitem = $2;
                   6567:     } else {
                   6568:         $lastitem = $thisdisfn;
                   6569:     }
1.921     bisitz   6570: 
1.1406    raeburn  6571:     my $crsauthor;
1.1246    raeburn  6572:     if (($env{'request.course.id'}) &&
                   6573:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6574:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6575:         $crsauthor = 1;
1.1406    raeburn  6576:         if ($title eq '') {
                   6577:             $title = &mt('Course Authoring Space');
                   6578:         }
                   6579:     } elsif ($title eq '') {
1.1246    raeburn  6580:         $title = &mt('Authoring Space');
                   6581:     }
                   6582: 
1.1379    raeburn  6583:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6584:     if ($frameset) {
                   6585:         $target = ' target="_parent"';
                   6586:         $crumbtarget = '_parent';
                   6587:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6588:         $target = '';
                   6589:         $crumbtarget = '';
1.1379    raeburn  6590:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6591:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6592:         $crumbtarget = $env{'request.deeplink.target'};
                   6593:     }
1.1313    raeburn  6594: 
1.921     bisitz   6595:     my $output =
1.1407    raeburn  6596:          '<div>'
1.822     bisitz   6597:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6598:         .'<b>'.$title.'</b> '
1.1314    raeburn  6599:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6600:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6601: 
                   6602:     if ($lastitem) {
                   6603:         $output .=
                   6604:              '<span class="LC_filename">'
                   6605:             .$lastitem
                   6606:             .'</span>';
                   6607:     }
1.1245    raeburn  6608: 
1.1246    raeburn  6609:     if ($crsauthor) {
1.1379    raeburn  6610:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6611:     } else {
                   6612:         $output .=
                   6613:              '<br />'
1.1314    raeburn  6614:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6615:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6616:             .'</form>'
1.1379    raeburn  6617:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6618:     }
1.1407    raeburn  6619:     $output .= '</div>';
1.921     bisitz   6620: 
                   6621:     return $output;
1.822     bisitz   6622: }
                   6623: 
1.1419    raeburn  6624: ##############################################
                   6625: =pod
                   6626: 
                   6627: =item * &nocodemirror()
                   6628: 
                   6629: Input: None
                   6630: 
                   6631: Returns: 1 if CodeMirror is deactivated based on
                   6632:          user's preference, or domain default,
                   6633:          if user indicated use of default.
                   6634: 
                   6635: =cut
                   6636: 
1.1416    raeburn  6637: sub nocodemirror {
                   6638:     my $nocodem = $env{'environment.nocodemirror'};
                   6639:     unless ($nocodem) {
                   6640:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6641:         if ($domdefs{'nocodemirror'}) {
                   6642:             $nocodem = 'yes';
                   6643:         }
                   6644:     }
1.1417    raeburn  6645:     if ($nocodem eq 'yes') {
                   6646:         return 1;
                   6647:     }
                   6648:     return;
1.1416    raeburn  6649: }
                   6650: 
1.1419    raeburn  6651: ##############################################
                   6652: =pod
                   6653: 
                   6654: =item * &permitted_editors()
                   6655: 
1.1422    raeburn  6656: Input: $uri (optional)
1.1419    raeburn  6657: 
                   6658: Returns: %editors hash in which keys are editors
                   6659:          permitted in current Authoring Space.
                   6660:          Value for each key is 1. Possible keys
                   6661:          are: edit, xml, and daxe. If no specific
                   6662:          set of editors has been set for the Author
                   6663:          who owns the Authoring Space, then the
                   6664:          domain default will be used.  If no domain
                   6665:          default has been set, then the keys will be
                   6666:          edit and xml.
                   6667: 
                   6668: =cut
                   6669: 
1.1418    raeburn  6670: sub permitted_editors {
1.1422    raeburn  6671:     my ($uri) = @_;
1.1418    raeburn  6672:     my ($is_author,$is_coauthor,$auname,$audom,%editors);
                   6673:     if ($env{'request.role'} =~ m{^au\./}) {
                   6674:         $is_author = 1;
                   6675:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6676:         ($audom,$auname) = ($1,$2);
                   6677:         if (($audom ne '') && ($auname ne '')) {
                   6678:             if (($env{'user.domain'} eq $audom) &&
                   6679:                 ($env{'user.name'} eq $auname)) {
                   6680:                 $is_author = 1;
                   6681:             } else {
                   6682:                 $is_coauthor = 1;
                   6683:             }
                   6684:         }
                   6685:     } elsif ($env{'request.course.id'}) {
                   6686:         if ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6687:             ($audom,$auname) = ($1,$2);
                   6688:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6689:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6690:         } elsif (($uri eq '/daxesave') &&
                   6691:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6692:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6693:         }
                   6694:         if (($audom ne '') && ($auname ne '')) {
                   6695:             if (($env{'user.domain'} eq $audom) &&
                   6696:                 ($env{'user.name'} eq $auname)) {
                   6697:                 $is_author = 1;
                   6698:             } else {
                   6699:                 $is_coauthor = 1;
                   6700:             }
                   6701:         }
                   6702:     }
                   6703:     if ($is_author) {
                   6704:         if (exists($env{'environment.editors'})) {
                   6705:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6706:         } else {
                   6707:             %editors = ( edit => 1,
                   6708:                          xml => 1,
                   6709:                        );
                   6710:         }
                   6711:     } elsif ($is_coauthor) {
                   6712:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6713:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6714:         } else {
                   6715:             %editors = ( edit => 1,
                   6716:                          xml => 1,
                   6717:                        );
                   6718:         }
                   6719:     } else {
                   6720:         %editors = ( edit => 1,
                   6721:                      xml => 1,
                   6722:                    );
                   6723:     }
                   6724:     return %editors;
                   6725: }
                   6726: 
1.60      matthew  6727: ###############################################
                   6728: ###############################################
                   6729: 
                   6730: =pod
                   6731: 
1.112     bowersj2 6732: =back
                   6733: 
1.549     albertel 6734: =head1 HTML Helpers
1.112     bowersj2 6735: 
                   6736: =over 4
                   6737: 
                   6738: =item * &bodytag()
1.60      matthew  6739: 
                   6740: Returns a uniform header for LON-CAPA web pages.
                   6741: 
                   6742: Inputs: 
                   6743: 
1.112     bowersj2 6744: =over 4
                   6745: 
                   6746: =item * $title, A title to be displayed on the page.
                   6747: 
                   6748: =item * $function, the current role (can be undef).
                   6749: 
                   6750: =item * $addentries, extra parameters for the <body> tag.
                   6751: 
                   6752: =item * $bodyonly, if defined, only return the <body> tag.
                   6753: 
                   6754: =item * $domain, if defined, force a given domain.
                   6755: 
                   6756: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6757:             text interface only)
1.60      matthew  6758: 
1.814     bisitz   6759: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6760:                      navigational links
1.317     albertel 6761: 
1.338     albertel 6762: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6763: 
1.460     albertel 6764: =item * $args, optional argument valid values are
                   6765:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6766:             use_absolute     -> for external resource or syllabus, this will
                   6767:                                 contain https://<hostname> if server uses
                   6768:                                 https (as per hosts.tab), but request is for http
                   6769:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6770: 
1.1096    raeburn  6771: =item * $advtoolsref, optional argument, ref to an array containing
                   6772:             inlineremote items to be added in "Functions" menu below
                   6773:             breadcrumbs.
                   6774: 
1.1316    raeburn  6775: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6776:             course, if LON-CAPA is in LTI Provider context. Value is
                   6777:             the scope of use, i.e., launch was for access to a single, a map
                   6778:             or the entire course.
                   6779: 
                   6780: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6781:             context, this will contain the URL for the landing item in
                   6782:             the course, after launch from an LTI Consumer
                   6783: 
1.1318    raeburn  6784: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6785:             context, this will contain a reference to hash of items
                   6786:             to be included in the page header and/or inline menu.
                   6787: 
1.1385    raeburn  6788: =item * $menucoll, optional argument, if specific menu collection is in
                   6789:             effect, either set as the default for the course, or set for
                   6790:             the deeplink paramater for $env{'request.deeplink.login'}
                   6791:             then $menucoll will be the number of that collection. 
                   6792: 
                   6793: =item * $menuref, optional argument, reference to a hash, containing the
                   6794:             menu options included for the menu in effect, based on the
                   6795:             configuration for the numbered menu collection in use.  
                   6796: 
                   6797: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6798:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6799:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6800:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6801:             being called a second time.
                   6802: 
1.112     bowersj2 6803: =back
                   6804: 
1.60      matthew  6805: Returns: A uniform header for LON-CAPA web pages.  
                   6806: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6807: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6808: other decorations will be returned.
                   6809: 
                   6810: =cut
                   6811: 
1.54      www      6812: sub bodytag {
1.831     bisitz   6813:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6814:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6815:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6816: 
1.954     raeburn  6817:     my $public;
                   6818:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6819:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6820:         $public = 1;
                   6821:     }
1.460     albertel 6822:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6823:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6824:     my $hostname = $args->{'hostname'};
1.339     albertel 6825: 
1.183     matthew  6826:     $function = &get_users_function() if (!$function);
1.339     albertel 6827:     my $img =    &designparm($function.'.img',$domain);
                   6828:     my $font =   &designparm($function.'.font',$domain);
                   6829:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6830: 
1.803     bisitz   6831:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6832: 		   'bgcolor' => $pgbg,
1.339     albertel 6833: 		   'text'    => $font,
                   6834:                    'alink'   => &designparm($function.'.alink',$domain),
                   6835: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6836: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6837:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6838: 
1.63      www      6839:  # role and realm
1.1178    raeburn  6840:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6841:     if ($realm) {
                   6842:         $realm = '/'.$realm;
                   6843:     }
1.1357    raeburn  6844:     if ($role eq 'ca') {
1.479     albertel 6845:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6846:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6847:     } 
1.55      www      6848: # realm
1.1357    raeburn  6849:     my ($cid,$sec);
1.258     albertel 6850:     if ($env{'request.course.id'}) {
1.1357    raeburn  6851:         $cid = $env{'request.course.id'};
                   6852:         if ($env{'request.course.sec'}) {
                   6853:             $sec = $env{'request.course.sec'};
                   6854:         }
                   6855:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6856:         if (&Apache::lonnet::is_course($1,$2)) {
                   6857:             $cid = $1.'_'.$2;
                   6858:             $sec = $3;
                   6859:         }
                   6860:     }
                   6861:     if ($cid) {
1.378     raeburn  6862:         if ($env{'request.role'} !~ /^cr/) {
                   6863:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6864:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6865:             if ($env{'request.role.desc'}) {
                   6866:                 $role = $env{'request.role.desc'};
                   6867:             } else {
                   6868:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6869:             }
1.1257    raeburn  6870:         } else {
                   6871:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6872:         }
1.1357    raeburn  6873:         if ($sec) {
                   6874:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6875:         }   
1.1357    raeburn  6876: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6877:     } else {
                   6878:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6879:     }
1.433     albertel 6880: 
1.359     albertel 6881:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6882: 
1.438     albertel 6883:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6884: 
1.101     www      6885: # construct main body tag
1.359     albertel 6886:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6887: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6888: 
1.1131    raeburn  6889:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6890: 
1.1130    raeburn  6891:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6892:         return $bodytag;
1.1130    raeburn  6893:     }
1.359     albertel 6894: 
1.954     raeburn  6895:     if ($public) {
1.433     albertel 6896: 	undef($role);
                   6897:     }
1.1318    raeburn  6898: 
1.1359    raeburn  6899:     my $showcrstitle = 1;
1.1357    raeburn  6900:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6901:         if (ref($ltimenu) eq 'HASH') {
                   6902:             unless ($ltimenu->{'role'}) {
                   6903:                 undef($role);
                   6904:             }
                   6905:             unless ($ltimenu->{'coursetitle'}) {
                   6906:                 $realm='&nbsp;';
1.1359    raeburn  6907:                 $showcrstitle = 0;
                   6908:             }
                   6909:         }
                   6910:     } elsif (($cid) && ($menucoll)) {
                   6911:         if (ref($menuref) eq 'HASH') {
                   6912:             unless ($menuref->{'role'}) {
                   6913:                 undef($role);
                   6914:             }
                   6915:             unless ($menuref->{'crs'}) {
                   6916:                 $realm='&nbsp;';
                   6917:                 $showcrstitle = 0;
1.1318    raeburn  6918:             }
                   6919:         }
                   6920:     }
                   6921: 
1.762     bisitz   6922:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6923:     #
                   6924:     # Extra info if you are the DC
                   6925:     my $dc_info = '';
1.1359    raeburn  6926:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6927:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6928:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6929:         $dc_info =~ s/\s+$//;
1.359     albertel 6930:     }
                   6931: 
1.1237    raeburn  6932:     my $crstype;
1.1357    raeburn  6933:     if ($cid) {
                   6934:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6935:     } elsif ($args->{'crstype'}) {
                   6936:         $crstype = $args->{'crstype'};
                   6937:     }
                   6938:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6939:         undef($role);
                   6940:     } else {
1.1242    raeburn  6941:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6942:     }
1.853     droeschl 6943: 
1.903     droeschl 6944:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6945: 
                   6946:         #    if ($env{'request.state'} eq 'construct') {
                   6947:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6948:         #    }
                   6949: 
1.1130    raeburn  6950:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6951:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6952: 
1.1427  ! raeburn  6953:         my $collapsible;
1.1423    raeburn  6954:         if ($args->{'collapsible_header'} ne '') {
1.1427  ! raeburn  6955:             $collapsible = 1;
        !          6956:             my ($menustate,$tiptext,$divclass);
        !          6957:             if ($args->{'start_collapsed'}) {
        !          6958:                 $menustate = 'collapsed';
        !          6959:                 $tiptext = 'display';
        !          6960:                 $divclass = 'hidden';
        !          6961:             } else {
        !          6962:                 $menustate = 'expanded';
        !          6963:                 $tiptext = 'hide';
        !          6964:                 $divclass = 'shown';
        !          6965:             }
        !          6966:             my $alttext = &mt('menu state: '.$menustate);
        !          6967:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  6968:             $bodytag .= <<"END";
                   6969: <div id="LC_expandingContainer" style="display:inline;">
                   6970: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427  ! raeburn  6971: <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>
        !          6972: <div class="LC_menus_content $divclass">
1.1421    raeburn  6973: END
                   6974:         }
1.1318    raeburn  6975:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6976:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6977:                                                               $args->{'links_disabled'},
1.1421    raeburn  6978:                                                               $args->{'links_target'},
1.1427  ! raeburn  6979:                                                               $collapsible);
1.359     albertel 6980: 
1.1318    raeburn  6981:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6982:                 if ($dc_info) {
                   6983:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6984:                 }
                   6985:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6986:                                <em>$realm</em> $dc_info</div>|;
                   6987:                 return $bodytag;
                   6988:             }
1.894     droeschl 6989: 
1.1318    raeburn  6990:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6991:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6992:             }
1.916     droeschl 6993: 
1.1318    raeburn  6994:             $bodytag .= $right;
1.852     droeschl 6995: 
1.1318    raeburn  6996:             if ($dc_info) {
                   6997:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6998:             }
                   6999:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  7000:         }
1.916     droeschl 7001: 
1.1169    raeburn  7002:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7003:         if ($args->{'no_secondary_menu'}) {
                   7004:             return $bodytag;
                   7005:         }
1.1169    raeburn  7006:         #don't show menus for public users
1.954     raeburn  7007:         if (!$public){
1.1318    raeburn  7008:             unless ($args->{'no_inline_menu'}) {
                   7009:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7010:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7011:                                                             $menucoll,$menuref,
1.1380    raeburn  7012:                                                             $args->{'links_disabled'},
                   7013:                                                             $args->{'links_target'});
1.1318    raeburn  7014:             }
1.903     droeschl 7015:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  7016:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7017:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7018:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7019:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7020:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7021:             } elsif ($forcereg) {
                   7022:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7023:                                 $args->{'group'},$args->{'hide_buttons'},
                   7024:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7025:             } else {
                   7026:                 $bodytag .= 
                   7027:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7028:                                                         $forcereg,$args->{'group'},
                   7029:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7030:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7031:             }
1.903     droeschl 7032:         }else{
                   7033:             # this is to seperate menu from content when there's no secondary
                   7034:             # menu. Especially needed for public accessible ressources.
                   7035:             $bodytag .= '<hr style="clear:both" />';
                   7036:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  7037:         }
1.1423    raeburn  7038:         if ($args->{'collapsible_header'} ne '') {
                   7039:             $bodytag .= $args->{'collapsible_header'}.
                   7040:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7041:                         '</div></div>';
                   7042:         }
1.235     raeburn  7043:         return $bodytag;
1.182     matthew  7044: }
                   7045: 
1.917     raeburn  7046: sub dc_courseid_toggle {
                   7047:     my ($dc_info) = @_;
1.980     raeburn  7048:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7049:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7050:            &mt('(More ...)').'</a></span>'.
                   7051:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7052: }
                   7053: 
1.330     albertel 7054: sub make_attr_string {
                   7055:     my ($register,$attr_ref) = @_;
                   7056: 
                   7057:     if ($attr_ref && !ref($attr_ref)) {
                   7058: 	die("addentries Must be a hash ref ".
                   7059: 	    join(':',caller(1))." ".
                   7060: 	    join(':',caller(0))." ");
                   7061:     }
                   7062: 
                   7063:     if ($register) {
1.339     albertel 7064: 	my ($on_load,$on_unload);
                   7065: 	foreach my $key (keys(%{$attr_ref})) {
                   7066: 	    if      (lc($key) eq 'onload') {
                   7067: 		$on_load.=$attr_ref->{$key}.';';
                   7068: 		delete($attr_ref->{$key});
                   7069: 
                   7070: 	    } elsif (lc($key) eq 'onunload') {
                   7071: 		$on_unload.=$attr_ref->{$key}.';';
                   7072: 		delete($attr_ref->{$key});
                   7073: 	    }
                   7074: 	}
1.953     droeschl 7075: 	$attr_ref->{'onload'}  = $on_load;
                   7076: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7077:     }
1.339     albertel 7078: 
1.330     albertel 7079:     my $attr_string;
1.1159    raeburn  7080:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7081: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7082:     }
                   7083:     return $attr_string;
                   7084: }
                   7085: 
                   7086: 
1.182     matthew  7087: ###############################################
1.251     albertel 7088: ###############################################
                   7089: 
                   7090: =pod
                   7091: 
                   7092: =item * &endbodytag()
                   7093: 
                   7094: Returns a uniform footer for LON-CAPA web pages.
                   7095: 
1.635     raeburn  7096: Inputs: 1 - optional reference to an args hash
                   7097: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7098: a 'Continue' link is not displayed if the page contains an
                   7099: internal redirect in the <head></head> section,
                   7100: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7101: 
                   7102: =cut
                   7103: 
                   7104: sub endbodytag {
1.635     raeburn  7105:     my ($args) = @_;
1.1080    raeburn  7106:     my $endbodytag;
                   7107:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7108:         $endbodytag='</body>';
                   7109:     }
1.315     albertel 7110:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7111:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7112:             my ($endbodyjs,$idattr);
                   7113:             if ($env{'internal.head.to_opener'}) {
                   7114:                 my $linkid = 'LC_continue_link';
                   7115:                 $idattr = ' id="'.$linkid.'"';
                   7116:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7117:                 $endbodyjs=<<ENDJS;
                   7118: <script type="text/javascript">
                   7119: // <![CDATA[
                   7120: function ebFunction(evt) {
                   7121:     evt.preventDefault();
                   7122:     var dest = '$redirect_for_js';
                   7123:     if (window.opener != null && !window.opener.closed) {
                   7124:         window.opener.location.href=dest;
                   7125:         window.close();
                   7126:     } else {
                   7127:         window.location.href=dest;
                   7128:     }
                   7129:     return false;
                   7130: }
                   7131: 
                   7132: \$(document).ready(function () {
                   7133:   if (document.getElementById('$linkid')) {
                   7134:     var clickelem = document.getElementById('$linkid');
                   7135:     clickelem.addEventListener('click',ebFunction,false);
                   7136:   }
                   7137: });
                   7138: // ]]>
                   7139: </script>
                   7140: ENDJS
                   7141:             }
1.635     raeburn  7142: 	    $endbodytag=
1.1386    raeburn  7143: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7144: 	        &mt('Continue').'</a>'.
                   7145: 	        $endbodytag;
                   7146:         }
1.315     albertel 7147:     }
1.1411    raeburn  7148:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7149:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7150:     }
1.251     albertel 7151:     return $endbodytag;
                   7152: }
                   7153: 
1.352     albertel 7154: =pod
                   7155: 
                   7156: =item * &standard_css()
                   7157: 
                   7158: Returns a style sheet
                   7159: 
                   7160: Inputs: (all optional)
                   7161:             domain         -> force to color decorate a page for a specific
                   7162:                                domain
                   7163:             function       -> force usage of a specific rolish color scheme
                   7164:             bgcolor        -> override the default page bgcolor
                   7165: 
                   7166: =cut
                   7167: 
1.343     albertel 7168: sub standard_css {
1.345     albertel 7169:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7170:     $function  = &get_users_function() if (!$function);
                   7171:     my $img    = &designparm($function.'.img',   $domain);
                   7172:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7173:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7174:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7175: #second colour for later usage
1.345     albertel 7176:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7177:     my $pgbg_or_bgcolor =
                   7178: 	         $bgcolor ||
1.352     albertel 7179: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7180:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7181:     my $alink  = &designparm($function.'.alink', $domain);
                   7182:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7183:     my $link   = &designparm($function.'.link',  $domain);
                   7184: 
1.602     albertel 7185:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7186:     my $mono                 = 'monospace';
1.850     bisitz   7187:     my $data_table_head      = $sidebg;
                   7188:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7189:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7190:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7191:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7192:     my $mail_new             = '#FFBB77';
                   7193:     my $mail_new_hover       = '#DD9955';
                   7194:     my $mail_read            = '#BBBB77';
                   7195:     my $mail_read_hover      = '#999944';
                   7196:     my $mail_replied         = '#AAAA88';
                   7197:     my $mail_replied_hover   = '#888855';
                   7198:     my $mail_other           = '#99BBBB';
                   7199:     my $mail_other_hover     = '#669999';
1.391     albertel 7200:     my $table_header         = '#DDDDDD';
1.489     raeburn  7201:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7202:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7203:     my $button_hover         = '#BF2317';
1.392     albertel 7204: 
1.608     albertel 7205:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7206:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7207:                                              : '0 3px 0 4px';
1.448     albertel 7208: 
1.523     albertel 7209: 
1.343     albertel 7210:     return <<END;
1.947     droeschl 7211: 
                   7212: /* needed for iframe to allow 100% height in FF */
                   7213: body, html { 
                   7214:     margin: 0;
                   7215:     padding: 0 0.5%;
                   7216:     height: 99%; /* to avoid scrollbars */
                   7217: }
                   7218: 
1.795     www      7219: body {
1.911     bisitz   7220:   font-family: $sans;
                   7221:   line-height:130%;
                   7222:   font-size:0.83em;
                   7223:   color:$font;
1.795     www      7224: }
                   7225: 
1.959     onken    7226: a:focus,
                   7227: a:focus img {
1.795     www      7228:   color: red;
                   7229: }
1.698     harmsja  7230: 
1.911     bisitz   7231: form, .inline {
                   7232:   display: inline;
1.795     www      7233: }
1.721     harmsja  7234: 
1.1421    raeburn  7235: .LC_menus_content.shown{
                   7236:   display: inline;
                   7237: }
                   7238: 
                   7239: .LC_menus_content.hidden {
                   7240:   display: none;
                   7241: }
                   7242: 
1.795     www      7243: .LC_right {
1.911     bisitz   7244:   text-align:right;
1.795     www      7245: }
                   7246: 
                   7247: .LC_middle {
1.911     bisitz   7248:   vertical-align:middle;
1.795     www      7249: }
1.721     harmsja  7250: 
1.1130    raeburn  7251: .LC_floatleft {
                   7252:   float: left;
                   7253: }
                   7254: 
                   7255: .LC_floatright {
                   7256:   float: right;
                   7257: }
                   7258: 
1.911     bisitz   7259: .LC_400Box {
                   7260:   width:400px;
                   7261: }
1.721     harmsja  7262: 
1.1421    raeburn  7263: #LC_collapsible_separator {
                   7264:     border: 1px solid black;
                   7265:     width: 99.9%;
                   7266:     height: 0px;
                   7267: }
                   7268: 
1.947     droeschl 7269: .LC_iframecontainer {
                   7270:     width: 98%;
                   7271:     margin: 0;
                   7272:     position: fixed;
                   7273:     top: 8.5em;
                   7274:     bottom: 0;
                   7275: }
                   7276: 
                   7277: .LC_iframecontainer iframe{
                   7278:     border: none;
                   7279:     width: 100%;
                   7280:     height: 100%;
                   7281: }
                   7282: 
1.778     bisitz   7283: .LC_filename {
                   7284:   font-family: $mono;
                   7285:   white-space:pre;
1.921     bisitz   7286:   font-size: 120%;
1.778     bisitz   7287: }
                   7288: 
                   7289: .LC_fileicon {
                   7290:   border: none;
                   7291:   height: 1.3em;
                   7292:   vertical-align: text-bottom;
                   7293:   margin-right: 0.3em;
                   7294:   text-decoration:none;
                   7295: }
                   7296: 
1.1008    www      7297: .LC_setting {
                   7298:   text-decoration:underline;
                   7299: }
                   7300: 
1.350     albertel 7301: .LC_error {
                   7302:   color: red;
                   7303: }
1.795     www      7304: 
1.1097    bisitz   7305: .LC_warning {
                   7306:   color: darkorange;
                   7307: }
                   7308: 
1.457     albertel 7309: .LC_diff_removed {
1.733     bisitz   7310:   color: red;
1.394     albertel 7311: }
1.532     albertel 7312: 
                   7313: .LC_info,
1.457     albertel 7314: .LC_success,
                   7315: .LC_diff_added {
1.350     albertel 7316:   color: green;
                   7317: }
1.795     www      7318: 
1.802     bisitz   7319: div.LC_confirm_box {
                   7320:   background-color: #FAFAFA;
                   7321:   border: 1px solid $lg_border_color;
                   7322:   margin-right: 0;
                   7323:   padding: 5px;
                   7324: }
                   7325: 
                   7326: div.LC_confirm_box .LC_error img,
                   7327: div.LC_confirm_box .LC_success img {
                   7328:   vertical-align: middle;
                   7329: }
                   7330: 
1.1242    raeburn  7331: .LC_maxwidth {
                   7332:   max-width: 100%;
                   7333:   height: auto;
                   7334: }
                   7335: 
1.1243    raeburn  7336: .LC_textsize_mobile {
                   7337:   \@media only screen and (max-device-width: 480px) {
                   7338:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7339:   }
                   7340: }
                   7341: 
1.440     albertel 7342: .LC_icon {
1.771     droeschl 7343:   border: none;
1.790     droeschl 7344:   vertical-align: middle;
1.771     droeschl 7345: }
                   7346: 
1.543     albertel 7347: .LC_docs_spacer {
                   7348:   width: 25px;
                   7349:   height: 1px;
1.771     droeschl 7350:   border: none;
1.543     albertel 7351: }
1.346     albertel 7352: 
1.532     albertel 7353: .LC_internal_info {
1.735     bisitz   7354:   color: #999999;
1.532     albertel 7355: }
                   7356: 
1.794     www      7357: .LC_discussion {
1.1050    www      7358:   background: $data_table_dark;
1.911     bisitz   7359:   border: 1px solid black;
                   7360:   margin: 2px;
1.794     www      7361: }
                   7362: 
                   7363: .LC_disc_action_left {
1.1050    www      7364:   background: $sidebg;
1.911     bisitz   7365:   text-align: left;
1.1050    www      7366:   padding: 4px;
                   7367:   margin: 2px;
1.794     www      7368: }
                   7369: 
                   7370: .LC_disc_action_right {
1.1050    www      7371:   background: $sidebg;
1.911     bisitz   7372:   text-align: right;
1.1050    www      7373:   padding: 4px;
                   7374:   margin: 2px;
1.794     www      7375: }
                   7376: 
                   7377: .LC_disc_new_item {
1.911     bisitz   7378:   background: white;
                   7379:   border: 2px solid red;
1.1050    www      7380:   margin: 4px;
                   7381:   padding: 4px;
1.794     www      7382: }
                   7383: 
                   7384: .LC_disc_old_item {
1.911     bisitz   7385:   background: white;
1.1050    www      7386:   margin: 4px;
                   7387:   padding: 4px;
1.794     www      7388: }
                   7389: 
1.458     albertel 7390: table.LC_pastsubmission {
                   7391:   border: 1px solid black;
                   7392:   margin: 2px;
                   7393: }
                   7394: 
1.924     bisitz   7395: table#LC_menubuttons {
1.345     albertel 7396:   width: 100%;
                   7397:   background: $pgbg;
1.392     albertel 7398:   border: 2px;
1.402     albertel 7399:   border-collapse: separate;
1.803     bisitz   7400:   padding: 0;
1.345     albertel 7401: }
1.392     albertel 7402: 
1.801     tempelho 7403: table#LC_title_bar a {
                   7404:   color: $fontmenu;
                   7405: }
1.836     bisitz   7406: 
1.807     droeschl 7407: table#LC_title_bar {
1.819     tempelho 7408:   clear: both;
1.836     bisitz   7409:   display: none;
1.807     droeschl 7410: }
                   7411: 
1.795     www      7412: table#LC_title_bar,
1.933     droeschl 7413: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7414: table#LC_title_bar.LC_with_remote {
1.359     albertel 7415:   width: 100%;
1.392     albertel 7416:   border-color: $pgbg;
                   7417:   border-style: solid;
                   7418:   border-width: $border;
1.379     albertel 7419:   background: $pgbg;
1.801     tempelho 7420:   color: $fontmenu;
1.392     albertel 7421:   border-collapse: collapse;
1.803     bisitz   7422:   padding: 0;
1.819     tempelho 7423:   margin: 0;
1.359     albertel 7424: }
1.795     www      7425: 
1.933     droeschl 7426: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7427:     margin: 0;
                   7428:     padding: 0;
1.933     droeschl 7429:     position: relative;
                   7430:     list-style: none;
1.913     droeschl 7431: }
1.933     droeschl 7432: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7433:     display: inline;
                   7434: }
1.933     droeschl 7435: 
                   7436: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7437:     padding: 0;
1.933     droeschl 7438:     margin: 0;
                   7439:     float: left;
1.913     droeschl 7440: }
1.933     droeschl 7441: .LC_breadcrumb_tools_tools {
                   7442:     padding: 0;
                   7443:     margin: 0;
1.913     droeschl 7444:     float: right;
                   7445: }
                   7446: 
1.1240    raeburn  7447: .LC_placement_prog {
                   7448:     padding-right: 20px;
                   7449:     font-weight: bold;
                   7450:     font-size: 90%;
                   7451: }
                   7452: 
1.359     albertel 7453: table#LC_title_bar td {
                   7454:   background: $tabbg;
                   7455: }
1.795     www      7456: 
1.911     bisitz   7457: table#LC_menubuttons img {
1.803     bisitz   7458:   border: none;
1.346     albertel 7459: }
1.795     www      7460: 
1.842     droeschl 7461: .LC_breadcrumbs_component {
1.911     bisitz   7462:   float: right;
                   7463:   margin: 0 1em;
1.357     albertel 7464: }
1.842     droeschl 7465: .LC_breadcrumbs_component img {
1.911     bisitz   7466:   vertical-align: middle;
1.777     tempelho 7467: }
1.795     www      7468: 
1.1243    raeburn  7469: .LC_breadcrumbs_hoverable {
                   7470:   background: $sidebg;
                   7471: }
                   7472: 
1.383     albertel 7473: td.LC_table_cell_checkbox {
                   7474:   text-align: center;
                   7475: }
1.795     www      7476: 
                   7477: .LC_fontsize_small {
1.911     bisitz   7478:   font-size: 70%;
1.705     tempelho 7479: }
                   7480: 
1.844     bisitz   7481: #LC_breadcrumbs {
1.911     bisitz   7482:   clear:both;
                   7483:   background: $sidebg;
                   7484:   border-bottom: 1px solid $lg_border_color;
                   7485:   line-height: 2.5em;
1.933     droeschl 7486:   overflow: hidden;
1.911     bisitz   7487:   margin: 0;
                   7488:   padding: 0;
1.995     raeburn  7489:   text-align: left;
1.819     tempelho 7490: }
1.862     bisitz   7491: 
1.1098    bisitz   7492: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7493:   clear:both;
                   7494:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7495:   border: 1px solid $sidebg;
1.1098    bisitz   7496:   margin: 0 0 10px 0;
1.966     bisitz   7497:   padding: 3px;
1.995     raeburn  7498:   text-align: left;
1.822     bisitz   7499: }
                   7500: 
1.795     www      7501: .LC_fontsize_medium {
1.911     bisitz   7502:   font-size: 85%;
1.705     tempelho 7503: }
                   7504: 
1.795     www      7505: .LC_fontsize_large {
1.911     bisitz   7506:   font-size: 120%;
1.705     tempelho 7507: }
                   7508: 
1.346     albertel 7509: .LC_menubuttons_inline_text {
                   7510:   color: $font;
1.698     harmsja  7511:   font-size: 90%;
1.701     harmsja  7512:   padding-left:3px;
1.346     albertel 7513: }
                   7514: 
1.934     droeschl 7515: .LC_menubuttons_inline_text img{
                   7516:   vertical-align: middle;
                   7517: }
                   7518: 
1.1051    www      7519: li.LC_menubuttons_inline_text img {
1.951     onken    7520:   cursor:pointer;
1.1002    droeschl 7521:   text-decoration: none;
1.951     onken    7522: }
                   7523: 
1.526     www      7524: .LC_menubuttons_link {
                   7525:   text-decoration: none;
                   7526: }
1.795     www      7527: 
1.522     albertel 7528: .LC_menubuttons_category {
1.521     www      7529:   color: $font;
1.526     www      7530:   background: $pgbg;
1.521     www      7531:   font-size: larger;
                   7532:   font-weight: bold;
                   7533: }
                   7534: 
1.346     albertel 7535: td.LC_menubuttons_text {
1.911     bisitz   7536:   color: $font;
1.346     albertel 7537: }
1.706     harmsja  7538: 
1.346     albertel 7539: .LC_current_location {
                   7540:   background: $tabbg;
                   7541: }
1.795     www      7542: 
1.1286    raeburn  7543: td.LC_zero_height {
                   7544:   line-height: 0; 
                   7545:   cellpadding: 0;
                   7546: }
                   7547: 
1.938     bisitz   7548: table.LC_data_table {
1.347     albertel 7549:   border: 1px solid #000000;
1.402     albertel 7550:   border-collapse: separate;
1.426     albertel 7551:   border-spacing: 1px;
1.610     albertel 7552:   background: $pgbg;
1.347     albertel 7553: }
1.795     www      7554: 
1.422     albertel 7555: .LC_data_table_dense {
                   7556:   font-size: small;
                   7557: }
1.795     www      7558: 
1.507     raeburn  7559: table.LC_nested_outer {
                   7560:   border: 1px solid #000000;
1.589     raeburn  7561:   border-collapse: collapse;
1.803     bisitz   7562:   border-spacing: 0;
1.507     raeburn  7563:   width: 100%;
                   7564: }
1.795     www      7565: 
1.879     raeburn  7566: table.LC_innerpickbox,
1.507     raeburn  7567: table.LC_nested {
1.803     bisitz   7568:   border: none;
1.589     raeburn  7569:   border-collapse: collapse;
1.803     bisitz   7570:   border-spacing: 0;
1.507     raeburn  7571:   width: 100%;
                   7572: }
1.795     www      7573: 
1.911     bisitz   7574: table.LC_data_table tr th,
                   7575: table.LC_calendar tr th,
1.879     raeburn  7576: table.LC_prior_tries tr th,
                   7577: table.LC_innerpickbox tr th {
1.349     albertel 7578:   font-weight: bold;
                   7579:   background-color: $data_table_head;
1.801     tempelho 7580:   color:$fontmenu;
1.701     harmsja  7581:   font-size:90%;
1.347     albertel 7582: }
1.795     www      7583: 
1.879     raeburn  7584: table.LC_innerpickbox tr th,
                   7585: table.LC_innerpickbox tr td {
                   7586:   vertical-align: top;
                   7587: }
                   7588: 
1.711     raeburn  7589: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7590:   background-color: #CCCCCC;
1.711     raeburn  7591:   font-weight: bold;
                   7592:   text-align: left;
                   7593: }
1.795     www      7594: 
1.912     bisitz   7595: table.LC_data_table tr.LC_odd_row > td {
                   7596:   background-color: $data_table_light;
                   7597:   padding: 2px;
                   7598:   vertical-align: top;
                   7599: }
                   7600: 
1.809     bisitz   7601: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7602:   background-color: $data_table_light;
1.912     bisitz   7603:   vertical-align: top;
                   7604: }
                   7605: 
                   7606: table.LC_data_table tr.LC_even_row > td {
                   7607:   background-color: $data_table_dark;
1.425     albertel 7608:   padding: 2px;
1.900     bisitz   7609:   vertical-align: top;
1.347     albertel 7610: }
1.795     www      7611: 
1.809     bisitz   7612: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7613:   background-color: $data_table_dark;
1.900     bisitz   7614:   vertical-align: top;
1.347     albertel 7615: }
1.795     www      7616: 
1.425     albertel 7617: table.LC_data_table tr.LC_data_table_highlight td {
                   7618:   background-color: $data_table_darker;
                   7619: }
1.795     www      7620: 
1.639     raeburn  7621: table.LC_data_table tr td.LC_leftcol_header {
                   7622:   background-color: $data_table_head;
                   7623:   font-weight: bold;
                   7624: }
1.795     www      7625: 
1.451     albertel 7626: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7627: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7628:   font-weight: bold;
                   7629:   font-style: italic;
                   7630:   text-align: center;
                   7631:   padding: 8px;
1.347     albertel 7632: }
1.795     www      7633: 
1.1114    raeburn  7634: table.LC_data_table tr.LC_empty_row td,
                   7635: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7636:   background-color: $sidebg;
                   7637: }
                   7638: 
                   7639: table.LC_nested tr.LC_empty_row td {
                   7640:   background-color: #FFFFFF;
                   7641: }
                   7642: 
1.890     droeschl 7643: table.LC_caption {
                   7644: }
                   7645: 
1.507     raeburn  7646: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7647:   padding: 4ex
                   7648: }
1.795     www      7649: 
1.507     raeburn  7650: table.LC_nested_outer tr th {
                   7651:   font-weight: bold;
1.801     tempelho 7652:   color:$fontmenu;
1.507     raeburn  7653:   background-color: $data_table_head;
1.701     harmsja  7654:   font-size: small;
1.507     raeburn  7655:   border-bottom: 1px solid #000000;
                   7656: }
1.795     www      7657: 
1.507     raeburn  7658: table.LC_nested_outer tr td.LC_subheader {
                   7659:   background-color: $data_table_head;
                   7660:   font-weight: bold;
                   7661:   font-size: small;
                   7662:   border-bottom: 1px solid #000000;
                   7663:   text-align: right;
1.451     albertel 7664: }
1.795     www      7665: 
1.507     raeburn  7666: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7667:   background-color: #CCCCCC;
1.451     albertel 7668:   font-weight: bold;
                   7669:   font-size: small;
1.507     raeburn  7670:   text-align: center;
                   7671: }
1.795     www      7672: 
1.589     raeburn  7673: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7674: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7675:   text-align: left;
1.451     albertel 7676: }
1.795     www      7677: 
1.507     raeburn  7678: table.LC_nested td {
1.735     bisitz   7679:   background-color: #FFFFFF;
1.451     albertel 7680:   font-size: small;
1.507     raeburn  7681: }
1.795     www      7682: 
1.507     raeburn  7683: table.LC_nested_outer tr th.LC_right_item,
                   7684: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7685: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7686: table.LC_nested tr td.LC_right_item {
1.451     albertel 7687:   text-align: right;
                   7688: }
                   7689: 
1.507     raeburn  7690: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7691:   background-color: #EEEEEE;
1.451     albertel 7692: }
                   7693: 
1.473     raeburn  7694: table.LC_createuser {
                   7695: }
                   7696: 
                   7697: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7698:   font-size: small;
1.473     raeburn  7699: }
                   7700: 
                   7701: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7702:   background-color: #CCCCCC;
1.473     raeburn  7703:   font-weight: bold;
                   7704:   text-align: center;
                   7705: }
                   7706: 
1.349     albertel 7707: table.LC_calendar {
                   7708:   border: 1px solid #000000;
                   7709:   border-collapse: collapse;
1.917     raeburn  7710:   width: 98%;
1.349     albertel 7711: }
1.795     www      7712: 
1.349     albertel 7713: table.LC_calendar_pickdate {
                   7714:   font-size: xx-small;
                   7715: }
1.795     www      7716: 
1.349     albertel 7717: table.LC_calendar tr td {
                   7718:   border: 1px solid #000000;
                   7719:   vertical-align: top;
1.917     raeburn  7720:   width: 14%;
1.349     albertel 7721: }
1.795     www      7722: 
1.349     albertel 7723: table.LC_calendar tr td.LC_calendar_day_empty {
                   7724:   background-color: $data_table_dark;
                   7725: }
1.795     www      7726: 
1.779     bisitz   7727: table.LC_calendar tr td.LC_calendar_day_current {
                   7728:   background-color: $data_table_highlight;
1.777     tempelho 7729: }
1.795     www      7730: 
1.938     bisitz   7731: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7732:   background-color: $mail_new;
                   7733: }
1.795     www      7734: 
1.938     bisitz   7735: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7736:   background-color: $mail_new_hover;
                   7737: }
1.795     www      7738: 
1.938     bisitz   7739: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7740:   background-color: $mail_read;
                   7741: }
1.795     www      7742: 
1.938     bisitz   7743: /*
                   7744: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7745:   background-color: $mail_read_hover;
                   7746: }
1.938     bisitz   7747: */
1.795     www      7748: 
1.938     bisitz   7749: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7750:   background-color: $mail_replied;
                   7751: }
1.795     www      7752: 
1.938     bisitz   7753: /*
                   7754: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7755:   background-color: $mail_replied_hover;
                   7756: }
1.938     bisitz   7757: */
1.795     www      7758: 
1.938     bisitz   7759: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7760:   background-color: $mail_other;
                   7761: }
1.795     www      7762: 
1.938     bisitz   7763: /*
                   7764: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7765:   background-color: $mail_other_hover;
                   7766: }
1.938     bisitz   7767: */
1.494     raeburn  7768: 
1.777     tempelho 7769: table.LC_data_table tr > td.LC_browser_file,
                   7770: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7771:   background: #AAEE77;
1.389     albertel 7772: }
1.795     www      7773: 
1.777     tempelho 7774: table.LC_data_table tr > td.LC_browser_file_locked,
                   7775: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7776:   background: #FFAA99;
1.387     albertel 7777: }
1.795     www      7778: 
1.777     tempelho 7779: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7780:   background: #888888;
1.779     bisitz   7781: }
1.795     www      7782: 
1.777     tempelho 7783: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7784: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7785:   background: #F8F866;
1.777     tempelho 7786: }
1.795     www      7787: 
1.696     bisitz   7788: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7789:   background: #E0E8FF;
1.387     albertel 7790: }
1.696     bisitz   7791: 
1.707     bisitz   7792: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7793:   /* background: #77FF77; */
1.707     bisitz   7794: }
1.795     www      7795: 
1.707     bisitz   7796: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7797:   border-right: 8px solid #FFFF77;
1.707     bisitz   7798: }
1.795     www      7799: 
1.707     bisitz   7800: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7801:   border-right: 8px solid #FFAA77;
1.707     bisitz   7802: }
1.795     www      7803: 
1.707     bisitz   7804: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7805:   border-right: 8px solid #FF7777;
1.707     bisitz   7806: }
1.795     www      7807: 
1.707     bisitz   7808: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7809:   border-right: 8px solid #AAFF77;
1.707     bisitz   7810: }
1.795     www      7811: 
1.707     bisitz   7812: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7813:   border-right: 8px solid #11CC55;
1.707     bisitz   7814: }
                   7815: 
1.388     albertel 7816: span.LC_current_location {
1.701     harmsja  7817:   font-size:larger;
1.388     albertel 7818:   background: $pgbg;
                   7819: }
1.387     albertel 7820: 
1.1029    www      7821: span.LC_current_nav_location {
                   7822:   font-weight:bold;
                   7823:   background: $sidebg;
                   7824: }
                   7825: 
1.395     albertel 7826: span.LC_parm_menu_item {
                   7827:   font-size: larger;
                   7828: }
1.795     www      7829: 
1.395     albertel 7830: span.LC_parm_scope_all {
                   7831:   color: red;
                   7832: }
1.795     www      7833: 
1.395     albertel 7834: span.LC_parm_scope_folder {
                   7835:   color: green;
                   7836: }
1.795     www      7837: 
1.395     albertel 7838: span.LC_parm_scope_resource {
                   7839:   color: orange;
                   7840: }
1.795     www      7841: 
1.395     albertel 7842: span.LC_parm_part {
                   7843:   color: blue;
                   7844: }
1.795     www      7845: 
1.911     bisitz   7846: span.LC_parm_folder,
                   7847: span.LC_parm_symb {
1.395     albertel 7848:   font-size: x-small;
                   7849:   font-family: $mono;
                   7850:   color: #AAAAAA;
                   7851: }
                   7852: 
1.977     bisitz   7853: ul.LC_parm_parmlist li {
                   7854:   display: inline-block;
                   7855:   padding: 0.3em 0.8em;
                   7856:   vertical-align: top;
                   7857:   width: 150px;
                   7858:   border-top:1px solid $lg_border_color;
                   7859: }
                   7860: 
1.795     www      7861: td.LC_parm_overview_level_menu,
                   7862: td.LC_parm_overview_map_menu,
                   7863: td.LC_parm_overview_parm_selectors,
                   7864: td.LC_parm_overview_restrictions  {
1.396     albertel 7865:   border: 1px solid black;
                   7866:   border-collapse: collapse;
                   7867: }
1.795     www      7868: 
1.1285    raeburn  7869: span.LC_parm_recursive,
                   7870: td.LC_parm_recursive {
                   7871:   font-weight: bold;
                   7872:   font-size: smaller;
                   7873: }
                   7874: 
1.396     albertel 7875: table.LC_parm_overview_restrictions td {
                   7876:   border-width: 1px 4px 1px 4px;
                   7877:   border-style: solid;
                   7878:   border-color: $pgbg;
                   7879:   text-align: center;
                   7880: }
1.795     www      7881: 
1.396     albertel 7882: table.LC_parm_overview_restrictions th {
                   7883:   background: $tabbg;
                   7884:   border-width: 1px 4px 1px 4px;
                   7885:   border-style: solid;
                   7886:   border-color: $pgbg;
                   7887: }
1.795     www      7888: 
1.398     albertel 7889: table#LC_helpmenu {
1.803     bisitz   7890:   border: none;
1.398     albertel 7891:   height: 55px;
1.803     bisitz   7892:   border-spacing: 0;
1.398     albertel 7893: }
                   7894: 
                   7895: table#LC_helpmenu fieldset legend {
                   7896:   font-size: larger;
                   7897: }
1.795     www      7898: 
1.397     albertel 7899: table#LC_helpmenu_links {
                   7900:   width: 100%;
                   7901:   border: 1px solid black;
                   7902:   background: $pgbg;
1.803     bisitz   7903:   padding: 0;
1.397     albertel 7904:   border-spacing: 1px;
                   7905: }
1.795     www      7906: 
1.397     albertel 7907: table#LC_helpmenu_links tr td {
                   7908:   padding: 1px;
                   7909:   background: $tabbg;
1.399     albertel 7910:   text-align: center;
                   7911:   font-weight: bold;
1.397     albertel 7912: }
1.396     albertel 7913: 
1.795     www      7914: table#LC_helpmenu_links a:link,
                   7915: table#LC_helpmenu_links a:visited,
1.397     albertel 7916: table#LC_helpmenu_links a:active {
                   7917:   text-decoration: none;
                   7918:   color: $font;
                   7919: }
1.795     www      7920: 
1.397     albertel 7921: table#LC_helpmenu_links a:hover {
                   7922:   text-decoration: underline;
                   7923:   color: $vlink;
                   7924: }
1.396     albertel 7925: 
1.417     albertel 7926: .LC_chrt_popup_exists {
                   7927:   border: 1px solid #339933;
                   7928:   margin: -1px;
                   7929: }
1.795     www      7930: 
1.417     albertel 7931: .LC_chrt_popup_up {
                   7932:   border: 1px solid yellow;
                   7933:   margin: -1px;
                   7934: }
1.795     www      7935: 
1.417     albertel 7936: .LC_chrt_popup {
                   7937:   border: 1px solid #8888FF;
                   7938:   background: #CCCCFF;
                   7939: }
1.795     www      7940: 
1.421     albertel 7941: table.LC_pick_box {
                   7942:   border-collapse: separate;
                   7943:   background: white;
                   7944:   border: 1px solid black;
                   7945:   border-spacing: 1px;
                   7946: }
1.795     www      7947: 
1.421     albertel 7948: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7949:   background: $sidebg;
1.421     albertel 7950:   font-weight: bold;
1.900     bisitz   7951:   text-align: left;
1.740     bisitz   7952:   vertical-align: top;
1.421     albertel 7953:   width: 184px;
                   7954:   padding: 8px;
                   7955: }
1.795     www      7956: 
1.579     raeburn  7957: table.LC_pick_box td.LC_pick_box_value {
                   7958:   text-align: left;
                   7959:   padding: 8px;
                   7960: }
1.795     www      7961: 
1.579     raeburn  7962: table.LC_pick_box td.LC_pick_box_select {
                   7963:   text-align: left;
                   7964:   padding: 8px;
                   7965: }
1.795     www      7966: 
1.424     albertel 7967: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7968:   padding: 0;
1.421     albertel 7969:   height: 1px;
                   7970:   background: black;
                   7971: }
1.795     www      7972: 
1.421     albertel 7973: table.LC_pick_box td.LC_pick_box_submit {
                   7974:   text-align: right;
                   7975: }
1.795     www      7976: 
1.579     raeburn  7977: table.LC_pick_box td.LC_evenrow_value {
                   7978:   text-align: left;
                   7979:   padding: 8px;
                   7980:   background-color: $data_table_light;
                   7981: }
1.795     www      7982: 
1.579     raeburn  7983: table.LC_pick_box td.LC_oddrow_value {
                   7984:   text-align: left;
                   7985:   padding: 8px;
                   7986:   background-color: $data_table_light;
                   7987: }
1.795     www      7988: 
1.579     raeburn  7989: span.LC_helpform_receipt_cat {
                   7990:   font-weight: bold;
                   7991: }
1.795     www      7992: 
1.424     albertel 7993: table.LC_group_priv_box {
                   7994:   background: white;
                   7995:   border: 1px solid black;
                   7996:   border-spacing: 1px;
                   7997: }
1.795     www      7998: 
1.424     albertel 7999: table.LC_group_priv_box td.LC_pick_box_title {
                   8000:   background: $tabbg;
                   8001:   font-weight: bold;
                   8002:   text-align: right;
                   8003:   width: 184px;
                   8004: }
1.795     www      8005: 
1.424     albertel 8006: table.LC_group_priv_box td.LC_groups_fixed {
                   8007:   background: $data_table_light;
                   8008:   text-align: center;
                   8009: }
1.795     www      8010: 
1.424     albertel 8011: table.LC_group_priv_box td.LC_groups_optional {
                   8012:   background: $data_table_dark;
                   8013:   text-align: center;
                   8014: }
1.795     www      8015: 
1.424     albertel 8016: table.LC_group_priv_box td.LC_groups_functionality {
                   8017:   background: $data_table_darker;
                   8018:   text-align: center;
                   8019:   font-weight: bold;
                   8020: }
1.795     www      8021: 
1.424     albertel 8022: table.LC_group_priv td {
                   8023:   text-align: left;
1.803     bisitz   8024:   padding: 0;
1.424     albertel 8025: }
                   8026: 
                   8027: .LC_navbuttons {
                   8028:   margin: 2ex 0ex 2ex 0ex;
                   8029: }
1.795     www      8030: 
1.423     albertel 8031: .LC_topic_bar {
                   8032:   font-weight: bold;
                   8033:   background: $tabbg;
1.918     wenzelju 8034:   margin: 1em 0em 1em 2em;
1.805     bisitz   8035:   padding: 3px;
1.918     wenzelju 8036:   font-size: 1.2em;
1.423     albertel 8037: }
1.795     www      8038: 
1.423     albertel 8039: .LC_topic_bar span {
1.918     wenzelju 8040:   left: 0.5em;
                   8041:   position: absolute;
1.423     albertel 8042:   vertical-align: middle;
1.918     wenzelju 8043:   font-size: 1.2em;
1.423     albertel 8044: }
1.795     www      8045: 
1.423     albertel 8046: table.LC_course_group_status {
                   8047:   margin: 20px;
                   8048: }
1.795     www      8049: 
1.423     albertel 8050: table.LC_status_selector td {
                   8051:   vertical-align: top;
                   8052:   text-align: center;
1.424     albertel 8053:   padding: 4px;
                   8054: }
1.795     www      8055: 
1.599     albertel 8056: div.LC_feedback_link {
1.616     albertel 8057:   clear: both;
1.829     kalberla 8058:   background: $sidebg;
1.779     bisitz   8059:   width: 100%;
1.829     kalberla 8060:   padding-bottom: 10px;
                   8061:   border: 1px $tabbg solid;
1.833     kalberla 8062:   height: 22px;
                   8063:   line-height: 22px;
                   8064:   padding-top: 5px;
                   8065: }
                   8066: 
                   8067: div.LC_feedback_link img {
                   8068:   height: 22px;
1.867     kalberla 8069:   vertical-align:middle;
1.829     kalberla 8070: }
                   8071: 
1.911     bisitz   8072: div.LC_feedback_link a {
1.829     kalberla 8073:   text-decoration: none;
1.489     raeburn  8074: }
1.795     www      8075: 
1.867     kalberla 8076: div.LC_comblock {
1.911     bisitz   8077:   display:inline;
1.867     kalberla 8078:   color:$font;
                   8079:   font-size:90%;
                   8080: }
                   8081: 
                   8082: div.LC_feedback_link div.LC_comblock {
                   8083:   padding-left:5px;
                   8084: }
                   8085: 
                   8086: div.LC_feedback_link div.LC_comblock a {
                   8087:   color:$font;
                   8088: }
                   8089: 
1.489     raeburn  8090: span.LC_feedback_link {
1.858     bisitz   8091:   /* background: $feedback_link_bg; */
1.599     albertel 8092:   font-size: larger;
                   8093: }
1.795     www      8094: 
1.599     albertel 8095: span.LC_message_link {
1.858     bisitz   8096:   /* background: $feedback_link_bg; */
1.599     albertel 8097:   font-size: larger;
                   8098:   position: absolute;
                   8099:   right: 1em;
1.489     raeburn  8100: }
1.421     albertel 8101: 
1.515     albertel 8102: table.LC_prior_tries {
1.524     albertel 8103:   border: 1px solid #000000;
                   8104:   border-collapse: separate;
                   8105:   border-spacing: 1px;
1.515     albertel 8106: }
1.523     albertel 8107: 
1.515     albertel 8108: table.LC_prior_tries td {
1.524     albertel 8109:   padding: 2px;
1.515     albertel 8110: }
1.523     albertel 8111: 
                   8112: .LC_answer_correct {
1.795     www      8113:   background: lightgreen;
                   8114:   color: darkgreen;
                   8115:   padding: 6px;
1.523     albertel 8116: }
1.795     www      8117: 
1.523     albertel 8118: .LC_answer_charged_try {
1.797     www      8119:   background: #FFAAAA;
1.795     www      8120:   color: darkred;
                   8121:   padding: 6px;
1.523     albertel 8122: }
1.795     www      8123: 
1.779     bisitz   8124: .LC_answer_not_charged_try,
1.523     albertel 8125: .LC_answer_no_grade,
                   8126: .LC_answer_late {
1.795     www      8127:   background: lightyellow;
1.523     albertel 8128:   color: black;
1.795     www      8129:   padding: 6px;
1.523     albertel 8130: }
1.795     www      8131: 
1.523     albertel 8132: .LC_answer_previous {
1.795     www      8133:   background: lightblue;
                   8134:   color: darkblue;
                   8135:   padding: 6px;
1.523     albertel 8136: }
1.795     www      8137: 
1.779     bisitz   8138: .LC_answer_no_message {
1.777     tempelho 8139:   background: #FFFFFF;
                   8140:   color: black;
1.795     www      8141:   padding: 6px;
1.779     bisitz   8142: }
1.795     www      8143: 
1.1334    raeburn  8144: .LC_answer_unknown,
                   8145: .LC_answer_warning {
1.779     bisitz   8146:   background: orange;
                   8147:   color: black;
1.795     www      8148:   padding: 6px;
1.777     tempelho 8149: }
1.795     www      8150: 
1.529     albertel 8151: span.LC_prior_numerical,
                   8152: span.LC_prior_string,
                   8153: span.LC_prior_custom,
                   8154: span.LC_prior_reaction,
                   8155: span.LC_prior_math {
1.925     bisitz   8156:   font-family: $mono;
1.523     albertel 8157:   white-space: pre;
                   8158: }
                   8159: 
1.525     albertel 8160: span.LC_prior_string {
1.925     bisitz   8161:   font-family: $mono;
1.525     albertel 8162:   white-space: pre;
                   8163: }
                   8164: 
1.523     albertel 8165: table.LC_prior_option {
                   8166:   width: 100%;
                   8167:   border-collapse: collapse;
                   8168: }
1.795     www      8169: 
1.911     bisitz   8170: table.LC_prior_rank,
1.795     www      8171: table.LC_prior_match {
1.528     albertel 8172:   border-collapse: collapse;
                   8173: }
1.795     www      8174: 
1.528     albertel 8175: table.LC_prior_option tr td,
                   8176: table.LC_prior_rank tr td,
                   8177: table.LC_prior_match tr td {
1.524     albertel 8178:   border: 1px solid #000000;
1.515     albertel 8179: }
                   8180: 
1.855     bisitz   8181: .LC_nobreak {
1.544     albertel 8182:   white-space: nowrap;
1.519     raeburn  8183: }
                   8184: 
1.576     raeburn  8185: span.LC_cusr_emph {
                   8186:   font-style: italic;
                   8187: }
                   8188: 
1.633     raeburn  8189: span.LC_cusr_subheading {
                   8190:   font-weight: normal;
                   8191:   font-size: 85%;
                   8192: }
                   8193: 
1.861     bisitz   8194: div.LC_docs_entry_move {
1.859     bisitz   8195:   border: 1px solid #BBBBBB;
1.545     albertel 8196:   background: #DDDDDD;
1.861     bisitz   8197:   width: 22px;
1.859     bisitz   8198:   padding: 1px;
                   8199:   margin: 0;
1.545     albertel 8200: }
                   8201: 
1.861     bisitz   8202: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8203: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8204:   font-size: x-small;
                   8205: }
1.795     www      8206: 
1.861     bisitz   8207: .LC_docs_entry_parameter {
                   8208:   white-space: nowrap;
                   8209: }
                   8210: 
1.544     albertel 8211: .LC_docs_copy {
1.545     albertel 8212:   color: #000099;
1.544     albertel 8213: }
1.795     www      8214: 
1.544     albertel 8215: .LC_docs_cut {
1.545     albertel 8216:   color: #550044;
1.544     albertel 8217: }
1.795     www      8218: 
1.544     albertel 8219: .LC_docs_rename {
1.545     albertel 8220:   color: #009900;
1.544     albertel 8221: }
1.795     www      8222: 
1.544     albertel 8223: .LC_docs_remove {
1.545     albertel 8224:   color: #990000;
                   8225: }
                   8226: 
1.1284    raeburn  8227: .LC_docs_alias {
                   8228:   color: #440055;  
                   8229: }
                   8230: 
1.1286    raeburn  8231: .LC_domprefs_email,
1.1284    raeburn  8232: .LC_docs_alias_name,
1.547     albertel 8233: .LC_docs_reinit_warn,
                   8234: .LC_docs_ext_edit {
                   8235:   font-size: x-small;
                   8236: }
                   8237: 
1.545     albertel 8238: table.LC_docs_adddocs td,
                   8239: table.LC_docs_adddocs th {
                   8240:   border: 1px solid #BBBBBB;
                   8241:   padding: 4px;
                   8242:   background: #DDDDDD;
1.543     albertel 8243: }
                   8244: 
1.584     albertel 8245: table.LC_sty_begin {
                   8246:   background: #BBFFBB;
                   8247: }
1.795     www      8248: 
1.584     albertel 8249: table.LC_sty_end {
                   8250:   background: #FFBBBB;
                   8251: }
                   8252: 
1.589     raeburn  8253: table.LC_double_column {
1.803     bisitz   8254:   border-width: 0;
1.589     raeburn  8255:   border-collapse: collapse;
                   8256:   width: 100%;
                   8257:   padding: 2px;
                   8258: }
                   8259: 
                   8260: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8261:   top: 2px;
1.589     raeburn  8262:   left: 2px;
                   8263:   width: 47%;
                   8264:   vertical-align: top;
                   8265: }
                   8266: 
                   8267: table.LC_double_column tr td.LC_right_col {
                   8268:   top: 2px;
1.779     bisitz   8269:   right: 2px;
1.589     raeburn  8270:   width: 47%;
                   8271:   vertical-align: top;
                   8272: }
                   8273: 
1.591     raeburn  8274: div.LC_left_float {
                   8275:   float: left;
                   8276:   padding-right: 5%;
1.597     albertel 8277:   padding-bottom: 4px;
1.591     raeburn  8278: }
                   8279: 
                   8280: div.LC_clear_float_header {
1.597     albertel 8281:   padding-bottom: 2px;
1.591     raeburn  8282: }
                   8283: 
                   8284: div.LC_clear_float_footer {
1.597     albertel 8285:   padding-top: 10px;
1.591     raeburn  8286:   clear: both;
                   8287: }
                   8288: 
1.597     albertel 8289: div.LC_grade_show_user {
1.941     bisitz   8290: /*  border-left: 5px solid $sidebg; */
                   8291:   border-top: 5px solid #000000;
                   8292:   margin: 50px 0 0 0;
1.936     bisitz   8293:   padding: 15px 0 5px 10px;
1.597     albertel 8294: }
1.795     www      8295: 
1.936     bisitz   8296: div.LC_grade_show_user_odd_row {
1.941     bisitz   8297: /*  border-left: 5px solid #000000; */
                   8298: }
                   8299: 
                   8300: div.LC_grade_show_user div.LC_Box {
                   8301:   margin-right: 50px;
1.597     albertel 8302: }
                   8303: 
                   8304: div.LC_grade_submissions,
                   8305: div.LC_grade_message_center,
1.936     bisitz   8306: div.LC_grade_info_links {
1.597     albertel 8307:   margin: 5px;
                   8308:   width: 99%;
                   8309:   background: #FFFFFF;
                   8310: }
1.795     www      8311: 
1.597     albertel 8312: div.LC_grade_submissions_header,
1.936     bisitz   8313: div.LC_grade_message_center_header {
1.705     tempelho 8314:   font-weight: bold;
                   8315:   font-size: large;
1.597     albertel 8316: }
1.795     www      8317: 
1.597     albertel 8318: div.LC_grade_submissions_body,
1.936     bisitz   8319: div.LC_grade_message_center_body {
1.597     albertel 8320:   border: 1px solid black;
                   8321:   width: 99%;
                   8322:   background: #FFFFFF;
                   8323: }
1.795     www      8324: 
1.613     albertel 8325: table.LC_scantron_action {
                   8326:   width: 100%;
                   8327: }
1.795     www      8328: 
1.613     albertel 8329: table.LC_scantron_action tr th {
1.698     harmsja  8330:   font-weight:bold;
                   8331:   font-style:normal;
1.613     albertel 8332: }
1.795     www      8333: 
1.779     bisitz   8334: .LC_edit_problem_header,
1.614     albertel 8335: div.LC_edit_problem_footer {
1.705     tempelho 8336:   font-weight: normal;
                   8337:   font-size:  medium;
1.602     albertel 8338:   margin: 2px;
1.1060    bisitz   8339:   background-color: $sidebg;
1.600     albertel 8340: }
1.795     www      8341: 
1.600     albertel 8342: div.LC_edit_problem_header,
1.602     albertel 8343: div.LC_edit_problem_header div,
1.614     albertel 8344: div.LC_edit_problem_footer,
                   8345: div.LC_edit_problem_footer div,
1.602     albertel 8346: div.LC_edit_problem_editxml_header,
                   8347: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8348:   z-index: 100;
1.600     albertel 8349: }
1.795     www      8350: 
1.600     albertel 8351: div.LC_edit_problem_header_title {
1.705     tempelho 8352:   font-weight: bold;
                   8353:   font-size: larger;
1.602     albertel 8354:   background: $tabbg;
                   8355:   padding: 3px;
1.1060    bisitz   8356:   margin: 0 0 5px 0;
1.602     albertel 8357: }
1.795     www      8358: 
1.602     albertel 8359: table.LC_edit_problem_header_title {
                   8360:   width: 100%;
1.600     albertel 8361:   background: $tabbg;
1.602     albertel 8362: }
                   8363: 
1.1205    golterma 8364: div.LC_edit_actionbar {
                   8365:     background-color: $sidebg;
1.1218    droeschl 8366:     margin: 0;
                   8367:     padding: 0;
                   8368:     line-height: 200%;
1.602     albertel 8369: }
1.795     www      8370: 
1.1218    droeschl 8371: div.LC_edit_actionbar div{
                   8372:     padding: 0;
                   8373:     margin: 0;
                   8374:     display: inline-block;
1.600     albertel 8375: }
1.795     www      8376: 
1.1124    bisitz   8377: .LC_edit_opt {
                   8378:   padding-left: 1em;
                   8379:   white-space: nowrap;
                   8380: }
                   8381: 
1.1152    golterma 8382: .LC_edit_problem_latexhelper{
                   8383:     text-align: right;
                   8384: }
                   8385: 
                   8386: #LC_edit_problem_colorful div{
                   8387:     margin-left: 40px;
                   8388: }
                   8389: 
1.1205    golterma 8390: #LC_edit_problem_codemirror div{
                   8391:     margin-left: 0px;
                   8392: }
                   8393: 
1.911     bisitz   8394: img.stift {
1.803     bisitz   8395:   border-width: 0;
                   8396:   vertical-align: middle;
1.677     riegler  8397: }
1.680     riegler  8398: 
1.923     bisitz   8399: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8400:   vertical-align: top;
1.777     tempelho 8401: }
1.795     www      8402: 
1.716     raeburn  8403: div.LC_createcourse {
1.911     bisitz   8404:   margin: 10px 10px 10px 10px;
1.716     raeburn  8405: }
                   8406: 
1.917     raeburn  8407: .LC_dccid {
1.1130    raeburn  8408:   float: right;
1.917     raeburn  8409:   margin: 0.2em 0 0 0;
                   8410:   padding: 0;
                   8411:   font-size: 90%;
                   8412:   display:none;
                   8413: }
                   8414: 
1.897     wenzelju 8415: ol.LC_primary_menu a:hover,
1.721     harmsja  8416: ol#LC_MenuBreadcrumbs a:hover,
                   8417: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8418: ul#LC_secondary_menu a:hover,
1.721     harmsja  8419: .LC_FormSectionClearButton input:hover
1.795     www      8420: ul.LC_TabContent   li:hover a {
1.952     onken    8421:   color:$button_hover;
1.911     bisitz   8422:   text-decoration:none;
1.693     droeschl 8423: }
                   8424: 
1.779     bisitz   8425: h1 {
1.911     bisitz   8426:   padding: 0;
                   8427:   line-height:130%;
1.693     droeschl 8428: }
1.698     harmsja  8429: 
1.911     bisitz   8430: h2,
                   8431: h3,
                   8432: h4,
                   8433: h5,
                   8434: h6 {
                   8435:   margin: 5px 0 5px 0;
                   8436:   padding: 0;
                   8437:   line-height:130%;
1.693     droeschl 8438: }
1.795     www      8439: 
                   8440: .LC_hcell {
1.911     bisitz   8441:   padding:3px 15px 3px 15px;
                   8442:   margin: 0;
                   8443:   background-color:$tabbg;
                   8444:   color:$fontmenu;
                   8445:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8446: }
1.795     www      8447: 
1.840     bisitz   8448: .LC_Box > .LC_hcell {
1.911     bisitz   8449:   margin: 0 -10px 10px -10px;
1.835     bisitz   8450: }
                   8451: 
1.721     harmsja  8452: .LC_noBorder {
1.911     bisitz   8453:   border: 0;
1.698     harmsja  8454: }
1.693     droeschl 8455: 
1.721     harmsja  8456: .LC_FormSectionClearButton input {
1.911     bisitz   8457:   background-color:transparent;
                   8458:   border: none;
                   8459:   cursor:pointer;
                   8460:   text-decoration:underline;
1.693     droeschl 8461: }
1.763     bisitz   8462: 
                   8463: .LC_help_open_topic {
1.911     bisitz   8464:   color: #FFFFFF;
                   8465:   background-color: #EEEEFF;
                   8466:   margin: 1px;
                   8467:   padding: 4px;
                   8468:   border: 1px solid #000033;
                   8469:   white-space: nowrap;
                   8470:   /* vertical-align: middle; */
1.759     neumanie 8471: }
1.693     droeschl 8472: 
1.911     bisitz   8473: dl,
                   8474: ul,
                   8475: div,
                   8476: fieldset {
                   8477:   margin: 10px 10px 10px 0;
                   8478:   /* overflow: hidden; */
1.693     droeschl 8479: }
1.795     www      8480: 
1.1404    raeburn  8481: fieldset#LC_selectuser {
                   8482:     margin: 0;
                   8483:     padding: 0;
                   8484: }
                   8485: 
1.1211    raeburn  8486: article.geogebraweb div {
                   8487:     margin: 0;
                   8488: }
                   8489: 
1.838     bisitz   8490: fieldset > legend {
1.911     bisitz   8491:   font-weight: bold;
                   8492:   padding: 0 5px 0 5px;
1.838     bisitz   8493: }
                   8494: 
1.813     bisitz   8495: #LC_nav_bar {
1.911     bisitz   8496:   float: left;
1.995     raeburn  8497:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8498:   margin: 0 0 2px 0;
1.807     droeschl 8499: }
                   8500: 
1.916     droeschl 8501: #LC_realm {
                   8502:   margin: 0.2em 0 0 0;
                   8503:   padding: 0;
                   8504:   font-weight: bold;
                   8505:   text-align: center;
1.995     raeburn  8506:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8507: }
                   8508: 
1.911     bisitz   8509: #LC_nav_bar em {
                   8510:   font-weight: bold;
                   8511:   font-style: normal;
1.807     droeschl 8512: }
                   8513: 
1.897     wenzelju 8514: ol.LC_primary_menu {
1.934     droeschl 8515:   margin: 0;
1.1076    raeburn  8516:   padding: 0;
1.807     droeschl 8517: }
                   8518: 
1.852     droeschl 8519: ol#LC_PathBreadcrumbs {
1.911     bisitz   8520:   margin: 0;
1.693     droeschl 8521: }
                   8522: 
1.897     wenzelju 8523: ol.LC_primary_menu li {
1.1076    raeburn  8524:   color: RGB(80, 80, 80);
                   8525:   vertical-align: middle;
                   8526:   text-align: left;
                   8527:   list-style: none;
1.1205    golterma 8528:   position: relative;
1.1076    raeburn  8529:   float: left;
1.1205    golterma 8530:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8531:   line-height: 1.5em;
1.1076    raeburn  8532: }
                   8533: 
1.1205    golterma 8534: ol.LC_primary_menu li a,
                   8535: ol.LC_primary_menu li p {
1.1076    raeburn  8536:   display: block;
                   8537:   margin: 0;
                   8538:   padding: 0 5px 0 10px;
                   8539:   text-decoration: none;
                   8540: }
                   8541: 
1.1205    golterma 8542: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8543:   display: inline-block;
                   8544:   width: 95%;
                   8545:   text-align: left;
                   8546: }
                   8547: 
                   8548: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8549:   display: inline-block;	
                   8550:   width: 5%;
                   8551:   float: right;
                   8552:   text-align: right;
                   8553:   font-size: 70%;
                   8554: }
                   8555: 
                   8556: ol.LC_primary_menu ul {
1.1076    raeburn  8557:   display: none;
1.1205    golterma 8558:   width: 15em;
1.1076    raeburn  8559:   background-color: $data_table_light;
1.1205    golterma 8560:   position: absolute;
                   8561:   top: 100%;
1.1076    raeburn  8562: }
                   8563: 
1.1205    golterma 8564: ol.LC_primary_menu ul ul {
                   8565:   left: 100%;
                   8566:   top: 0;
                   8567: }
                   8568: 
                   8569: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8570:   display: block;
                   8571:   position: absolute;
                   8572:   margin: 0;
                   8573:   padding: 0;
1.1078    raeburn  8574:   z-index: 2;
1.1076    raeburn  8575: }
                   8576: 
                   8577: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8578: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8579:   font-size: 90%;
1.911     bisitz   8580:   vertical-align: top;
1.1076    raeburn  8581:   float: none;
1.1079    raeburn  8582:   border-left: 1px solid black;
                   8583:   border-right: 1px solid black;
1.1205    golterma 8584: /* A dark bottom border to visualize different menu options; 
                   8585: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8586:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8587: }
                   8588: 
1.1205    golterma 8589: ol.LC_primary_menu li li p:hover {
                   8590:   color:$button_hover;
                   8591:   text-decoration:none;
                   8592:   background-color:$data_table_dark;
1.1076    raeburn  8593: }
                   8594: 
                   8595: ol.LC_primary_menu li li a:hover {
                   8596:    color:$button_hover;
                   8597:    background-color:$data_table_dark;
1.693     droeschl 8598: }
                   8599: 
1.1205    golterma 8600: /* Font-size equal to the size of the predecessors*/
                   8601: ol.LC_primary_menu li:hover li li {
                   8602:   font-size: 100%;
                   8603: }
                   8604: 
1.897     wenzelju 8605: ol.LC_primary_menu li img {
1.911     bisitz   8606:   vertical-align: bottom;
1.934     droeschl 8607:   height: 1.1em;
1.1077    raeburn  8608:   margin: 0.2em 0 0 0;
1.693     droeschl 8609: }
                   8610: 
1.897     wenzelju 8611: ol.LC_primary_menu a {
1.911     bisitz   8612:   color: RGB(80, 80, 80);
                   8613:   text-decoration: none;
1.693     droeschl 8614: }
1.795     www      8615: 
1.949     droeschl 8616: ol.LC_primary_menu a.LC_new_message {
                   8617:   font-weight:bold;
                   8618:   color: darkred;
                   8619: }
                   8620: 
1.975     raeburn  8621: ol.LC_docs_parameters {
                   8622:   margin-left: 0;
                   8623:   padding: 0;
                   8624:   list-style: none;
                   8625: }
                   8626: 
                   8627: ol.LC_docs_parameters li {
                   8628:   margin: 0;
                   8629:   padding-right: 20px;
                   8630:   display: inline;
                   8631: }
                   8632: 
1.976     raeburn  8633: ol.LC_docs_parameters li:before {
                   8634:   content: "\\002022 \\0020";
                   8635: }
                   8636: 
                   8637: li.LC_docs_parameters_title {
                   8638:   font-weight: bold;
                   8639: }
                   8640: 
                   8641: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8642:   content: "";
                   8643: }
                   8644: 
1.897     wenzelju 8645: ul#LC_secondary_menu {
1.1107    raeburn  8646:   clear: right;
1.911     bisitz   8647:   color: $fontmenu;
                   8648:   background: $tabbg;
                   8649:   list-style: none;
                   8650:   padding: 0;
                   8651:   margin: 0;
                   8652:   width: 100%;
1.995     raeburn  8653:   text-align: left;
1.1107    raeburn  8654:   float: left;
1.808     droeschl 8655: }
                   8656: 
1.897     wenzelju 8657: ul#LC_secondary_menu li {
1.911     bisitz   8658:   font-weight: bold;
                   8659:   line-height: 1.8em;
1.1107    raeburn  8660:   border-right: 1px solid black;
                   8661:   float: left;
                   8662: }
                   8663: 
                   8664: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8665:   background-color: $data_table_light;
                   8666: }
                   8667: 
                   8668: ul#LC_secondary_menu li a {
1.911     bisitz   8669:   padding: 0 0.8em;
1.1107    raeburn  8670: }
                   8671: 
                   8672: ul#LC_secondary_menu li ul {
                   8673:   display: none;
                   8674: }
                   8675: 
                   8676: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8677:   display: block;
                   8678:   position: absolute;
                   8679:   margin: 0;
                   8680:   padding: 0;
                   8681:   list-style:none;
                   8682:   float: none;
                   8683:   background-color: $data_table_light;
                   8684:   z-index: 2;
                   8685:   margin-left: -1px;
                   8686: }
                   8687: 
                   8688: ul#LC_secondary_menu li ul li {
                   8689:   font-size: 90%;
                   8690:   vertical-align: top;
                   8691:   border-left: 1px solid black;
1.911     bisitz   8692:   border-right: 1px solid black;
1.1119    raeburn  8693:   background-color: $data_table_light;
1.1107    raeburn  8694:   list-style:none;
                   8695:   float: none;
                   8696: }
                   8697: 
                   8698: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8699:   background-color: $data_table_dark;
1.807     droeschl 8700: }
                   8701: 
1.847     tempelho 8702: ul.LC_TabContent {
1.911     bisitz   8703:   display:block;
                   8704:   background: $sidebg;
                   8705:   border-bottom: solid 1px $lg_border_color;
                   8706:   list-style:none;
1.1020    raeburn  8707:   margin: -1px -10px 0 -10px;
1.911     bisitz   8708:   padding: 0;
1.693     droeschl 8709: }
                   8710: 
1.795     www      8711: ul.LC_TabContent li,
                   8712: ul.LC_TabContentBigger li {
1.911     bisitz   8713:   float:left;
1.741     harmsja  8714: }
1.795     www      8715: 
1.897     wenzelju 8716: ul#LC_secondary_menu li a {
1.911     bisitz   8717:   color: $fontmenu;
                   8718:   text-decoration: none;
1.693     droeschl 8719: }
1.795     www      8720: 
1.721     harmsja  8721: ul.LC_TabContent {
1.952     onken    8722:   min-height:20px;
1.721     harmsja  8723: }
1.795     www      8724: 
                   8725: ul.LC_TabContent li {
1.911     bisitz   8726:   vertical-align:middle;
1.959     onken    8727:   padding: 0 16px 0 10px;
1.911     bisitz   8728:   background-color:$tabbg;
                   8729:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8730:   border-left: solid 1px $font;
1.721     harmsja  8731: }
1.795     www      8732: 
1.847     tempelho 8733: ul.LC_TabContent .right {
1.911     bisitz   8734:   float:right;
1.847     tempelho 8735: }
                   8736: 
1.911     bisitz   8737: ul.LC_TabContent li a,
                   8738: ul.LC_TabContent li {
                   8739:   color:rgb(47,47,47);
                   8740:   text-decoration:none;
                   8741:   font-size:95%;
                   8742:   font-weight:bold;
1.952     onken    8743:   min-height:20px;
                   8744: }
                   8745: 
1.959     onken    8746: ul.LC_TabContent li a:hover,
                   8747: ul.LC_TabContent li a:focus {
1.952     onken    8748:   color: $button_hover;
1.959     onken    8749:   background:none;
                   8750:   outline:none;
1.952     onken    8751: }
                   8752: 
                   8753: ul.LC_TabContent li:hover {
                   8754:   color: $button_hover;
                   8755:   cursor:pointer;
1.721     harmsja  8756: }
1.795     www      8757: 
1.911     bisitz   8758: ul.LC_TabContent li.active {
1.952     onken    8759:   color: $font;
1.911     bisitz   8760:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8761:   border-bottom:solid 1px #FFFFFF;
                   8762:   cursor: default;
1.744     ehlerst  8763: }
1.795     www      8764: 
1.959     onken    8765: ul.LC_TabContent li.active a {
                   8766:   color:$font;
                   8767:   background:#FFFFFF;
                   8768:   outline: none;
                   8769: }
1.1047    raeburn  8770: 
                   8771: ul.LC_TabContent li.goback {
                   8772:   float: left;
                   8773:   border-left: none;
                   8774: }
                   8775: 
1.870     tempelho 8776: #maincoursedoc {
1.911     bisitz   8777:   clear:both;
1.870     tempelho 8778: }
                   8779: 
                   8780: ul.LC_TabContentBigger {
1.911     bisitz   8781:   display:block;
                   8782:   list-style:none;
                   8783:   padding: 0;
1.870     tempelho 8784: }
                   8785: 
1.795     www      8786: ul.LC_TabContentBigger li {
1.911     bisitz   8787:   vertical-align:bottom;
                   8788:   height: 30px;
                   8789:   font-size:110%;
                   8790:   font-weight:bold;
                   8791:   color: #737373;
1.841     tempelho 8792: }
                   8793: 
1.957     onken    8794: ul.LC_TabContentBigger li.active {
                   8795:   position: relative;
                   8796:   top: 1px;
                   8797: }
                   8798: 
1.870     tempelho 8799: ul.LC_TabContentBigger li a {
1.911     bisitz   8800:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8801:   height: 30px;
                   8802:   line-height: 30px;
                   8803:   text-align: center;
                   8804:   display: block;
                   8805:   text-decoration: none;
1.958     onken    8806:   outline: none;  
1.741     harmsja  8807: }
1.795     www      8808: 
1.870     tempelho 8809: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8810:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8811:   color:$font;
1.744     ehlerst  8812: }
1.795     www      8813: 
1.870     tempelho 8814: ul.LC_TabContentBigger li b {
1.911     bisitz   8815:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8816:   display: block;
                   8817:   float: left;
                   8818:   padding: 0 30px;
1.957     onken    8819:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8820: }
                   8821: 
1.956     onken    8822: ul.LC_TabContentBigger li:hover b {
                   8823:   color:$button_hover;
                   8824: }
                   8825: 
1.870     tempelho 8826: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8827:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8828:   color:$font;
1.957     onken    8829:   border: 0;
1.741     harmsja  8830: }
1.693     droeschl 8831: 
1.870     tempelho 8832: 
1.862     bisitz   8833: ul.LC_CourseBreadcrumbs {
                   8834:   background: $sidebg;
1.1020    raeburn  8835:   height: 2em;
1.862     bisitz   8836:   padding-left: 10px;
1.1020    raeburn  8837:   margin: 0;
1.862     bisitz   8838:   list-style-position: inside;
                   8839: }
                   8840: 
1.911     bisitz   8841: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8842: ol#LC_PathBreadcrumbs {
1.911     bisitz   8843:   padding-left: 10px;
                   8844:   margin: 0;
1.933     droeschl 8845:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8846: }
                   8847: 
1.911     bisitz   8848: ol#LC_MenuBreadcrumbs li,
                   8849: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8850: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8851:   display: inline;
1.933     droeschl 8852:   white-space: normal;  
1.693     droeschl 8853: }
                   8854: 
1.823     bisitz   8855: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8856: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8857:   text-decoration: none;
                   8858:   font-size:90%;
1.693     droeschl 8859: }
1.795     www      8860: 
1.969     droeschl 8861: ol#LC_MenuBreadcrumbs h1 {
                   8862:   display: inline;
                   8863:   font-size: 90%;
                   8864:   line-height: 2.5em;
                   8865:   margin: 0;
                   8866:   padding: 0;
                   8867: }
                   8868: 
1.795     www      8869: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8870:   text-decoration:none;
                   8871:   font-size:100%;
                   8872:   font-weight:bold;
1.693     droeschl 8873: }
1.795     www      8874: 
1.840     bisitz   8875: .LC_Box {
1.911     bisitz   8876:   border: solid 1px $lg_border_color;
                   8877:   padding: 0 10px 10px 10px;
1.746     neumanie 8878: }
1.795     www      8879: 
1.1020    raeburn  8880: .LC_DocsBox {
                   8881:   border: solid 1px $lg_border_color;
                   8882:   padding: 0 0 10px 10px;
                   8883: }
                   8884: 
1.795     www      8885: .LC_AboutMe_Image {
1.911     bisitz   8886:   float:left;
                   8887:   margin-right:10px;
1.747     neumanie 8888: }
1.795     www      8889: 
                   8890: .LC_Clear_AboutMe_Image {
1.911     bisitz   8891:   clear:left;
1.747     neumanie 8892: }
1.795     www      8893: 
1.721     harmsja  8894: dl.LC_ListStyleClean dt {
1.911     bisitz   8895:   padding-right: 5px;
                   8896:   display: table-header-group;
1.693     droeschl 8897: }
                   8898: 
1.721     harmsja  8899: dl.LC_ListStyleClean dd {
1.911     bisitz   8900:   display: table-row;
1.693     droeschl 8901: }
                   8902: 
1.721     harmsja  8903: .LC_ListStyleClean,
                   8904: .LC_ListStyleSimple,
                   8905: .LC_ListStyleNormal,
1.795     www      8906: .LC_ListStyleSpecial {
1.911     bisitz   8907:   /* display:block; */
                   8908:   list-style-position: inside;
                   8909:   list-style-type: none;
                   8910:   overflow: hidden;
                   8911:   padding: 0;
1.693     droeschl 8912: }
                   8913: 
1.721     harmsja  8914: .LC_ListStyleSimple li,
                   8915: .LC_ListStyleSimple dd,
                   8916: .LC_ListStyleNormal li,
                   8917: .LC_ListStyleNormal dd,
                   8918: .LC_ListStyleSpecial li,
1.795     www      8919: .LC_ListStyleSpecial dd {
1.911     bisitz   8920:   margin: 0;
                   8921:   padding: 5px 5px 5px 10px;
                   8922:   clear: both;
1.693     droeschl 8923: }
                   8924: 
1.721     harmsja  8925: .LC_ListStyleClean li,
                   8926: .LC_ListStyleClean dd {
1.911     bisitz   8927:   padding-top: 0;
                   8928:   padding-bottom: 0;
1.693     droeschl 8929: }
                   8930: 
1.721     harmsja  8931: .LC_ListStyleSimple dd,
1.795     www      8932: .LC_ListStyleSimple li {
1.911     bisitz   8933:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8934: }
                   8935: 
1.721     harmsja  8936: .LC_ListStyleSpecial li,
                   8937: .LC_ListStyleSpecial dd {
1.911     bisitz   8938:   list-style-type: none;
                   8939:   background-color: RGB(220, 220, 220);
                   8940:   margin-bottom: 4px;
1.693     droeschl 8941: }
                   8942: 
1.721     harmsja  8943: table.LC_SimpleTable {
1.911     bisitz   8944:   margin:5px;
                   8945:   border:solid 1px $lg_border_color;
1.795     www      8946: }
1.693     droeschl 8947: 
1.721     harmsja  8948: table.LC_SimpleTable tr {
1.911     bisitz   8949:   padding: 0;
                   8950:   border:solid 1px $lg_border_color;
1.693     droeschl 8951: }
1.795     www      8952: 
                   8953: table.LC_SimpleTable thead {
1.911     bisitz   8954:   background:rgb(220,220,220);
1.693     droeschl 8955: }
                   8956: 
1.721     harmsja  8957: div.LC_columnSection {
1.911     bisitz   8958:   display: block;
                   8959:   clear: both;
                   8960:   overflow: hidden;
                   8961:   margin: 0;
1.693     droeschl 8962: }
                   8963: 
1.721     harmsja  8964: div.LC_columnSection>* {
1.911     bisitz   8965:   float: left;
                   8966:   margin: 10px 20px 10px 0;
                   8967:   overflow:hidden;
1.693     droeschl 8968: }
1.721     harmsja  8969: 
1.795     www      8970: table em {
1.911     bisitz   8971:   font-weight: bold;
                   8972:   font-style: normal;
1.748     schulted 8973: }
1.795     www      8974: 
1.779     bisitz   8975: table.LC_tableBrowseRes,
1.795     www      8976: table.LC_tableOfContent {
1.911     bisitz   8977:   border:none;
                   8978:   border-spacing: 1px;
                   8979:   padding: 3px;
                   8980:   background-color: #FFFFFF;
                   8981:   font-size: 90%;
1.753     droeschl 8982: }
1.789     droeschl 8983: 
1.911     bisitz   8984: table.LC_tableOfContent {
                   8985:   border-collapse: collapse;
1.789     droeschl 8986: }
                   8987: 
1.771     droeschl 8988: table.LC_tableBrowseRes a,
1.768     schulted 8989: table.LC_tableOfContent a {
1.911     bisitz   8990:   background-color: transparent;
                   8991:   text-decoration: none;
1.753     droeschl 8992: }
                   8993: 
1.795     www      8994: table.LC_tableOfContent img {
1.911     bisitz   8995:   border: none;
                   8996:   height: 1.3em;
                   8997:   vertical-align: text-bottom;
                   8998:   margin-right: 0.3em;
1.753     droeschl 8999: }
1.757     schulted 9000: 
1.795     www      9001: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9002:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9003: }
                   9004: 
1.795     www      9005: a#LC_content_toolbar_everything {
1.911     bisitz   9006:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9007: }
                   9008: 
1.795     www      9009: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9010:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9011: }
                   9012: 
1.795     www      9013: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9014:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9015: }
                   9016: 
1.795     www      9017: a#LC_content_toolbar_changefolder {
1.911     bisitz   9018:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9019: }
                   9020: 
1.795     www      9021: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9022:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9023: }
                   9024: 
1.1043    raeburn  9025: a#LC_content_toolbar_edittoplevel {
                   9026:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9027: }
                   9028: 
1.1384    raeburn  9029: a#LC_content_toolbar_printout {
                   9030:   background-image:url(/res/adm/pages/printout.gif);
                   9031: }
                   9032: 
1.795     www      9033: ul#LC_toolbar li a:hover {
1.911     bisitz   9034:   background-position: bottom center;
1.757     schulted 9035: }
                   9036: 
1.795     www      9037: ul#LC_toolbar {
1.911     bisitz   9038:   padding: 0;
                   9039:   margin: 2px;
                   9040:   list-style:none;
                   9041:   position:relative;
                   9042:   background-color:white;
1.1082    raeburn  9043:   overflow: auto;
1.757     schulted 9044: }
                   9045: 
1.795     www      9046: ul#LC_toolbar li {
1.911     bisitz   9047:   border:1px solid white;
                   9048:   padding: 0;
                   9049:   margin: 0;
                   9050:   float: left;
                   9051:   display:inline;
                   9052:   vertical-align:middle;
1.1082    raeburn  9053:   white-space: nowrap;
1.911     bisitz   9054: }
1.757     schulted 9055: 
1.783     amueller 9056: 
1.795     www      9057: a.LC_toolbarItem {
1.911     bisitz   9058:   display:block;
                   9059:   padding: 0;
                   9060:   margin: 0;
                   9061:   height: 32px;
                   9062:   width: 32px;
                   9063:   color:white;
                   9064:   border: none;
                   9065:   background-repeat:no-repeat;
                   9066:   background-color:transparent;
1.757     schulted 9067: }
                   9068: 
1.915     droeschl 9069: ul.LC_funclist {
                   9070:     margin: 0;
                   9071:     padding: 0.5em 1em 0.5em 0;
                   9072: }
                   9073: 
1.933     droeschl 9074: ul.LC_funclist > li:first-child {
                   9075:     font-weight:bold; 
                   9076:     margin-left:0.8em;
                   9077: }
                   9078: 
1.915     droeschl 9079: ul.LC_funclist + ul.LC_funclist {
                   9080:     /* 
                   9081:        left border as a seperator if we have more than
                   9082:        one list 
                   9083:     */
                   9084:     border-left: 1px solid $sidebg;
                   9085:     /* 
                   9086:        this hides the left border behind the border of the 
                   9087:        outer box if element is wrapped to the next 'line' 
                   9088:     */
                   9089:     margin-left: -1px;
                   9090: }
                   9091: 
1.843     bisitz   9092: ul.LC_funclist li {
1.915     droeschl 9093:   display: inline;
1.782     bisitz   9094:   white-space: nowrap;
1.915     droeschl 9095:   margin: 0 0 0 25px;
                   9096:   line-height: 150%;
1.782     bisitz   9097: }
                   9098: 
1.974     wenzelju 9099: .LC_hidden {
                   9100:   display: none;
                   9101: }
                   9102: 
1.1030    www      9103: .LCmodal-overlay {
                   9104: 		position:fixed;
                   9105: 		top:0;
                   9106: 		right:0;
                   9107: 		bottom:0;
                   9108: 		left:0;
                   9109: 		height:100%;
                   9110: 		width:100%;
                   9111: 		margin:0;
                   9112: 		padding:0;
                   9113: 		background:#999;
                   9114: 		opacity:.75;
                   9115: 		filter: alpha(opacity=75);
                   9116: 		-moz-opacity: 0.75;
                   9117: 		z-index:101;
                   9118: }
                   9119: 
                   9120: * html .LCmodal-overlay {   
                   9121: 		position: absolute;
                   9122: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9123: }
                   9124: 
                   9125: .LCmodal-window {
                   9126: 		position:fixed;
                   9127: 		top:50%;
                   9128: 		left:50%;
                   9129: 		margin:0;
                   9130: 		padding:0;
                   9131: 		z-index:102;
                   9132: 	}
                   9133: 
                   9134: * html .LCmodal-window {
                   9135: 		position:absolute;
                   9136: }
                   9137: 
                   9138: .LCclose-window {
                   9139: 		position:absolute;
                   9140: 		width:32px;
                   9141: 		height:32px;
                   9142: 		right:8px;
                   9143: 		top:8px;
                   9144: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9145: 		text-indent:-99999px;
                   9146: 		overflow:hidden;
                   9147: 		cursor:pointer;
                   9148: }
                   9149: 
1.1369    raeburn  9150: .LCisDisabled {
                   9151:   cursor: not-allowed;
                   9152:   opacity: 0.5;
                   9153: }
                   9154: 
                   9155: a[aria-disabled="true"] {
                   9156:   color: currentColor;
                   9157:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9158:   pointer-events: none;
                   9159:   text-decoration: none;
                   9160: }
                   9161: 
1.1335    raeburn  9162: pre.LC_wordwrap {
                   9163:   white-space: pre-wrap;
                   9164:   white-space: -moz-pre-wrap;
                   9165:   white-space: -pre-wrap;
                   9166:   white-space: -o-pre-wrap;
                   9167:   word-wrap: break-word;
                   9168: }
                   9169: 
1.1100    raeburn  9170: /*
1.1231    damieng  9171:   styles used for response display
                   9172: */
                   9173: div.LC_radiofoil, div.LC_rankfoil {
                   9174:   margin: .5em 0em .5em 0em;
                   9175: }
                   9176: table.LC_itemgroup {
                   9177:   margin-top: 1em;
                   9178: }
                   9179: 
                   9180: /*
1.1100    raeburn  9181:   styles used by TTH when "Default set of options to pass to tth/m
                   9182:   when converting TeX" in course settings has been set
                   9183: 
                   9184:   option passed: -t
                   9185: 
                   9186: */
                   9187: 
                   9188: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9189: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9190: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9191: td div.norm {line-height:normal;}
                   9192: 
                   9193: /*
                   9194:   option passed -y3
                   9195: */
                   9196: 
                   9197: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9198: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9199: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9200: 
1.1230    damieng  9201: /*
                   9202:   sections with roles, for content only
                   9203: */
                   9204: section[class^="role-"] {
                   9205:   padding-left: 10px;
                   9206:   padding-right: 5px;
                   9207:   margin-top: 8px;
                   9208:   margin-bottom: 8px;
                   9209:   border: 1px solid #2A4;
                   9210:   border-radius: 5px;
                   9211:   box-shadow: 0px 1px 1px #BBB;
                   9212: }
                   9213: section[class^="role-"]>h1 {
                   9214:   position: relative;
                   9215:   margin: 0px;
                   9216:   padding-top: 10px;
                   9217:   padding-left: 40px;
                   9218: }
                   9219: section[class^="role-"]>h1:before {
                   9220:   position: absolute;
                   9221:   left: -5px;
                   9222:   top: 5px;
                   9223: }
                   9224: section.role-activity>h1:before {
                   9225:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9226: }
                   9227: section.role-advice>h1:before {
                   9228:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9229: }
                   9230: section.role-bibliography>h1:before {
                   9231:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9232: }
                   9233: section.role-citation>h1:before {
                   9234:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9235: }
                   9236: section.role-conclusion>h1:before {
                   9237:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9238: }
                   9239: section.role-definition>h1:before {
                   9240:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9241: }
                   9242: section.role-demonstration>h1:before {
                   9243:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9244: }
                   9245: section.role-example>h1:before {
                   9246:   content:url('/adm/daxe/images/section_icons/example.png');
                   9247: }
                   9248: section.role-explanation>h1:before {
                   9249:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9250: }
                   9251: section.role-introduction>h1:before {
                   9252:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9253: }
                   9254: section.role-method>h1:before {
                   9255:   content:url('/adm/daxe/images/section_icons/method.png');
                   9256: }
                   9257: section.role-more_information>h1:before {
                   9258:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9259: }
                   9260: section.role-objectives>h1:before {
                   9261:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9262: }
                   9263: section.role-prerequisites>h1:before {
                   9264:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9265: }
                   9266: section.role-remark>h1:before {
                   9267:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9268: }
                   9269: section.role-reminder>h1:before {
                   9270:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9271: }
                   9272: section.role-summary>h1:before {
                   9273:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9274: }
                   9275: section.role-syntax>h1:before {
                   9276:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9277: }
                   9278: section.role-warning>h1:before {
                   9279:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9280: }
                   9281: 
1.1269    raeburn  9282: #LC_minitab_header {
                   9283:   float:left;
                   9284:   width:100%;
                   9285:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9286:   font-size:93%;
                   9287:   line-height:normal;
                   9288:   margin: 0.5em 0 0.5em 0;
                   9289: }
                   9290: #LC_minitab_header ul {
                   9291:   margin:0;
                   9292:   padding:10px 10px 0;
                   9293:   list-style:none;
                   9294: }
                   9295: #LC_minitab_header li {
                   9296:   float:left;
                   9297:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9298:   margin:0;
                   9299:   padding:0 0 0 9px;
                   9300: }
                   9301: #LC_minitab_header a {
                   9302:   display:block;
                   9303:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9304:   padding:5px 15px 4px 6px;
                   9305: }
                   9306: #LC_minitab_header #LC_current_minitab {
                   9307:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9308: }
                   9309: #LC_minitab_header #LC_current_minitab a {
                   9310:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9311:   padding-bottom:5px;
                   9312: }
                   9313: 
                   9314: 
1.343     albertel 9315: END
                   9316: }
                   9317: 
1.306     albertel 9318: =pod
                   9319: 
                   9320: =item * &headtag()
                   9321: 
                   9322: Returns a uniform footer for LON-CAPA web pages.
                   9323: 
1.307     albertel 9324: Inputs: $title - optional title for the head
                   9325:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9326:         $args - optional arguments
1.319     albertel 9327:             force_register - if is true call registerurl so the remote is 
                   9328:                              informed
1.415     albertel 9329:             redirect       -> array ref of
                   9330:                                    1- seconds before redirect occurs
                   9331:                                    2- url to redirect to
                   9332:                                    3- whether the side effect should occur
1.315     albertel 9333:                            (side effect of setting 
                   9334:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9335:                                redirected to)
                   9336:                                    4- whether the redirect target should be
                   9337:                                       the opener of the current (pop-up)
                   9338:                                       window (side effect of setting
                   9339:                                       $env{'internal.head.to_opener'} to
                   9340:                                       1, if true.
1.1388    raeburn  9341:                                    5- whether encrypt check should be skipped
1.352     albertel 9342:             domain         -> force to color decorate a page for a specific
                   9343:                                domain
                   9344:             function       -> force usage of a specific rolish color scheme
                   9345:             bgcolor        -> override the default page bgcolor
1.460     albertel 9346:             no_auto_mt_title
                   9347:                            -> prevent &mt()ing the title arg
1.464     albertel 9348: 
1.306     albertel 9349: =cut
                   9350: 
                   9351: sub headtag {
1.313     albertel 9352:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9353:     
1.363     albertel 9354:     my $function = $args->{'function'} || &get_users_function();
                   9355:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9356:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9357:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9358:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9359: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9360: 		   #time(),
1.418     albertel 9361: 		   $env{'environment.color.timestamp'},
1.363     albertel 9362: 		   $function,$domain,$bgcolor);
                   9363: 
1.369     www      9364:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9365: 
1.308     albertel 9366:     my $result =
                   9367: 	'<head>'.
1.1160    raeburn  9368: 	&font_settings($args);
1.319     albertel 9369: 
1.1188    raeburn  9370:     my $inhibitprint;
                   9371:     if ($args->{'print_suppress'}) {
                   9372:         $inhibitprint = &print_suppression();
                   9373:     }
1.1064    raeburn  9374: 
1.461     albertel 9375:     if (!$args->{'frameset'}) {
                   9376: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9377:     }
1.962     droeschl 9378:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9379:         $result .= Apache::lonxml::display_title();
1.319     albertel 9380:     }
1.436     albertel 9381:     if (!$args->{'no_nav_bar'} 
                   9382: 	&& !$args->{'only_body'}
                   9383: 	&& !$args->{'frameset'}) {
1.1154    raeburn  9384: 	$result .= &help_menu_js($httphost);
1.1032    www      9385:         $result.=&modal_window();
1.1038    www      9386:         $result.=&togglebox_script();
1.1034    www      9387:         $result.=&wishlist_window();
1.1041    www      9388:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9389:     } else {
                   9390:         if ($args->{'add_modal'}) {
                   9391:            $result.=&modal_window();
                   9392:         }
                   9393:         if ($args->{'add_wishlist'}) {
                   9394:            $result.=&wishlist_window();
                   9395:         }
1.1038    www      9396:         if ($args->{'add_togglebox'}) {
                   9397:            $result.=&togglebox_script();
                   9398:         }
1.1041    www      9399:         if ($args->{'add_progressbar'}) {
                   9400:            $result.=&LCprogressbarUpdate_script();
                   9401:         }
1.436     albertel 9402:     }
1.314     albertel 9403:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9404: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9405:         if (!$skip_enc_check) {
                   9406:             $url = &Apache::lonenc::check_encrypt($url);
                   9407:         }
1.414     albertel 9408: 	if (!$inhibit_continue) {
                   9409: 	    $env{'internal.head.redirect'} = $url;
                   9410: 	}
1.1386    raeburn  9411: 	$result.=<<"ADDMETA";
1.313     albertel 9412: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9413: ADDMETA
                   9414:         if ($to_opener) {
                   9415:             $env{'internal.head.to_opener'} = 1;
                   9416:             my $dest = &js_escape($url);
                   9417:             my $timeout = int($time * 1000);
                   9418:             $result .=<<"ENDJS";
                   9419: <script type="text/javascript">
                   9420: // <![CDATA[
                   9421: function LC_To_Opener() {
                   9422:     var dest = '$dest';
                   9423:     if (dest != '') {
                   9424:         if (window.opener != null && !window.opener.closed) {
                   9425:             window.opener.location.href=dest;
                   9426:             window.close();
                   9427:         } else {
                   9428:             window.location.href=dest;
                   9429:         }
                   9430:     }
                   9431: }
                   9432: \$(document).ready(function () {
                   9433:     setTimeout('LC_To_Opener()',$timeout);
                   9434: });
                   9435: // ]]>
                   9436: </script>
                   9437: ENDJS
                   9438:         } else {
                   9439:             $result.=<<"ADDMETA";
1.344     albertel 9440: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9441: ADDMETA
1.1386    raeburn  9442:         }
1.1210    raeburn  9443:     } else {
                   9444:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9445:             my $requrl = $env{'request.uri'};
                   9446:             if ($requrl eq '') {
                   9447:                 $requrl = $ENV{'REQUEST_URI'};
                   9448:                 $requrl =~ s/\?.+$//;
                   9449:             }
                   9450:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9451:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9452:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9453:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9454:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9455:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9456:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9457:                     my ($offload,$offloadoth);
1.1210    raeburn  9458:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9459:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9460:                             $offload = 1;
1.1353    raeburn  9461:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9462:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9463:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9464:                                     $offloadoth = 1;
                   9465:                                     $dom_in_use = $env{'user.domain'};
                   9466:                                 }
                   9467:                             }
1.1340    raeburn  9468:                         }
                   9469:                     }
                   9470:                     unless ($offload) {
                   9471:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9472:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9473:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9474:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9475:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9476:                                         $offload = 1;
1.1352    raeburn  9477:                                         $offloadoth = 1;
1.1340    raeburn  9478:                                         $dom_in_use = $env{'user.domain'};
                   9479:                                     }
1.1210    raeburn  9480:                                 }
1.1340    raeburn  9481:                             }
                   9482:                         }
                   9483:                     }
                   9484:                     if ($offload) {
1.1358    raeburn  9485:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9486:                         if (($newserver eq '') && ($offloadoth)) {
                   9487:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9488:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9489:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9490:                             }
                   9491:                         }
1.1340    raeburn  9492:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9493:                             my $numsec = 5;
                   9494:                             my $timeout = $numsec * 1000;
                   9495:                             my ($newurl,$locknum,%locks,$msg);
                   9496:                             if ($env{'request.role.adv'}) {
                   9497:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9498:                             }
                   9499:                             my $disable_submit = 0;
                   9500:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9501:                                 $disable_submit = 1;
                   9502:                             }
                   9503:                             if ($locknum) {
                   9504:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9505:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9506:                                        join(", ",sort(values(%locks)))."\n";
                   9507:                                 if (&show_course()) {
                   9508:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9509:                                 } else {
                   9510:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9511:                                 }
1.1340    raeburn  9512:                             } else {
                   9513:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9514:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9515:                                 }
                   9516:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9517:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9518:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9519:                                     $newurl .= '&role='.$env{'request.role'};
                   9520:                                 }
                   9521:                                 if ($env{'request.symb'}) {
                   9522:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9523:                                     if ($shownsymb =~ m{^/enc/}) {
                   9524:                                         my $reqdmajor = 2;
                   9525:                                         my $reqdminor = 11;
                   9526:                                         my $reqdsubminor = 3;
                   9527:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9528:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9529:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9530:                                         if (($major eq '' && $minor eq '') ||
                   9531:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9532:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9533:                                              ($reqdsubminor > $subminor))))) {
                   9534:                                             undef($shownsymb);
                   9535:                                         }
1.1210    raeburn  9536:                                     }
1.1340    raeburn  9537:                                     if ($shownsymb) {
                   9538:                                         &js_escape(\$shownsymb);
                   9539:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9540:                                     }
1.1340    raeburn  9541:                                 } else {
                   9542:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9543:                                     &js_escape(\$shownurl);
                   9544:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9545:                                 }
1.1340    raeburn  9546:                             }
                   9547:                             &js_escape(\$msg);
                   9548:                             $result.=<<OFFLOAD
1.1210    raeburn  9549: <meta http-equiv="pragma" content="no-cache" />
                   9550: <script type="text/javascript">
1.1215    raeburn  9551: // <![CDATA[
1.1210    raeburn  9552: function LC_Offload_Now() {
                   9553:     var dest = "$newurl";
                   9554:     if (dest != '') {
                   9555:         window.location.href="$newurl";
                   9556:     }
                   9557: }
1.1214    raeburn  9558: \$(document).ready(function () {
                   9559:     window.alert('$msg');
                   9560:     if ($disable_submit) {
1.1210    raeburn  9561:         \$(".LC_hwk_submit").prop("disabled", true);
                   9562:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9563:     }
                   9564:     setTimeout('LC_Offload_Now()', $timeout);
                   9565: });
1.1215    raeburn  9566: // ]]>
1.1210    raeburn  9567: </script>
                   9568: OFFLOAD
                   9569:                         }
                   9570:                     }
                   9571:                 }
                   9572:             }
                   9573:         }
1.313     albertel 9574:     }
1.306     albertel 9575:     if (!defined($title)) {
                   9576: 	$title = 'The LearningOnline Network with CAPA';
                   9577:     }
1.460     albertel 9578:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9579:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9580: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9581:     if (!$args->{'frameset'}) {
                   9582:         $result .= ' /';
                   9583:     }
                   9584:     $result .= '>' 
1.1064    raeburn  9585:         .$inhibitprint
1.414     albertel 9586: 	.$head_extra;
1.1242    raeburn  9587:     my $clientmobile;
                   9588:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9589:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9590:     } else {
                   9591:         $clientmobile = $env{'browser.mobile'};
                   9592:     }
                   9593:     if ($clientmobile) {
1.1137    raeburn  9594:         $result .= '
                   9595: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9596: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9597:     }
1.1278    raeburn  9598:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9599:     return $result.'</head>';
1.306     albertel 9600: }
                   9601: 
                   9602: =pod
                   9603: 
1.340     albertel 9604: =item * &font_settings()
                   9605: 
                   9606: Returns neccessary <meta> to set the proper encoding
                   9607: 
1.1160    raeburn  9608: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9609: 
                   9610: =cut
                   9611: 
                   9612: sub font_settings {
1.1160    raeburn  9613:     my ($args) = @_;
1.340     albertel 9614:     my $headerstring='';
1.1160    raeburn  9615:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9616:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9617:         $headerstring.=
                   9618:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9619:         if (!$args->{'frameset'}) {
                   9620: 	    $headerstring.= ' /';
                   9621:         }
                   9622: 	$headerstring .= '>'."\n";
1.340     albertel 9623:     }
                   9624:     return $headerstring;
                   9625: }
                   9626: 
1.341     albertel 9627: =pod
                   9628: 
1.1064    raeburn  9629: =item * &print_suppression()
                   9630: 
                   9631: In course context returns css which causes the body to be blank when media="print",
                   9632: if printout generation is unavailable for the current resource.
                   9633: 
                   9634: This could be because:
                   9635: 
                   9636: (a) printstartdate is in the future
                   9637: 
                   9638: (b) printenddate is in the past
                   9639: 
                   9640: (c) there is an active exam block with "printout"
                   9641: functionality blocked
                   9642: 
                   9643: Users with pav, pfo or evb privileges are exempt.
                   9644: 
                   9645: Inputs: none
                   9646: 
                   9647: =cut
                   9648: 
                   9649: 
                   9650: sub print_suppression {
                   9651:     my $noprint;
                   9652:     if ($env{'request.course.id'}) {
                   9653:         my $scope = $env{'request.course.id'};
                   9654:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9655:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9656:             return;
                   9657:         }
                   9658:         if ($env{'request.course.sec'} ne '') {
                   9659:             $scope .= "/$env{'request.course.sec'}";
                   9660:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9661:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9662:                 return;
1.1064    raeburn  9663:             }
                   9664:         }
                   9665:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9666:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9667:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9668:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9669:         if ($blocked) {
                   9670:             my $checkrole = "cm./$cdom/$cnum";
                   9671:             if ($env{'request.course.sec'} ne '') {
                   9672:                 $checkrole .= "/$env{'request.course.sec'}";
                   9673:             }
                   9674:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9675:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9676:                 $noprint = 1;
                   9677:             }
                   9678:         }
                   9679:         unless ($noprint) {
                   9680:             my $symb = &Apache::lonnet::symbread();
                   9681:             if ($symb ne '') {
                   9682:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9683:                 if (ref($navmap)) {
                   9684:                     my $res = $navmap->getBySymb($symb);
                   9685:                     if (ref($res)) {
                   9686:                         if (!$res->resprintable()) {
                   9687:                             $noprint = 1;
                   9688:                         }
                   9689:                     }
                   9690:                 }
                   9691:             }
                   9692:         }
                   9693:         if ($noprint) {
                   9694:             return <<"ENDSTYLE";
                   9695: <style type="text/css" media="print">
                   9696:     body { display:none }
                   9697: </style>
                   9698: ENDSTYLE
                   9699:         }
                   9700:     }
                   9701:     return;
                   9702: }
                   9703: 
                   9704: =pod
                   9705: 
1.341     albertel 9706: =item * &xml_begin()
                   9707: 
                   9708: Returns the needed doctype and <html>
                   9709: 
                   9710: Inputs: none
                   9711: 
                   9712: =cut
                   9713: 
                   9714: sub xml_begin {
1.1168    raeburn  9715:     my ($is_frameset) = @_;
1.341     albertel 9716:     my $output='';
                   9717: 
                   9718:     if ($env{'browser.mathml'}) {
                   9719: 	$output='<?xml version="1.0"?>'
                   9720:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9721: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9722:             
                   9723: #	    .'<!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">] >'
                   9724: 	    .'<!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">'
                   9725:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9726: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9727:     } elsif ($is_frameset) {
                   9728:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9729:                 '<html>'."\n";
1.341     albertel 9730:     } else {
1.1168    raeburn  9731: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9732:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9733:     }
                   9734:     return $output;
                   9735: }
1.340     albertel 9736: 
                   9737: =pod
                   9738: 
1.306     albertel 9739: =item * &start_page()
                   9740: 
                   9741: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9742: 
1.648     raeburn  9743: Inputs:
                   9744: 
                   9745: =over 4
                   9746: 
                   9747: $title - optional title for the page
                   9748: 
                   9749: $head_extra - optional extra HTML to incude inside the <head>
                   9750: 
                   9751: $args - additional optional args supported are:
                   9752: 
                   9753: =over 8
                   9754: 
                   9755:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9756:                                     arg on
1.814     bisitz   9757:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9758:              add_entries    -> additional attributes to add to the  <body>
                   9759:              domain         -> force to color decorate a page for a 
1.317     albertel 9760:                                     specific domain
1.648     raeburn  9761:              function       -> force usage of a specific rolish color
1.317     albertel 9762:                                     scheme
1.648     raeburn  9763:              redirect       -> see &headtag()
                   9764:              bgcolor        -> override the default page bg color
                   9765:              js_ready       -> return a string ready for being used in 
1.317     albertel 9766:                                     a javascript writeln
1.648     raeburn  9767:              html_encode    -> return a string ready for being used in 
1.320     albertel 9768:                                     a html attribute
1.648     raeburn  9769:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9770:                                     $forcereg arg
1.648     raeburn  9771:              frameset       -> if true will start with a <frameset>
1.330     albertel 9772:                                     rather than <body>
1.648     raeburn  9773:              skip_phases    -> hash ref of 
1.338     albertel 9774:                                     head -> skip the <html><head> generation
                   9775:                                     body -> skip all <body> generation
1.648     raeburn  9776:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9777:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9778:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9779:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9780:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9781:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9782:                                specific group
                   9783:              use_absolute   -> for request for external resource or syllabus, this
                   9784:                                will contain https://<hostname> if server uses
                   9785:                                https (as per hosts.tab), but request is for http
                   9786:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9787:              links_disabled -> Links in primary and secondary menus are disabled
                   9788:                                (Can enable them once page has loaded - see lonroles.pm
                   9789:                                for an example).
1.1380    raeburn  9790:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9791: 
1.648     raeburn  9792: =back
1.460     albertel 9793: 
1.648     raeburn  9794: =back
1.562     albertel 9795: 
1.306     albertel 9796: =cut
                   9797: 
                   9798: sub start_page {
1.309     albertel 9799:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9800:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9801: 
1.315     albertel 9802:     $env{'internal.start_page'}++;
1.1359    raeburn  9803:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9804: 
1.338     albertel 9805:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9806:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9807:     }
1.1316    raeburn  9808: 
                   9809:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9810:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9811:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9812:                 $args->{'no_primary_menu'} = 1;
                   9813:             }
                   9814:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9815:                 $args->{'no_inline_menu'} = 1;
                   9816:             }
                   9817:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9818:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9819:             }
                   9820:         } else {
                   9821:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9822:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9823:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9824:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9825:                     $args->{'no_primary_menu'} = 1;
                   9826:                 }
                   9827:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9828:                     $args->{'no_inline_menu'} = 1;
                   9829:                 }
                   9830:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9831:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9832:                 }
                   9833:             }
                   9834:         }
1.1316    raeburn  9835:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9836:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9837:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9838:     } elsif ($env{'request.course.id'}) {
                   9839:         my $expiretime=600;
                   9840:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9841:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9842:         }
                   9843:         my ($deeplinkmenu,$menuref);
                   9844:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9845:         if ($menucoll) {
                   9846:             if (ref($menuref) eq 'HASH') {
                   9847:                 %menu = %{$menuref};
                   9848:             }
                   9849:             if ($menu{'top'} eq 'n') {
                   9850:                 $args->{'no_primary_menu'} = 1;
                   9851:             }
                   9852:             if ($menu{'inline'} eq 'n') {
                   9853:                 unless (&Apache::lonnet::allowed('opa')) {
                   9854:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9855:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9856:                     my $crstype = &course_type();
                   9857:                     my $now = time;
                   9858:                     my $ccrole;
                   9859:                     if ($crstype eq 'Community') {
                   9860:                         $ccrole = 'co';
                   9861:                     } else {
                   9862:                         $ccrole = 'cc';
                   9863:                     }
                   9864:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9865:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9866:                         if ((($start) && ($start<0)) ||
                   9867:                             (($end) && ($end<$now))  ||
                   9868:                             (($start) && ($now<$start))) {
                   9869:                             $args->{'no_inline_menu'} = 1;
                   9870:                         }
                   9871:                     } else {
                   9872:                         $args->{'no_inline_menu'} = 1;
                   9873:                     }
                   9874:                 }
                   9875:             }
                   9876:         }
1.1316    raeburn  9877:     }
1.1359    raeburn  9878: 
1.1385    raeburn  9879:     my $showncrumbs;
1.338     albertel 9880:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9881: 	if ($args->{'frameset'}) {
                   9882: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9883: 						$args->{'add_entries'});
                   9884: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9885:         } else {
                   9886:             $result .=
                   9887:                 &bodytag($title, 
                   9888:                          $args->{'function'},       $args->{'add_entries'},
                   9889:                          $args->{'only_body'},      $args->{'domain'},
                   9890:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9891:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  9892:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   9893:                          \%menu,\$showncrumbs);
1.831     bisitz   9894:         }
1.330     albertel 9895:     }
1.338     albertel 9896: 
1.315     albertel 9897:     if ($args->{'js_ready'}) {
1.713     kaisler  9898: 		$result = &js_ready($result);
1.315     albertel 9899:     }
1.320     albertel 9900:     if ($args->{'html_encode'}) {
1.713     kaisler  9901: 		$result = &html_encode($result);
                   9902:     }
                   9903: 
1.813     bisitz   9904:     # Preparation for new and consistent functionlist at top of screen
                   9905:     # if ($args->{'functionlist'}) {
                   9906:     #            $result .= &build_functionlist();
                   9907:     #}
                   9908: 
1.964     droeschl 9909:     # Don't add anything more if only_body wanted or in const space
                   9910:     return $result if    $args->{'only_body'} 
                   9911:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9912: 
                   9913:     #Breadcrumbs
1.758     kaisler  9914:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  9915:         unless ($showncrumbs) {
1.758     kaisler  9916: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9917: 		#if any br links exists, add them to the breadcrumbs
                   9918: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9919: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9920: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9921: 			}
                   9922: 		}
1.1096    raeburn  9923:                 # if @advtools array contains items add then to the breadcrumbs
                   9924:                 if (@advtools > 0) {
                   9925:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9926:                 }
1.1272    raeburn  9927:                 my $menulink;
                   9928:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9929:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9930:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9931:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9932:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9933:                      (!$env{'request.role.adv'}))) {
                   9934:                     $menulink = 0;
                   9935:                 } else {
                   9936:                     undef($menulink);
                   9937:                 }
1.1385    raeburn  9938:                 my $linkprotout;
                   9939:                 if ($env{'request.deeplink.login'}) {
                   9940:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9941:                     if ($linkprotout) {
                   9942:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9943:                     }
                   9944:                 }
1.758     kaisler  9945: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9946: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9947: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9948:                 } else {
1.1272    raeburn  9949: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9950: 		}
1.1385    raeburn  9951:         }
1.320     albertel 9952:     }
1.315     albertel 9953:     return $result;
1.306     albertel 9954: }
                   9955: 
                   9956: sub end_page {
1.315     albertel 9957:     my ($args) = @_;
                   9958:     $env{'internal.end_page'}++;
1.330     albertel 9959:     my $result;
1.335     albertel 9960:     if ($args->{'discussion'}) {
                   9961: 	my ($target,$parser);
                   9962: 	if (ref($args->{'discussion'})) {
                   9963: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9964: 				$args->{'discussion'}{'parser'});
                   9965: 	}
                   9966: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9967:     }
1.330     albertel 9968:     if ($args->{'frameset'}) {
                   9969: 	$result .= '</frameset>';
                   9970:     } else {
1.635     raeburn  9971: 	$result .= &endbodytag($args);
1.330     albertel 9972:     }
1.1080    raeburn  9973:     unless ($args->{'notbody'}) {
                   9974:         $result .= "\n</html>";
                   9975:     }
1.330     albertel 9976: 
1.315     albertel 9977:     if ($args->{'js_ready'}) {
1.317     albertel 9978: 	$result = &js_ready($result);
1.315     albertel 9979:     }
1.335     albertel 9980: 
1.320     albertel 9981:     if ($args->{'html_encode'}) {
                   9982: 	$result = &html_encode($result);
                   9983:     }
1.335     albertel 9984: 
1.315     albertel 9985:     return $result;
                   9986: }
                   9987: 
1.1359    raeburn  9988: sub menucoll_in_effect {
                   9989:     my ($menucoll,$deeplinkmenu,%menu);
                   9990:     if ($env{'request.course.id'}) {
                   9991:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9992:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9993:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9994:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9995:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9996:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9997:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9998:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9999:                     if (ref($navmap)) {
                   10000:                         $deeplink = $navmap->get_mapparam(undef,
                   10001:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10002:                                                           '0.deeplink');
1.1370    raeburn  10003:                     } else {
                   10004:                         $check_login_symb = 1;
1.1362    raeburn  10005:                     }
                   10006:                 } else {
1.1370    raeburn  10007:                     my $symb = &Apache::lonnet::symbread();
                   10008:                     if ($symb) {
                   10009:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10010:                     } else {
                   10011:                         $check_login_symb = 1;
                   10012:                     }
1.1362    raeburn  10013:                 }
                   10014:             } else {
1.1370    raeburn  10015:                 $check_login_symb = 1;
                   10016:             }
                   10017:             if ($check_login_symb) {
1.1362    raeburn  10018:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10019:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10020:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10021:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10022:                     if (ref($navmap)) {
                   10023:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10024:                     }
                   10025:                 } else {
                   10026:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10027:                 }
                   10028:             }
1.1359    raeburn  10029:             if ($deeplink ne '') {
1.1378    raeburn  10030:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10031:                 if ($display =~ /^\d+$/) {
                   10032:                     $deeplinkmenu = 1;
                   10033:                     $menucoll = $display;
                   10034:                 }
                   10035:             }
                   10036:         }
                   10037:         if ($menucoll) {
                   10038:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10039:         }
                   10040:     }
                   10041:     return ($menucoll,$deeplinkmenu,\%menu);
                   10042: }
                   10043: 
1.1362    raeburn  10044: sub deeplink_login_symb {
                   10045:     my ($cnum,$cdom) = @_;
                   10046:     my $login_symb;
                   10047:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10048:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10049:     }
                   10050:     return $login_symb;
                   10051: }
                   10052: 
                   10053: sub symb_from_tinyurl {
                   10054:     my ($url,$cnum,$cdom) = @_;
                   10055:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10056:         my $key = $1;
                   10057:         my ($tinyurl,$login);
                   10058:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10059:         if (defined($cached)) {
                   10060:             $tinyurl = $result;
                   10061:         } else {
                   10062:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10063:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10064:             if ($currtiny{$key} ne '') {
                   10065:                 $tinyurl = $currtiny{$key};
                   10066:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10067:             }
1.1364    raeburn  10068:         }
                   10069:         if ($tinyurl ne '') {
                   10070:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10071:             if (wantarray) {
                   10072:                 return ($cnumreq,$symb);
                   10073:             } elsif ($cnumreq eq $cnum) {
                   10074:                 return $symb;
1.1362    raeburn  10075:             }
                   10076:         }
                   10077:     }
1.1364    raeburn  10078:     if (wantarray) {
                   10079:         return ();
                   10080:     } else {
                   10081:         return;
                   10082:     }
1.1362    raeburn  10083: }
                   10084: 
1.1405    raeburn  10085: sub usable_exttools {
                   10086:     my %tooltypes;
                   10087:     if ($env{'request.course.id'}) {
                   10088:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10089:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10090:                %tooltypes = (
                   10091:                              crs => 1,
                   10092:                              dom => 1,
                   10093:                             );
                   10094:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10095:                $tooltypes{'crs'} = 1;
                   10096:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10097:                $tooltypes{'dom'} = 1;
                   10098:            }
                   10099:         } else {
                   10100:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10101:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10102:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10103:             if ($crstype eq '') {
                   10104:                 $crstype = 'course';
                   10105:             }
                   10106:             if ($crstype eq 'course') {
                   10107:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10108:                     $crstype = 'official';
                   10109:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10110:                     $crstype = 'textbook';
                   10111:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10112:                     $crstype = 'lti';
                   10113:                 } else {
                   10114:                     $crstype = 'unofficial';
                   10115:                 }
                   10116:             }
                   10117:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10118:             if ($domdefaults{$crstype.'domexttool'}) {
                   10119:                 $tooltypes{'dom'} = 1;
                   10120:             }
                   10121:             if ($domdefaults{$crstype.'exttool'}) {
                   10122:                 $tooltypes{'crs'} = 1;
                   10123:             }
                   10124:         }
                   10125:     }
                   10126:     return %tooltypes;
                   10127: }
                   10128: 
1.1034    www      10129: sub wishlist_window {
                   10130:     return(<<'ENDWISHLIST');
1.1046    raeburn  10131: <script type="text/javascript">
1.1034    www      10132: // <![CDATA[
                   10133: // <!-- BEGIN LON-CAPA Internal
                   10134: function set_wishlistlink(title, path) {
                   10135:     if (!title) {
                   10136:         title = document.title;
                   10137:         title = title.replace(/^LON-CAPA /,'');
                   10138:     }
1.1175    raeburn  10139:     title = encodeURIComponent(title);
1.1203    raeburn  10140:     title = title.replace("'","\\\'");
1.1034    www      10141:     if (!path) {
                   10142:         path = location.pathname;
                   10143:     }
1.1175    raeburn  10144:     path = encodeURIComponent(path);
1.1203    raeburn  10145:     path = path.replace("'","\\\'");
1.1034    www      10146:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10147:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10148: }
                   10149: // END LON-CAPA Internal -->
                   10150: // ]]>
                   10151: </script>
                   10152: ENDWISHLIST
                   10153: }
                   10154: 
1.1030    www      10155: sub modal_window {
                   10156:     return(<<'ENDMODAL');
1.1046    raeburn  10157: <script type="text/javascript">
1.1030    www      10158: // <![CDATA[
                   10159: // <!-- BEGIN LON-CAPA Internal
                   10160: var modalWindow = {
                   10161: 	parent:"body",
                   10162: 	windowId:null,
                   10163: 	content:null,
                   10164: 	width:null,
                   10165: 	height:null,
                   10166: 	close:function()
                   10167: 	{
                   10168: 	        $(".LCmodal-window").remove();
                   10169: 	        $(".LCmodal-overlay").remove();
                   10170: 	},
                   10171: 	open:function()
                   10172: 	{
                   10173: 		var modal = "";
                   10174: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10175: 		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;\">";
                   10176: 		modal += this.content;
                   10177: 		modal += "</div>";	
                   10178: 
                   10179: 		$(this.parent).append(modal);
                   10180: 
                   10181: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10182: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10183: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10184: 	}
                   10185: };
1.1140    raeburn  10186: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10187: 	{
1.1266    raeburn  10188:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10189: 		modalWindow.windowId = "myModal";
                   10190: 		modalWindow.width = width;
                   10191: 		modalWindow.height = height;
1.1196    raeburn  10192: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10193: 		modalWindow.open();
1.1208    raeburn  10194: 	};
1.1030    www      10195: // END LON-CAPA Internal -->
                   10196: // ]]>
                   10197: </script>
                   10198: ENDMODAL
                   10199: }
                   10200: 
                   10201: sub modal_link {
1.1140    raeburn  10202:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10203:     unless ($width) { $width=480; }
                   10204:     unless ($height) { $height=400; }
1.1031    www      10205:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10206:     unless ($transparency) { $transparency='true'; }
                   10207: 
1.1074    raeburn  10208:     my $target_attr;
                   10209:     if (defined($target)) {
                   10210:         $target_attr = 'target="'.$target.'"';
                   10211:     }
                   10212:     return <<"ENDLINK";
1.1336    raeburn  10213: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10214: ENDLINK
1.1030    www      10215: }
                   10216: 
1.1032    www      10217: sub modal_adhoc_script {
1.1365    raeburn  10218:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10219:     my $mathjax;
                   10220:     if ($possmathjax) {
                   10221:         $mathjax = <<'ENDJAX';
                   10222:                if (typeof MathJax == 'object') {
                   10223:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10224:                }
                   10225: ENDJAX
                   10226:     }
1.1032    www      10227:     return (<<ENDADHOC);
1.1046    raeburn  10228: <script type="text/javascript">
1.1032    www      10229: // <![CDATA[
                   10230:         var $funcname = function()
                   10231:         {
                   10232:                 modalWindow.windowId = "myModal";
                   10233:                 modalWindow.width = $width;
                   10234:                 modalWindow.height = $height;
                   10235:                 modalWindow.content = '$content';
                   10236:                 modalWindow.open();
1.1365    raeburn  10237:                 $mathjax
1.1032    www      10238:         };  
                   10239: // ]]>
                   10240: </script>
                   10241: ENDADHOC
                   10242: }
                   10243: 
1.1041    www      10244: sub modal_adhoc_inner {
1.1365    raeburn  10245:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10246:     my $innerwidth=$width-20;
                   10247:     $content=&js_ready(
1.1140    raeburn  10248:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10249:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10250:                  $content.
1.1041    www      10251:                  &end_scrollbox().
1.1140    raeburn  10252:                  &end_page()
1.1041    www      10253:              );
1.1365    raeburn  10254:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10255: }
                   10256: 
                   10257: sub modal_adhoc_window {
1.1365    raeburn  10258:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10259:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10260:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10261: }
                   10262: 
                   10263: sub modal_adhoc_launch {
                   10264:     my ($funcname,$width,$height,$content)=@_;
                   10265:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10266: <script type="text/javascript">
                   10267: // <![CDATA[
                   10268: $funcname();
                   10269: // ]]>
                   10270: </script>
                   10271: ENDLAUNCH
                   10272: }
                   10273: 
                   10274: sub modal_adhoc_close {
                   10275:     return (<<ENDCLOSE);
                   10276: <script type="text/javascript">
                   10277: // <![CDATA[
                   10278: modalWindow.close();
                   10279: // ]]>
                   10280: </script>
                   10281: ENDCLOSE
                   10282: }
                   10283: 
1.1038    www      10284: sub togglebox_script {
                   10285:    return(<<ENDTOGGLE);
                   10286: <script type="text/javascript"> 
                   10287: // <![CDATA[
                   10288: function LCtoggleDisplay(id,hidetext,showtext) {
                   10289:    link = document.getElementById(id + "link").childNodes[0];
                   10290:    with (document.getElementById(id).style) {
                   10291:       if (display == "none" ) {
                   10292:           display = "inline";
                   10293:           link.nodeValue = hidetext;
                   10294:         } else {
                   10295:           display = "none";
                   10296:           link.nodeValue = showtext;
                   10297:        }
                   10298:    }
                   10299: }
                   10300: // ]]>
                   10301: </script>
                   10302: ENDTOGGLE
                   10303: }
                   10304: 
1.1039    www      10305: sub start_togglebox {
                   10306:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10307:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10308:     unless ($showtext) { $showtext=&mt('show'); }
                   10309:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10310:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10311:     return &start_data_table().
                   10312:            &start_data_table_header_row().
                   10313:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10314:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10315:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10316:            &end_data_table_header_row().
                   10317:            '<tr id="'.$id.'" style="display:none""><td>';
                   10318: }
                   10319: 
                   10320: sub end_togglebox {
                   10321:     return '</td></tr>'.&end_data_table();
                   10322: }
                   10323: 
1.1041    www      10324: sub LCprogressbar_script {
1.1302    raeburn  10325:    my ($id,$number_to_do)=@_;
                   10326:    if ($number_to_do) {
                   10327:        return(<<ENDPROGRESS);
1.1041    www      10328: <script type="text/javascript">
                   10329: // <![CDATA[
1.1045    www      10330: \$('#progressbar$id').progressbar({
1.1041    www      10331:   value: 0,
                   10332:   change: function(event, ui) {
                   10333:     var newVal = \$(this).progressbar('option', 'value');
                   10334:     \$('.pblabel', this).text(LCprogressTxt);
                   10335:   }
                   10336: });
                   10337: // ]]>
                   10338: </script>
                   10339: ENDPROGRESS
1.1302    raeburn  10340:    } else {
                   10341:        return(<<ENDPROGRESS);
                   10342: <script type="text/javascript">
                   10343: // <![CDATA[
                   10344: \$('#progressbar$id').progressbar({
                   10345:   value: false,
                   10346:   create: function(event, ui) {
                   10347:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10348:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10349:   }
                   10350: });
                   10351: // ]]>
                   10352: </script>
                   10353: ENDPROGRESS
                   10354:    }
1.1041    www      10355: }
                   10356: 
                   10357: sub LCprogressbarUpdate_script {
                   10358:    return(<<ENDPROGRESSUPDATE);
                   10359: <style type="text/css">
                   10360: .ui-progressbar { position:relative; }
1.1302    raeburn  10361: .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      10362: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10363: </style>
                   10364: <script type="text/javascript">
                   10365: // <![CDATA[
1.1045    www      10366: var LCprogressTxt='---';
                   10367: 
1.1302    raeburn  10368: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10369:    LCprogressTxt=progresstext;
1.1302    raeburn  10370:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10371:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10372:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10373:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10374:    } else {
                   10375:        \$('#progressbar'+id).progressbar('value',percent);
                   10376:    }
1.1041    www      10377: }
                   10378: // ]]>
                   10379: </script>
                   10380: ENDPROGRESSUPDATE
                   10381: }
                   10382: 
1.1042    www      10383: my $LClastpercent;
1.1045    www      10384: my $LCidcnt;
                   10385: my $LCcurrentid;
1.1042    www      10386: 
1.1041    www      10387: sub LCprogressbar {
1.1302    raeburn  10388:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10389:     $LClastpercent=0;
1.1045    www      10390:     $LCidcnt++;
                   10391:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10392:     my ($starting,$content);
                   10393:     if ($number_to_do) {
                   10394:         $starting=&mt('Starting');
                   10395:         $content=(<<ENDPROGBAR);
                   10396: $preamble
1.1045    www      10397:   <div id="progressbar$LCcurrentid">
1.1041    www      10398:     <span class="pblabel">$starting</span>
                   10399:   </div>
                   10400: ENDPROGBAR
1.1302    raeburn  10401:     } else {
                   10402:         $starting=&mt('Loading...');
                   10403:         $LClastpercent='false';
                   10404:         $content=(<<ENDPROGBAR);
                   10405: $preamble
                   10406:   <div id="progressbar$LCcurrentid">
                   10407:       <div class="progress-label">$starting</div>
                   10408:   </div>
                   10409: ENDPROGBAR
                   10410:     }
                   10411:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10412: }
                   10413: 
                   10414: sub LCprogressbarUpdate {
1.1302    raeburn  10415:     my ($r,$val,$text,$number_to_do)=@_;
                   10416:     if ($number_to_do) {
                   10417:         unless ($val) { 
                   10418:             if ($LClastpercent) {
                   10419:                 $val=$LClastpercent;
                   10420:             } else {
                   10421:                 $val=0;
                   10422:             }
                   10423:         }
                   10424:         if ($val<0) { $val=0; }
                   10425:         if ($val>100) { $val=0; }
                   10426:         $LClastpercent=$val;
                   10427:         unless ($text) { $text=$val.'%'; }
                   10428:     } else {
                   10429:         $val = 'false';
1.1042    www      10430:     }
1.1041    www      10431:     $text=&js_ready($text);
1.1044    www      10432:     &r_print($r,<<ENDUPDATE);
1.1041    www      10433: <script type="text/javascript">
                   10434: // <![CDATA[
1.1302    raeburn  10435: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10436: // ]]>
                   10437: </script>
                   10438: ENDUPDATE
1.1035    www      10439: }
                   10440: 
1.1042    www      10441: sub LCprogressbarClose {
                   10442:     my ($r)=@_;
                   10443:     $LClastpercent=0;
1.1044    www      10444:     &r_print($r,<<ENDCLOSE);
1.1042    www      10445: <script type="text/javascript">
                   10446: // <![CDATA[
1.1045    www      10447: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10448: // ]]>
                   10449: </script>
                   10450: ENDCLOSE
1.1044    www      10451: }
                   10452: 
                   10453: sub r_print {
                   10454:     my ($r,$to_print)=@_;
                   10455:     if ($r) {
                   10456:       $r->print($to_print);
                   10457:       $r->rflush();
                   10458:     } else {
                   10459:       print($to_print);
                   10460:     }
1.1042    www      10461: }
                   10462: 
1.320     albertel 10463: sub html_encode {
                   10464:     my ($result) = @_;
                   10465: 
1.322     albertel 10466:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10467:     
                   10468:     return $result;
                   10469: }
1.1044    www      10470: 
1.317     albertel 10471: sub js_ready {
                   10472:     my ($result) = @_;
                   10473: 
1.323     albertel 10474:     $result =~ s/[\n\r]/ /xmsg;
                   10475:     $result =~ s/\\/\\\\/xmsg;
                   10476:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10477:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10478:     
                   10479:     return $result;
                   10480: }
                   10481: 
1.315     albertel 10482: sub validate_page {
                   10483:     if (  exists($env{'internal.start_page'})
1.316     albertel 10484: 	  &&     $env{'internal.start_page'} > 1) {
                   10485: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10486: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10487: 				 $ENV{'request.filename'});
1.315     albertel 10488:     }
                   10489:     if (  exists($env{'internal.end_page'})
1.316     albertel 10490: 	  &&     $env{'internal.end_page'} > 1) {
                   10491: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10492: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10493: 				 $env{'request.filename'});
1.315     albertel 10494:     }
                   10495:     if (     exists($env{'internal.start_page'})
                   10496: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10497: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10498: 				 $env{'request.filename'});
1.315     albertel 10499:     }
                   10500:     if (   ! exists($env{'internal.start_page'})
                   10501: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10502: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10503: 				 $env{'request.filename'});
1.315     albertel 10504:     }
1.306     albertel 10505: }
1.315     albertel 10506: 
1.996     www      10507: 
                   10508: sub start_scrollbox {
1.1140    raeburn  10509:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10510:     unless ($outerwidth) { $outerwidth='520px'; }
                   10511:     unless ($width) { $width='500px'; }
                   10512:     unless ($height) { $height='200px'; }
1.1075    raeburn  10513:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10514:     if ($id ne '') {
1.1140    raeburn  10515:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10516:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10517:     }
1.1075    raeburn  10518:     if ($bgcolor ne '') {
                   10519:         $tdcol = "background-color: $bgcolor;";
                   10520:     }
1.1137    raeburn  10521:     my $nicescroll_js;
                   10522:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10523:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10524:     }
                   10525:     return <<"END";
                   10526: $nicescroll_js
                   10527: 
                   10528: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10529: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10530: END
                   10531: }
                   10532: 
                   10533: sub end_scrollbox {
                   10534:     return '</div></td></tr></table>';
                   10535: }
                   10536: 
                   10537: sub nicescroll_javascript {
                   10538:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10539:     my %options;
                   10540:     if (ref($cursor) eq 'HASH') {
                   10541:         %options = %{$cursor};
                   10542:     }
                   10543:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10544:         $options{'railalign'} = 'left';
                   10545:     }
                   10546:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10547:         my $function  = &get_users_function();
                   10548:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10549:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10550:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10551:         }
1.1140    raeburn  10552:     }
                   10553:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10554:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10555:             $options{'cursoropacity'}='1.0';
                   10556:         }
1.1140    raeburn  10557:     } else {
                   10558:         $options{'cursoropacity'}='1.0';
                   10559:     }
                   10560:     if ($options{'cursorfixedheight'} eq 'none') {
                   10561:         delete($options{'cursorfixedheight'});
                   10562:     } else {
                   10563:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10564:     }
                   10565:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10566:         delete($options{'railoffset'});
                   10567:     }
                   10568:     my @niceoptions;
                   10569:     while (my($key,$value) = each(%options)) {
                   10570:         if ($value =~ /^\{.+\}$/) {
                   10571:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10572:         } else {
1.1140    raeburn  10573:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10574:         }
1.1140    raeburn  10575:     }
                   10576:     my $nicescroll_js = '
1.1137    raeburn  10577: $(document).ready(
1.1140    raeburn  10578:       function() {
                   10579:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10580:       }
1.1137    raeburn  10581: );
                   10582: ';
1.1140    raeburn  10583:     if ($framecheck) {
                   10584:         $nicescroll_js .= '
                   10585: function expand_div(caller) {
                   10586:     if (top === self) {
                   10587:         document.getElementById("'.$id.'").style.width = "auto";
                   10588:         document.getElementById("'.$id.'").style.height = "auto";
                   10589:     } else {
                   10590:         try {
                   10591:             if (parent.frames) {
                   10592:                 if (parent.frames.length > 1) {
                   10593:                     var framesrc = parent.frames[1].location.href;
                   10594:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10595:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10596:                         document.getElementById("'.$id.'").style.width = "auto";
                   10597:                         document.getElementById("'.$id.'").style.height = "auto";
                   10598:                     }
                   10599:                 }
                   10600:             }
                   10601:         } catch (e) {
                   10602:             return;
                   10603:         }
1.1137    raeburn  10604:     }
1.1140    raeburn  10605:     return;
1.996     www      10606: }
1.1140    raeburn  10607: ';
                   10608:     }
                   10609:     if ($needjsready) {
                   10610:         $nicescroll_js = '
                   10611: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10612:     } else {
                   10613:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10614:     }
                   10615:     return $nicescroll_js;
1.996     www      10616: }
                   10617: 
1.318     albertel 10618: sub simple_error_page {
1.1150    bisitz   10619:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10620:     my %displayargs;
1.1151    raeburn  10621:     if (ref($args) eq 'HASH') {
                   10622:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10623:         if ($args->{'only_body'}) {
                   10624:             $displayargs{'only_body'} = 1;
                   10625:         }
                   10626:         if ($args->{'no_nav_bar'}) {
                   10627:             $displayargs{'no_nav_bar'} = 1;
                   10628:         }
1.1151    raeburn  10629:     } else {
                   10630:         $msg = &mt($msg);
                   10631:     }
1.1150    bisitz   10632: 
1.318     albertel 10633:     my $page =
1.1304    raeburn  10634: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10635: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10636: 	&Apache::loncommon::end_page();
                   10637:     if (ref($r)) {
                   10638: 	$r->print($page);
1.327     albertel 10639: 	return;
1.318     albertel 10640:     }
                   10641:     return $page;
                   10642: }
1.347     albertel 10643: 
                   10644: {
1.610     albertel 10645:     my @row_count;
1.961     onken    10646: 
                   10647:     sub start_data_table_count {
                   10648:         unshift(@row_count, 0);
                   10649:         return;
                   10650:     }
                   10651: 
                   10652:     sub end_data_table_count {
                   10653:         shift(@row_count);
                   10654:         return;
                   10655:     }
                   10656: 
1.347     albertel 10657:     sub start_data_table {
1.1018    raeburn  10658: 	my ($add_class,$id) = @_;
1.422     albertel 10659: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10660:         my $table_id;
                   10661:         if (defined($id)) {
                   10662:             $table_id = ' id="'.$id.'"';
                   10663:         }
1.961     onken    10664: 	&start_data_table_count();
1.1018    raeburn  10665: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10666:     }
                   10667: 
                   10668:     sub end_data_table {
1.961     onken    10669: 	&end_data_table_count();
1.389     albertel 10670: 	return '</table>'."\n";;
1.347     albertel 10671:     }
                   10672: 
                   10673:     sub start_data_table_row {
1.974     wenzelju 10674: 	my ($add_class, $id) = @_;
1.610     albertel 10675: 	$row_count[0]++;
                   10676: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10677: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10678:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10679:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10680:     }
1.471     banghart 10681:     
                   10682:     sub continue_data_table_row {
1.974     wenzelju 10683: 	my ($add_class, $id) = @_;
1.610     albertel 10684: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10685: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10686:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10687:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10688:     }
1.347     albertel 10689: 
                   10690:     sub end_data_table_row {
1.389     albertel 10691: 	return '</tr>'."\n";;
1.347     albertel 10692:     }
1.367     www      10693: 
1.421     albertel 10694:     sub start_data_table_empty_row {
1.707     bisitz   10695: #	$row_count[0]++;
1.421     albertel 10696: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10697:     }
                   10698: 
                   10699:     sub end_data_table_empty_row {
                   10700: 	return '</tr>'."\n";;
                   10701:     }
                   10702: 
1.367     www      10703:     sub start_data_table_header_row {
1.389     albertel 10704: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10705:     }
                   10706: 
                   10707:     sub end_data_table_header_row {
1.389     albertel 10708: 	return '</tr>'."\n";;
1.367     www      10709:     }
1.890     droeschl 10710: 
                   10711:     sub data_table_caption {
                   10712:         my $caption = shift;
                   10713:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10714:     }
1.347     albertel 10715: }
                   10716: 
1.548     albertel 10717: =pod
                   10718: 
                   10719: =item * &inhibit_menu_check($arg)
                   10720: 
                   10721: Checks for a inhibitmenu state and generates output to preserve it
                   10722: 
                   10723: Inputs:         $arg - can be any of
                   10724:                      - undef - in which case the return value is a string 
                   10725:                                to add  into arguments list of a uri
                   10726:                      - 'input' - in which case the return value is a HTML
                   10727:                                  <form> <input> field of type hidden to
                   10728:                                  preserve the value
                   10729:                      - a url - in which case the return value is the url with
                   10730:                                the neccesary cgi args added to preserve the
                   10731:                                inhibitmenu state
                   10732:                      - a ref to a url - no return value, but the string is
                   10733:                                         updated to include the neccessary cgi
                   10734:                                         args to preserve the inhibitmenu state
                   10735: 
                   10736: =cut
                   10737: 
                   10738: sub inhibit_menu_check {
                   10739:     my ($arg) = @_;
                   10740:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10741:     if ($arg eq 'input') {
                   10742: 	if ($env{'form.inhibitmenu'}) {
                   10743: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10744: 	} else {
                   10745: 	    return
                   10746: 	}
                   10747:     }
                   10748:     if ($env{'form.inhibitmenu'}) {
                   10749: 	if (ref($arg)) {
                   10750: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10751: 	} elsif ($arg eq '') {
                   10752: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10753: 	} else {
                   10754: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10755: 	}
                   10756:     }
                   10757:     if (!ref($arg)) {
                   10758: 	return $arg;
                   10759:     }
                   10760: }
                   10761: 
1.251     albertel 10762: ###############################################
1.182     matthew  10763: 
                   10764: =pod
                   10765: 
1.549     albertel 10766: =back
                   10767: 
                   10768: =head1 User Information Routines
                   10769: 
                   10770: =over 4
                   10771: 
1.405     albertel 10772: =item * &get_users_function()
1.182     matthew  10773: 
                   10774: Used by &bodytag to determine the current users primary role.
                   10775: Returns either 'student','coordinator','admin', or 'author'.
                   10776: 
                   10777: =cut
                   10778: 
                   10779: ###############################################
                   10780: sub get_users_function {
1.815     tempelho 10781:     my $function = 'norole';
1.818     tempelho 10782:     if ($env{'request.role'}=~/^(st)/) {
                   10783:         $function='student';
                   10784:     }
1.907     raeburn  10785:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10786:         $function='coordinator';
                   10787:     }
1.258     albertel 10788:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10789:         $function='admin';
                   10790:     }
1.826     bisitz   10791:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10792:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10793:         $function='author';
                   10794:     }
                   10795:     return $function;
1.54      www      10796: }
1.99      www      10797: 
                   10798: ###############################################
                   10799: 
1.233     raeburn  10800: =pod
                   10801: 
1.821     raeburn  10802: =item * &show_course()
                   10803: 
                   10804: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10805: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10806: 
                   10807: Inputs:
                   10808: None
                   10809: 
                   10810: Outputs:
                   10811: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10812: 
                   10813: =cut
                   10814: 
                   10815: ###############################################
                   10816: sub show_course {
1.1408    raeburn  10817:     my ($udom,$uname) = @_;
                   10818:     if (($udom ne '') && ($uname ne '')) {
                   10819:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  10820:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  10821:                 return 0;
                   10822:             } else {
                   10823:                 return 1;
                   10824:             }
                   10825:         }
                   10826:     }
1.821     raeburn  10827:     my $course = !$env{'user.adv'};
                   10828:     if (!$env{'user.adv'}) {
                   10829:         foreach my $env (keys(%env)) {
                   10830:             next if ($env !~ m/^user\.priv\./);
                   10831:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10832:                 $course = 0;
                   10833:                 last;
                   10834:             }
                   10835:         }
                   10836:     }
                   10837:     return $course;
                   10838: }
                   10839: 
                   10840: ###############################################
                   10841: 
                   10842: =pod
                   10843: 
1.542     raeburn  10844: =item * &check_user_status()
1.274     raeburn  10845: 
                   10846: Determines current status of supplied role for a
                   10847: specific user. Roles can be active, previous or future.
                   10848: 
                   10849: Inputs: 
                   10850: user's domain, user's username, course's domain,
1.375     raeburn  10851: course's number, optional section ID.
1.274     raeburn  10852: 
                   10853: Outputs:
                   10854: role status: active, previous or future. 
                   10855: 
                   10856: =cut
                   10857: 
                   10858: sub check_user_status {
1.412     raeburn  10859:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10860:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10861:     my @uroles = keys(%userinfo);
1.274     raeburn  10862:     my $srchstr;
                   10863:     my $active_chk = 'none';
1.412     raeburn  10864:     my $now = time;
1.274     raeburn  10865:     if (@uroles > 0) {
1.908     raeburn  10866:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10867:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10868:         } else {
1.412     raeburn  10869:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10870:         }
                   10871:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10872:             my $role_end = 0;
                   10873:             my $role_start = 0;
                   10874:             $active_chk = 'active';
1.412     raeburn  10875:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10876:                 $role_end = $1;
                   10877:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10878:                     $role_start = $1;
1.274     raeburn  10879:                 }
                   10880:             }
                   10881:             if ($role_start > 0) {
1.412     raeburn  10882:                 if ($now < $role_start) {
1.274     raeburn  10883:                     $active_chk = 'future';
                   10884:                 }
                   10885:             }
                   10886:             if ($role_end > 0) {
1.412     raeburn  10887:                 if ($now > $role_end) {
1.274     raeburn  10888:                     $active_chk = 'previous';
                   10889:                 }
                   10890:             }
                   10891:         }
                   10892:     }
                   10893:     return $active_chk;
                   10894: }
                   10895: 
                   10896: ###############################################
                   10897: 
                   10898: =pod
                   10899: 
1.405     albertel 10900: =item * &get_sections()
1.233     raeburn  10901: 
                   10902: Determines all the sections for a course including
                   10903: sections with students and sections containing other roles.
1.419     raeburn  10904: Incoming parameters: 
                   10905: 
                   10906: 1. domain
                   10907: 2. course number 
                   10908: 3. reference to array containing roles for which sections should 
                   10909: be gathered (optional).
                   10910: 4. reference to array containing status types for which sections 
                   10911: should be gathered (optional).
                   10912: 
                   10913: If the third argument is undefined, sections are gathered for any role. 
                   10914: If the fourth argument is undefined, sections are gathered for any status.
                   10915: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10916:  
1.374     raeburn  10917: Returns section hash (keys are section IDs, values are
                   10918: number of users in each section), subject to the
1.419     raeburn  10919: optional roles filter, optional status filter 
1.233     raeburn  10920: 
                   10921: =cut
                   10922: 
                   10923: ###############################################
                   10924: sub get_sections {
1.419     raeburn  10925:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10926:     if (!defined($cdom) || !defined($cnum)) {
                   10927:         my $cid =  $env{'request.course.id'};
                   10928: 
                   10929: 	return if (!defined($cid));
                   10930: 
                   10931:         $cdom = $env{'course.'.$cid.'.domain'};
                   10932:         $cnum = $env{'course.'.$cid.'.num'};
                   10933:     }
                   10934: 
                   10935:     my %sectioncount;
1.419     raeburn  10936:     my $now = time;
1.240     albertel 10937: 
1.1118    raeburn  10938:     my $check_students = 1;
                   10939:     my $only_students = 0;
                   10940:     if (ref($possible_roles) eq 'ARRAY') {
                   10941:         if (grep(/^st$/,@{$possible_roles})) {
                   10942:             if (@{$possible_roles} == 1) {
                   10943:                 $only_students = 1;
                   10944:             }
                   10945:         } else {
                   10946:             $check_students = 0;
                   10947:         }
                   10948:     }
                   10949: 
                   10950:     if ($check_students) { 
1.276     albertel 10951: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10952: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10953: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10954:         my $start_index = &Apache::loncoursedata::CL_START();
                   10955:         my $end_index = &Apache::loncoursedata::CL_END();
                   10956:         my $status;
1.366     albertel 10957: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10958: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10959: 				                     $data->[$status_index],
                   10960:                                                      $data->[$start_index],
                   10961:                                                      $data->[$end_index]);
                   10962:             if ($stu_status eq 'Active') {
                   10963:                 $status = 'active';
                   10964:             } elsif ($end < $now) {
                   10965:                 $status = 'previous';
                   10966:             } elsif ($start > $now) {
                   10967:                 $status = 'future';
                   10968:             } 
                   10969: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10970:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10971:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10972: 		    $sectioncount{$section}++;
                   10973:                 }
1.240     albertel 10974: 	    }
                   10975: 	}
                   10976:     }
1.1118    raeburn  10977:     if ($only_students) {
                   10978:         return %sectioncount;
                   10979:     }
1.240     albertel 10980:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10981:     foreach my $user (sort(keys(%courseroles))) {
                   10982: 	if ($user !~ /^(\w{2})/) { next; }
                   10983: 	my ($role) = ($user =~ /^(\w{2})/);
                   10984: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10985: 	my ($section,$status);
1.240     albertel 10986: 	if ($role eq 'cr' &&
                   10987: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10988: 	    $section=$1;
                   10989: 	}
                   10990: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10991: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10992:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10993:         if ($end == -1 && $start == -1) {
                   10994:             next; #deleted role
                   10995:         }
                   10996:         if (!defined($possible_status)) { 
                   10997:             $sectioncount{$section}++;
                   10998:         } else {
                   10999:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11000:                 $status = 'active';
                   11001:             } elsif ($end < $now) {
                   11002:                 $status = 'future';
                   11003:             } elsif ($start > $now) {
                   11004:                 $status = 'previous';
                   11005:             }
                   11006:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11007:                 $sectioncount{$section}++;
                   11008:             }
                   11009:         }
1.233     raeburn  11010:     }
1.366     albertel 11011:     return %sectioncount;
1.233     raeburn  11012: }
                   11013: 
1.274     raeburn  11014: ###############################################
1.294     raeburn  11015: 
                   11016: =pod
1.405     albertel 11017: 
                   11018: =item * &get_course_users()
                   11019: 
1.275     raeburn  11020: Retrieves usernames:domains for users in the specified course
                   11021: with specific role(s), and access status. 
                   11022: 
                   11023: Incoming parameters:
1.277     albertel 11024: 1. course domain
                   11025: 2. course number
                   11026: 3. access status: users must have - either active, 
1.275     raeburn  11027: previous, future, or all.
1.277     albertel 11028: 4. reference to array of permissible roles
1.288     raeburn  11029: 5. reference to array of section restrictions (optional)
                   11030: 6. reference to results object (hash of hashes).
                   11031: 7. reference to optional userdata hash
1.609     raeburn  11032: 8. reference to optional statushash
1.630     raeburn  11033: 9. flag if privileged users (except those set to unhide in
                   11034:    course settings) should be excluded    
1.609     raeburn  11035: Keys of top level results hash are roles.
1.275     raeburn  11036: Keys of inner hashes are username:domain, with 
                   11037: values set to access type.
1.288     raeburn  11038: Optional userdata hash returns an array with arguments in the 
                   11039: same order as loncoursedata::get_classlist() for student data.
                   11040: 
1.609     raeburn  11041: Optional statushash returns
                   11042: 
1.288     raeburn  11043: Entries for end, start, section and status are blank because
                   11044: of the possibility of multiple values for non-student roles.
                   11045: 
1.275     raeburn  11046: =cut
1.405     albertel 11047: 
1.275     raeburn  11048: ###############################################
1.405     albertel 11049: 
1.275     raeburn  11050: sub get_course_users {
1.630     raeburn  11051:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11052:     my %idx = ();
1.419     raeburn  11053:     my %seclists;
1.288     raeburn  11054: 
                   11055:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11056:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11057:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11058:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11059:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11060:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11061:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11062:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11063: 
1.290     albertel 11064:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11065:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11066:         my $now = time;
1.277     albertel 11067:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11068:             my $match = 0;
1.412     raeburn  11069:             my $secmatch = 0;
1.419     raeburn  11070:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11071:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11072:             if ($section eq '') {
                   11073:                 $section = 'none';
                   11074:             }
1.291     albertel 11075:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11076:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11077:                     $secmatch = 1;
                   11078:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11079:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11080:                         $secmatch = 1;
                   11081:                     }
                   11082:                 } else {  
1.419     raeburn  11083: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11084: 		        $secmatch = 1;
                   11085:                     }
1.290     albertel 11086: 		}
1.412     raeburn  11087:                 if (!$secmatch) {
                   11088:                     next;
                   11089:                 }
1.419     raeburn  11090:             }
1.275     raeburn  11091:             if (defined($$types{'active'})) {
1.288     raeburn  11092:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11093:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11094:                     $match = 1;
1.275     raeburn  11095:                 }
                   11096:             }
                   11097:             if (defined($$types{'previous'})) {
1.609     raeburn  11098:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11099:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11100:                     $match = 1;
1.275     raeburn  11101:                 }
                   11102:             }
                   11103:             if (defined($$types{'future'})) {
1.609     raeburn  11104:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11105:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11106:                     $match = 1;
1.275     raeburn  11107:                 }
                   11108:             }
1.609     raeburn  11109:             if ($match) {
                   11110:                 push(@{$seclists{$student}},$section);
                   11111:                 if (ref($userdata) eq 'HASH') {
                   11112:                     $$userdata{$student} = $$classlist{$student};
                   11113:                 }
                   11114:                 if (ref($statushash) eq 'HASH') {
                   11115:                     $statushash->{$student}{'st'}{$section} = $status;
                   11116:                 }
1.288     raeburn  11117:             }
1.275     raeburn  11118:         }
                   11119:     }
1.412     raeburn  11120:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11121:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11122:         my $now = time;
1.609     raeburn  11123:         my %displaystatus = ( previous => 'Expired',
                   11124:                               active   => 'Active',
                   11125:                               future   => 'Future',
                   11126:                             );
1.1121    raeburn  11127:         my (%nothide,@possdoms);
1.630     raeburn  11128:         if ($hidepriv) {
                   11129:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11130:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11131:                 if ($user !~ /:/) {
                   11132:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11133:                 } else {
                   11134:                     $nothide{$user} = 1;
                   11135:                 }
                   11136:             }
1.1121    raeburn  11137:             my @possdoms = ($cdom);
                   11138:             if ($coursehash{'checkforpriv'}) {
                   11139:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11140:             }
1.630     raeburn  11141:         }
1.439     raeburn  11142:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11143:             my $match = 0;
1.412     raeburn  11144:             my $secmatch = 0;
1.439     raeburn  11145:             my $status;
1.412     raeburn  11146:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11147:             $user =~ s/:$//;
1.439     raeburn  11148:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11149:             if ($end == -1 || $start == -1) {
                   11150:                 next;
                   11151:             }
                   11152:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11153:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11154:                 my ($uname,$udom) = split(/:/,$user);
                   11155:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11156:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11157:                         $secmatch = 1;
                   11158:                     } elsif ($usec eq '') {
1.420     albertel 11159:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11160:                             $secmatch = 1;
                   11161:                         }
                   11162:                     } else {
                   11163:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11164:                             $secmatch = 1;
                   11165:                         }
                   11166:                     }
                   11167:                     if (!$secmatch) {
                   11168:                         next;
                   11169:                     }
1.288     raeburn  11170:                 }
1.419     raeburn  11171:                 if ($usec eq '') {
                   11172:                     $usec = 'none';
                   11173:                 }
1.275     raeburn  11174:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11175:                     if ($hidepriv) {
1.1121    raeburn  11176:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11177:                             (!$nothide{$uname.':'.$udom})) {
                   11178:                             next;
                   11179:                         }
                   11180:                     }
1.503     raeburn  11181:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11182:                         $status = 'previous';
                   11183:                     } elsif ($start > $now) {
                   11184:                         $status = 'future';
                   11185:                     } else {
                   11186:                         $status = 'active';
                   11187:                     }
1.277     albertel 11188:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11189:                         if ($status eq $type) {
1.420     albertel 11190:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11191:                                 push(@{$$users{$role}{$user}},$type);
                   11192:                             }
1.288     raeburn  11193:                             $match = 1;
                   11194:                         }
                   11195:                     }
1.419     raeburn  11196:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11197:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11198: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11199:                         }
1.420     albertel 11200:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11201:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11202:                         }
1.609     raeburn  11203:                         if (ref($statushash) eq 'HASH') {
                   11204:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11205:                         }
1.275     raeburn  11206:                     }
                   11207:                 }
                   11208:             }
                   11209:         }
1.290     albertel 11210:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11211:             if ((defined($cdom)) && (defined($cnum))) {
                   11212:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11213:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11214:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11215:                     next if ($owner eq '');
                   11216:                     my ($ownername,$ownerdom);
                   11217:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11218:                         $ownername = $1;
                   11219:                         $ownerdom = $2;
                   11220:                     } else {
                   11221:                         $ownername = $owner;
                   11222:                         $ownerdom = $cdom;
                   11223:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11224:                     }
                   11225:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11226:                     if (defined($userdata) && 
1.609     raeburn  11227: 			!exists($$userdata{$owner})) {
                   11228: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11229:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11230:                             push(@{$seclists{$owner}},'none');
                   11231:                         }
                   11232:                         if (ref($statushash) eq 'HASH') {
                   11233:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11234:                         }
1.290     albertel 11235: 		    }
1.279     raeburn  11236:                 }
                   11237:             }
                   11238:         }
1.419     raeburn  11239:         foreach my $user (keys(%seclists)) {
                   11240:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11241:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11242:         }
1.275     raeburn  11243:     }
                   11244:     return;
                   11245: }
                   11246: 
1.288     raeburn  11247: sub get_user_info {
                   11248:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11249:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11250: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11251:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11252:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11253:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11254:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11255:     return;
                   11256: }
1.275     raeburn  11257: 
1.472     raeburn  11258: ###############################################
                   11259: 
                   11260: =pod
                   11261: 
                   11262: =item * &get_user_quota()
                   11263: 
1.1134    raeburn  11264: Retrieves quota assigned for storage of user files.
                   11265: Default is to report quota for portfolio files.
1.472     raeburn  11266: 
                   11267: Incoming parameters:
                   11268: 1. user's username
                   11269: 2. user's domain
1.1134    raeburn  11270: 3. quota name - portfolio, author, or course
1.1136    raeburn  11271:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11272: 4. crstype - official, unofficial, textbook, placement or community, 
                   11273:    if quota name is course
1.472     raeburn  11274: 
                   11275: Returns:
1.1163    raeburn  11276: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11277: 2. (Optional) Type of setting: custom or default
                   11278:    (individually assigned or default for user's 
                   11279:    institutional status).
                   11280: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11281:    or student - types as defined in localenroll::inst_usertypes 
                   11282:    for user's domain, which determines default quota for user.
                   11283: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11284: 
                   11285: If a value has been stored in the user's environment, 
1.536     raeburn  11286: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11287: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11288: 
                   11289: =cut
                   11290: 
                   11291: ###############################################
                   11292: 
                   11293: 
                   11294: sub get_user_quota {
1.1136    raeburn  11295:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11296:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11297:     if (!defined($udom)) {
                   11298:         $udom = $env{'user.domain'};
                   11299:     }
                   11300:     if (!defined($uname)) {
                   11301:         $uname = $env{'user.name'};
                   11302:     }
                   11303:     if (($udom eq '' || $uname eq '') ||
                   11304:         ($udom eq 'public') && ($uname eq 'public')) {
                   11305:         $quota = 0;
1.536     raeburn  11306:         $quotatype = 'default';
                   11307:         $defquota = 0; 
1.472     raeburn  11308:     } else {
1.536     raeburn  11309:         my $inststatus;
1.1134    raeburn  11310:         if ($quotaname eq 'course') {
                   11311:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11312:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11313:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11314:             } else {
                   11315:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11316:                 $quota = $cenv{'internal.uploadquota'};
                   11317:             }
1.536     raeburn  11318:         } else {
1.1134    raeburn  11319:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11320:                 if ($quotaname eq 'author') {
                   11321:                     $quota = $env{'environment.authorquota'};
                   11322:                 } else {
                   11323:                     $quota = $env{'environment.portfolioquota'};
                   11324:                 }
                   11325:                 $inststatus = $env{'environment.inststatus'};
                   11326:             } else {
                   11327:                 my %userenv = 
                   11328:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11329:                                          'authorquota','inststatus'],$udom,$uname);
                   11330:                 my ($tmp) = keys(%userenv);
                   11331:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11332:                     if ($quotaname eq 'author') {
                   11333:                         $quota = $userenv{'authorquota'};
                   11334:                     } else {
                   11335:                         $quota = $userenv{'portfolioquota'};
                   11336:                     }
                   11337:                     $inststatus = $userenv{'inststatus'};
                   11338:                 } else {
                   11339:                     undef(%userenv);
                   11340:                 }
                   11341:             }
                   11342:         }
                   11343:         if ($quota eq '' || wantarray) {
                   11344:             if ($quotaname eq 'course') {
                   11345:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11346:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11347:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11348:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11349:                     $defquota = $domdefs{$crstype.'quota'};
                   11350:                 }
                   11351:                 if ($defquota eq '') {
                   11352:                     $defquota = 500;
                   11353:                 }
1.1134    raeburn  11354:             } else {
                   11355:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11356:             }
                   11357:             if ($quota eq '') {
                   11358:                 $quota = $defquota;
                   11359:                 $quotatype = 'default';
                   11360:             } else {
                   11361:                 $quotatype = 'custom';
                   11362:             }
1.472     raeburn  11363:         }
                   11364:     }
1.536     raeburn  11365:     if (wantarray) {
                   11366:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11367:     } else {
                   11368:         return $quota;
                   11369:     }
1.472     raeburn  11370: }
                   11371: 
                   11372: ###############################################
                   11373: 
                   11374: =pod
                   11375: 
                   11376: =item * &default_quota()
                   11377: 
1.536     raeburn  11378: Retrieves default quota assigned for storage of user portfolio files,
                   11379: given an (optional) user's institutional status.
1.472     raeburn  11380: 
                   11381: Incoming parameters:
1.1142    raeburn  11382: 
1.472     raeburn  11383: 1. domain
1.536     raeburn  11384: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11385:    status types (e.g., faculty, staff, student etc.)
                   11386:    which apply to the user for whom the default is being retrieved.
                   11387:    If the institutional status string in undefined, the domain
1.1134    raeburn  11388:    default quota will be returned.
                   11389: 3.  quota name - portfolio, author, or course
                   11390:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11391: 
                   11392: Returns:
1.1142    raeburn  11393: 
1.1163    raeburn  11394: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11395: 2. (Optional) institutional type which determined the value of the
                   11396:    default quota.
1.472     raeburn  11397: 
                   11398: If a value has been stored in the domain's configuration db,
                   11399: it will return that, otherwise it returns 20 (for backwards 
                   11400: compatibility with domains which have not set up a configuration
1.1163    raeburn  11401: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11402: 
1.536     raeburn  11403: If the user's status includes multiple types (e.g., staff and student),
                   11404: the largest default quota which applies to the user determines the
                   11405: default quota returned.
                   11406: 
1.472     raeburn  11407: =cut
                   11408: 
                   11409: ###############################################
                   11410: 
                   11411: 
                   11412: sub default_quota {
1.1134    raeburn  11413:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11414:     my ($defquota,$settingstatus);
                   11415:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11416:                                             ['quotas'],$udom);
1.1134    raeburn  11417:     my $key = 'defaultquota';
                   11418:     if ($quotaname eq 'author') {
                   11419:         $key = 'authorquota';
                   11420:     }
1.622     raeburn  11421:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11422:         if ($inststatus ne '') {
1.765     raeburn  11423:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11424:             foreach my $item (@statuses) {
1.1134    raeburn  11425:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11426:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11427:                         if ($defquota eq '') {
1.1134    raeburn  11428:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11429:                             $settingstatus = $item;
1.1134    raeburn  11430:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11431:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11432:                             $settingstatus = $item;
                   11433:                         }
                   11434:                     }
1.1134    raeburn  11435:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11436:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11437:                         if ($defquota eq '') {
                   11438:                             $defquota = $quotahash{'quotas'}{$item};
                   11439:                             $settingstatus = $item;
                   11440:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11441:                             $defquota = $quotahash{'quotas'}{$item};
                   11442:                             $settingstatus = $item;
                   11443:                         }
1.536     raeburn  11444:                     }
                   11445:                 }
                   11446:             }
                   11447:         }
                   11448:         if ($defquota eq '') {
1.1134    raeburn  11449:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11450:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11451:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11452:                 $defquota = $quotahash{'quotas'}{'default'};
                   11453:             }
1.536     raeburn  11454:             $settingstatus = 'default';
1.1139    raeburn  11455:             if ($defquota eq '') {
                   11456:                 if ($quotaname eq 'author') {
                   11457:                     $defquota = 500;
                   11458:                 }
                   11459:             }
1.536     raeburn  11460:         }
                   11461:     } else {
                   11462:         $settingstatus = 'default';
1.1134    raeburn  11463:         if ($quotaname eq 'author') {
                   11464:             $defquota = 500;
                   11465:         } else {
                   11466:             $defquota = 20;
                   11467:         }
1.536     raeburn  11468:     }
                   11469:     if (wantarray) {
                   11470:         return ($defquota,$settingstatus);
1.472     raeburn  11471:     } else {
1.536     raeburn  11472:         return $defquota;
1.472     raeburn  11473:     }
                   11474: }
                   11475: 
1.1135    raeburn  11476: ###############################################
                   11477: 
                   11478: =pod
                   11479: 
1.1136    raeburn  11480: =item * &excess_filesize_warning()
1.1135    raeburn  11481: 
                   11482: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11483: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11484: space to be exceeded.
1.1136    raeburn  11485: 
                   11486: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11487: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11488: 
1.1165    raeburn  11489: Inputs: 7 
1.1136    raeburn  11490: 1. username or coursenum
1.1135    raeburn  11491: 2. domain
1.1136    raeburn  11492: 3. context ('author' or 'course')
1.1135    raeburn  11493: 4. filename of file for which action is being requested
                   11494: 5. filesize (kB) of file
                   11495: 6. action being taken: copy or upload.
1.1237    raeburn  11496: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11497: 
                   11498: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11499:          otherwise return null.
                   11500: 
                   11501: =back
1.1135    raeburn  11502: 
                   11503: =cut
                   11504: 
1.1136    raeburn  11505: sub excess_filesize_warning {
1.1165    raeburn  11506:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11507:     my $current_disk_usage = 0;
1.1165    raeburn  11508:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11509:     if ($context eq 'author') {
                   11510:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11511:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11512:     } else {
                   11513:         foreach my $subdir ('docs','supplemental') {
                   11514:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11515:         }
                   11516:     }
1.1135    raeburn  11517:     $disk_quota = int($disk_quota * 1000);
                   11518:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11519:         return '<p class="LC_warning">'.
1.1135    raeburn  11520:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11521:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11522:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11523:                             $disk_quota,$current_disk_usage).
                   11524:                '</p>';
                   11525:     }
                   11526:     return;
                   11527: }
                   11528: 
                   11529: ###############################################
                   11530: 
                   11531: 
1.1136    raeburn  11532: 
                   11533: 
1.384     raeburn  11534: sub get_secgrprole_info {
                   11535:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11536:     my %sections_count = &get_sections($cdom,$cnum);
                   11537:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11538:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11539:     my @groups = sort(keys(%curr_groups));
                   11540:     my $allroles = [];
                   11541:     my $rolehash;
                   11542:     my $accesshash = {
                   11543:                      active => 'Currently has access',
                   11544:                      future => 'Will have future access',
                   11545:                      previous => 'Previously had access',
                   11546:                   };
                   11547:     if ($needroles) {
                   11548:         $rolehash = {'all' => 'all'};
1.385     albertel 11549:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11550: 	if (&Apache::lonnet::error(%user_roles)) {
                   11551: 	    undef(%user_roles);
                   11552: 	}
                   11553:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11554:             my ($role)=split(/\:/,$item,2);
                   11555:             if ($role eq 'cr') { next; }
                   11556:             if ($role =~ /^cr/) {
                   11557:                 $$rolehash{$role} = (split('/',$role))[3];
                   11558:             } else {
                   11559:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11560:             }
                   11561:         }
                   11562:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11563:             push(@{$allroles},$key);
                   11564:         }
                   11565:         push (@{$allroles},'st');
                   11566:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11567:     }
                   11568:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11569: }
                   11570: 
1.555     raeburn  11571: sub user_picker {
1.1279    raeburn  11572:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11573:     my $currdom = $dom;
1.1253    raeburn  11574:     my @alldoms = &Apache::lonnet::all_domains();
                   11575:     if (@alldoms == 1) {
                   11576:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11577:                                                ['directorysrch'],$alldoms[0]);
                   11578:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11579:         my $showdom = $domdesc;
                   11580:         if ($showdom eq '') {
                   11581:             $showdom = $dom;
                   11582:         }
                   11583:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11584:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11585:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11586:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11587:             }
                   11588:         }
                   11589:     }
1.555     raeburn  11590:     my %curr_selected = (
                   11591:                         srchin => 'dom',
1.580     raeburn  11592:                         srchby => 'lastname',
1.555     raeburn  11593:                       );
                   11594:     my $srchterm;
1.625     raeburn  11595:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11596:         if ($srch->{'srchby'} ne '') {
                   11597:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11598:         }
                   11599:         if ($srch->{'srchin'} ne '') {
                   11600:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11601:         }
                   11602:         if ($srch->{'srchtype'} ne '') {
                   11603:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11604:         }
                   11605:         if ($srch->{'srchdomain'} ne '') {
                   11606:             $currdom = $srch->{'srchdomain'};
                   11607:         }
                   11608:         $srchterm = $srch->{'srchterm'};
                   11609:     }
1.1222    damieng  11610:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11611:                     'usr'       => 'Search criteria',
1.563     raeburn  11612:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11613:                     'uname'     => 'username',
                   11614:                     'lastname'  => 'last name',
1.555     raeburn  11615:                     'lastfirst' => 'last name, first name',
1.558     albertel 11616:                     'crs'       => 'in this course',
1.576     raeburn  11617:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11618:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11619:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11620:                     'exact'     => 'is',
                   11621:                     'contains'  => 'contains',
1.569     raeburn  11622:                     'begins'    => 'begins with',
1.1222    damieng  11623:                                        );
                   11624:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11625:                     'youm'      => "You must include some text to search for.",
                   11626:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11627:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11628:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11629:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11630:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11631:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11632:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11633:                                        );
1.1222    damieng  11634:     &html_escape(\%html_lt);
                   11635:     &js_escape(\%js_lt);
1.1255    raeburn  11636:     my $domform;
1.1277    raeburn  11637:     my $allow_blank = 1;
1.1255    raeburn  11638:     if ($fixeddom) {
1.1277    raeburn  11639:         $allow_blank = 0;
                   11640:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11641:     } else {
1.1287    raeburn  11642:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11643:         my ($trusted,$untrusted);
1.1287    raeburn  11644:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11645:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11646:         } elsif ($context eq 'author') {
1.1288    raeburn  11647:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11648:         } elsif ($context eq 'domain') {
1.1288    raeburn  11649:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11650:         }
1.1288    raeburn  11651:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11652:     }
1.563     raeburn  11653:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11654: 
                   11655:     my @srchins = ('crs','dom','alc','instd');
                   11656: 
                   11657:     foreach my $option (@srchins) {
                   11658:         # FIXME 'alc' option unavailable until 
                   11659:         #       loncreateuser::print_user_query_page()
                   11660:         #       has been completed.
                   11661:         next if ($option eq 'alc');
1.880     raeburn  11662:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11663:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11664:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11665:         if ($curr_selected{'srchin'} eq $option) {
                   11666:             $srchinsel .= ' 
1.1222    damieng  11667:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11668:         } else {
                   11669:             $srchinsel .= '
1.1222    damieng  11670:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11671:         }
1.555     raeburn  11672:     }
1.563     raeburn  11673:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11674: 
                   11675:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11676:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11677:         if ($curr_selected{'srchby'} eq $option) {
                   11678:             $srchbysel .= '
1.1222    damieng  11679:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11680:         } else {
                   11681:             $srchbysel .= '
1.1222    damieng  11682:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11683:          }
                   11684:     }
                   11685:     $srchbysel .= "\n  </select>\n";
                   11686: 
                   11687:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11688:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11689:         if ($curr_selected{'srchtype'} eq $option) {
                   11690:             $srchtypesel .= '
1.1222    damieng  11691:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11692:         } else {
                   11693:             $srchtypesel .= '
1.1222    damieng  11694:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11695:         }
                   11696:     }
                   11697:     $srchtypesel .= "\n  </select>\n";
                   11698: 
1.558     albertel 11699:     my ($newuserscript,$new_user_create);
1.994     raeburn  11700:     my $context_dom = $env{'request.role.domain'};
                   11701:     if ($context eq 'requestcrs') {
                   11702:         if ($env{'form.coursedom'} ne '') { 
                   11703:             $context_dom = $env{'form.coursedom'};
                   11704:         }
                   11705:     }
1.556     raeburn  11706:     if ($forcenewuser) {
1.576     raeburn  11707:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11708:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11709:                 if ($cancreate) {
                   11710:                     $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>';
                   11711:                 } else {
1.799     bisitz   11712:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11713:                     my %usertypetext = (
                   11714:                         official   => 'institutional',
                   11715:                         unofficial => 'non-institutional',
                   11716:                     );
1.799     bisitz   11717:                     $new_user_create = '<p class="LC_warning">'
                   11718:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11719:                                       .' '
                   11720:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11721:                                           ,'<a href="'.$helplink.'">','</a>')
                   11722:                                       .'</p><br />';
1.627     raeburn  11723:                 }
1.576     raeburn  11724:             }
                   11725:         }
                   11726: 
1.556     raeburn  11727:         $newuserscript = <<"ENDSCRIPT";
                   11728: 
1.570     raeburn  11729: function setSearch(createnew,callingForm) {
1.556     raeburn  11730:     if (createnew == 1) {
1.570     raeburn  11731:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11732:             if (callingForm.srchby.options[i].value == 'uname') {
                   11733:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11734:             }
                   11735:         }
1.570     raeburn  11736:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11737:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11738: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11739:             }
                   11740:         }
1.570     raeburn  11741:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11742:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11743:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11744:             }
                   11745:         }
1.570     raeburn  11746:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11747:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11748:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11749:             }
                   11750:         }
                   11751:     }
                   11752: }
                   11753: ENDSCRIPT
1.558     albertel 11754: 
1.556     raeburn  11755:     }
                   11756: 
1.555     raeburn  11757:     my $output = <<"END_BLOCK";
1.556     raeburn  11758: <script type="text/javascript">
1.824     bisitz   11759: // <![CDATA[
1.570     raeburn  11760: function validateEntry(callingForm) {
1.558     albertel 11761: 
1.556     raeburn  11762:     var checkok = 1;
1.558     albertel 11763:     var srchin;
1.570     raeburn  11764:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11765: 	if ( callingForm.srchin[i].checked ) {
                   11766: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11767: 	}
                   11768:     }
                   11769: 
1.570     raeburn  11770:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11771:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11772:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11773:     var srchterm =  callingForm.srchterm.value;
                   11774:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11775:     var msg = "";
                   11776: 
                   11777:     if (srchterm == "") {
                   11778:         checkok = 0;
1.1222    damieng  11779:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11780:     }
                   11781: 
1.569     raeburn  11782:     if (srchtype== 'begins') {
                   11783:         if (srchterm.length < 2) {
                   11784:             checkok = 0;
1.1222    damieng  11785:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11786:         }
                   11787:     }
                   11788: 
1.556     raeburn  11789:     if (srchtype== 'contains') {
                   11790:         if (srchterm.length < 3) {
                   11791:             checkok = 0;
1.1222    damieng  11792:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11793:         }
                   11794:     }
                   11795:     if (srchin == 'instd') {
                   11796:         if (srchdomain == '') {
                   11797:             checkok = 0;
1.1222    damieng  11798:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11799:         }
                   11800:     }
                   11801:     if (srchin == 'dom') {
                   11802:         if (srchdomain == '') {
                   11803:             checkok = 0;
1.1222    damieng  11804:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11805:         }
                   11806:     }
                   11807:     if (srchby == 'lastfirst') {
                   11808:         if (srchterm.indexOf(",") == -1) {
                   11809:             checkok = 0;
1.1222    damieng  11810:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11811:         }
                   11812:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11813:             checkok = 0;
1.1222    damieng  11814:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11815:         }
                   11816:     }
                   11817:     if (checkok == 0) {
1.1222    damieng  11818:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11819:         return;
                   11820:     }
                   11821:     if (checkok == 1) {
1.570     raeburn  11822:         callingForm.submit();
1.556     raeburn  11823:     }
                   11824: }
                   11825: 
                   11826: $newuserscript
                   11827: 
1.824     bisitz   11828: // ]]>
1.556     raeburn  11829: </script>
1.558     albertel 11830: 
                   11831: $new_user_create
                   11832: 
1.555     raeburn  11833: END_BLOCK
1.558     albertel 11834: 
1.876     raeburn  11835:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11836:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11837:                $domform.
                   11838:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11839:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11840:                $srchbysel.
                   11841:                $srchtypesel. 
                   11842:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11843:                $srchinsel.
                   11844:                &Apache::lonhtmlcommon::row_closure(1). 
                   11845:                &Apache::lonhtmlcommon::end_pick_box().
                   11846:                '<br />';
1.1253    raeburn  11847:     return ($output,1);
1.555     raeburn  11848: }
                   11849: 
1.612     raeburn  11850: sub user_rule_check {
1.615     raeburn  11851:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11852:     my ($response,%inst_response);
1.612     raeburn  11853:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11854:         if (keys(%{$usershash}) > 1) {
                   11855:             my (%by_username,%by_id,%userdoms);
                   11856:             my $checkid; 
                   11857:             if (ref($checks) eq 'HASH') {
                   11858:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11859:                     $checkid = 1;
                   11860:                 }
                   11861:             }
                   11862:             foreach my $user (keys(%{$usershash})) {
                   11863:                 my ($uname,$udom) = split(/:/,$user);
                   11864:                 if ($checkid) {
                   11865:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11866:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11867:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11868:                             $userdoms{$udom} = 1;
1.1227    raeburn  11869:                             if (ref($inst_results) eq 'HASH') {
                   11870:                                 $inst_results->{$uname.':'.$udom} = {};
                   11871:                             }
1.1226    raeburn  11872:                         }
                   11873:                     }
                   11874:                 } else {
                   11875:                     $by_username{$udom}{$uname} = 1;
                   11876:                     $userdoms{$udom} = 1;
1.1227    raeburn  11877:                     if (ref($inst_results) eq 'HASH') {
                   11878:                         $inst_results->{$uname.':'.$udom} = {};
                   11879:                     }
1.1226    raeburn  11880:                 }
                   11881:             }
                   11882:             foreach my $udom (keys(%userdoms)) {
                   11883:                 if (!$got_rules->{$udom}) {
                   11884:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11885:                                                              ['usercreation'],$udom);
                   11886:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11887:                         foreach my $item ('username','id') {
                   11888:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11889:                                 $$curr_rules{$udom}{$item} =
                   11890:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11891:                             }
                   11892:                         }
                   11893:                     }
                   11894:                     $got_rules->{$udom} = 1;
                   11895:                 }
1.612     raeburn  11896:             }
1.1226    raeburn  11897:             if ($checkid) {
                   11898:                 foreach my $udom (keys(%by_id)) {
                   11899:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11900:                     if ($outcome eq 'ok') {
1.1227    raeburn  11901:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11902:                             my $uname = $by_id{$udom}{$id};
                   11903:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11904:                         }
1.1226    raeburn  11905:                         if (ref($results) eq 'HASH') {
                   11906:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11907:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11908:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11909:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11910:                                 }
1.1226    raeburn  11911:                             }
                   11912:                         }
                   11913:                     }
1.612     raeburn  11914:                 }
1.615     raeburn  11915:             } else {
1.1226    raeburn  11916:                 foreach my $udom (keys(%by_username)) {
                   11917:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11918:                     if ($outcome eq 'ok') {
1.1227    raeburn  11919:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11920:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11921:                         }
1.1226    raeburn  11922:                         if (ref($results) eq 'HASH') {
                   11923:                             foreach my $uname (keys(%{$results})) {
                   11924:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11925:                             }
                   11926:                         }
                   11927:                     }
                   11928:                 }
1.612     raeburn  11929:             }
1.1226    raeburn  11930:         } elsif (keys(%{$usershash}) == 1) {
                   11931:             my $user = (keys(%{$usershash}))[0];
                   11932:             my ($uname,$udom) = split(/:/,$user);
                   11933:             if (($udom ne '') && ($uname ne '')) {
                   11934:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11935:                     if (ref($checks) eq 'HASH') {
                   11936:                         if (defined($checks->{'username'})) {
                   11937:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11938:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11939:                         } elsif (defined($checks->{'id'})) {
                   11940:                             if ($usershash->{$user}->{'id'} ne '') {
                   11941:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11942:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11943:                                                                   $usershash->{$user}->{'id'});
                   11944:                             } else {
                   11945:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11946:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11947:                             }
1.585     raeburn  11948:                         }
1.1226    raeburn  11949:                     } else {
                   11950:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11951:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11952:                        return;
                   11953:                     }
                   11954:                     if (!$got_rules->{$udom}) {
                   11955:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11956:                                                                  ['usercreation'],$udom);
                   11957:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11958:                             foreach my $item ('username','id') {
                   11959:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11960:                                    $$curr_rules{$udom}{$item} = 
                   11961:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11962:                                 }
                   11963:                             }
                   11964:                         }
                   11965:                         $got_rules->{$udom} = 1;
1.585     raeburn  11966:                     }
                   11967:                 }
1.1226    raeburn  11968:             } else {
                   11969:                 return;
                   11970:             }
                   11971:         } else {
                   11972:             return;
                   11973:         }
                   11974:         foreach my $user (keys(%{$usershash})) {
                   11975:             my ($uname,$udom) = split(/:/,$user);
                   11976:             next if (($udom eq '') || ($uname eq ''));
                   11977:             my $id;
1.1227    raeburn  11978:             if (ref($inst_results) eq 'HASH') {
                   11979:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11980:                     $id = $inst_results->{$user}->{'id'};
                   11981:                 }
                   11982:             }
                   11983:             if ($id eq '') { 
                   11984:                 if (ref($usershash->{$user})) {
                   11985:                     $id = $usershash->{$user}->{'id'};
                   11986:                 }
1.585     raeburn  11987:             }
1.612     raeburn  11988:             foreach my $item (keys(%{$checks})) {
                   11989:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11990:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11991:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11992:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11993:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11994:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11995:                                 if ($rule_check{$rule}) {
                   11996:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11997:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11998:                                         if (ref($inst_results) eq 'HASH') {
                   11999:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12000:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12001:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12002:                                                 } elsif ($item eq 'id') {
                   12003:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12004:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12005:                                                     }
1.615     raeburn  12006:                                                 }
1.612     raeburn  12007:                                             }
                   12008:                                         }
1.615     raeburn  12009:                                     }
                   12010:                                     last;
1.585     raeburn  12011:                                 }
                   12012:                             }
                   12013:                         }
                   12014:                     }
                   12015:                 }
                   12016:             }
                   12017:         }
                   12018:     }
1.612     raeburn  12019:     return;
                   12020: }
                   12021: 
                   12022: sub user_rule_formats {
                   12023:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12024:     my %text = ( 
                   12025:                  'username' => 'Usernames',
                   12026:                  'id'       => 'IDs',
                   12027:                );
                   12028:     my $output;
                   12029:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12030:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12031:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12032:             $output = '<br />'.
                   12033:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12034:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12035:                       ' <ul>';
1.612     raeburn  12036:             foreach my $rule (@{$ruleorder}) {
                   12037:                 if (ref($curr_rules) eq 'ARRAY') {
                   12038:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12039:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12040:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12041:                                         $rules->{$rule}{'desc'}.'</li>';
                   12042:                         }
                   12043:                     }
                   12044:                 }
                   12045:             }
                   12046:             $output .= '</ul>';
                   12047:         }
                   12048:     }
                   12049:     return $output;
                   12050: }
                   12051: 
                   12052: sub instrule_disallow_msg {
1.615     raeburn  12053:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12054:     my $response;
                   12055:     my %text = (
                   12056:                   item   => 'username',
                   12057:                   items  => 'usernames',
                   12058:                   match  => 'matches',
                   12059:                   do     => 'does',
                   12060:                   action => 'a username',
                   12061:                   one    => 'one',
                   12062:                );
                   12063:     if ($count > 1) {
                   12064:         $text{'item'} = 'usernames';
                   12065:         $text{'match'} ='match';
                   12066:         $text{'do'} = 'do';
                   12067:         $text{'action'} = 'usernames',
                   12068:         $text{'one'} = 'ones';
                   12069:     }
                   12070:     if ($checkitem eq 'id') {
                   12071:         $text{'items'} = 'IDs';
                   12072:         $text{'item'} = 'ID';
                   12073:         $text{'action'} = 'an ID';
1.615     raeburn  12074:         if ($count > 1) {
                   12075:             $text{'item'} = 'IDs';
                   12076:             $text{'action'} = 'IDs';
                   12077:         }
1.612     raeburn  12078:     }
1.674     bisitz   12079:     $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  12080:     if ($mode eq 'upload') {
                   12081:         if ($checkitem eq 'username') {
                   12082:             $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'}.");
                   12083:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12084:             $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  12085:         }
1.669     raeburn  12086:     } elsif ($mode eq 'selfcreate') {
                   12087:         if ($checkitem eq 'id') {
                   12088:             $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.");
                   12089:         }
1.615     raeburn  12090:     } else {
                   12091:         if ($checkitem eq 'username') {
                   12092:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12093:         } elsif ($checkitem eq 'id') {
                   12094:             $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.");
                   12095:         }
1.612     raeburn  12096:     }
                   12097:     return $response;
1.585     raeburn  12098: }
                   12099: 
1.624     raeburn  12100: sub personal_data_fieldtitles {
                   12101:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12102:                         id => 'Student/Employee ID',
                   12103:                         permanentemail => 'E-mail address',
                   12104:                         lastname => 'Last Name',
                   12105:                         firstname => 'First Name',
                   12106:                         middlename => 'Middle Name',
                   12107:                         generation => 'Generation',
                   12108:                         gen => 'Generation',
1.765     raeburn  12109:                         inststatus => 'Affiliation',
1.624     raeburn  12110:                    );
                   12111:     return %fieldtitles;
                   12112: }
                   12113: 
1.642     raeburn  12114: sub sorted_inst_types {
                   12115:     my ($dom) = @_;
1.1185    raeburn  12116:     my ($usertypes,$order);
                   12117:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12118:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12119:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12120:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12121:     } else {
                   12122:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12123:     }
1.642     raeburn  12124:     my $othertitle = &mt('All users');
                   12125:     if ($env{'request.course.id'}) {
1.668     raeburn  12126:         $othertitle  = &mt('Any users');
1.642     raeburn  12127:     }
                   12128:     my @types;
                   12129:     if (ref($order) eq 'ARRAY') {
                   12130:         @types = @{$order};
                   12131:     }
                   12132:     if (@types == 0) {
                   12133:         if (ref($usertypes) eq 'HASH') {
                   12134:             @types = sort(keys(%{$usertypes}));
                   12135:         }
                   12136:     }
                   12137:     if (keys(%{$usertypes}) > 0) {
                   12138:         $othertitle = &mt('Other users');
                   12139:     }
                   12140:     return ($othertitle,$usertypes,\@types);
                   12141: }
                   12142: 
1.645     raeburn  12143: sub get_institutional_codes {
1.1361    raeburn  12144:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12145: # Get complete list of course sections to update
                   12146:     my @currsections = ();
                   12147:     my @currxlists = ();
1.1361    raeburn  12148:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12149:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12150:     my $crskey = $crs.':'.$coursecode;
                   12151:     @{$unclutteredsec{$crskey}} = ();
                   12152:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12153: 
                   12154:     if ($$settings{'internal.sectionnums'} ne '') {
                   12155:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12156:     }
                   12157: 
                   12158:     if ($$settings{'internal.crosslistings'} ne '') {
                   12159:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12160:     }
                   12161: 
                   12162:     if (@currxlists > 0) {
1.1361    raeburn  12163:         foreach my $xl (@currxlists) {
                   12164:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12165:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12166:                     push(@{$allcourses},$1);
1.645     raeburn  12167:                     $$LC_code{$1} = $2;
                   12168:                 }
                   12169:             }
                   12170:         }
                   12171:     }
1.1361    raeburn  12172: 
1.645     raeburn  12173:     if (@currsections > 0) {
1.1361    raeburn  12174:         foreach my $sec (@currsections) {
                   12175:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12176:                 my $instsec = $1;
1.645     raeburn  12177:                 my $lc_sec = $2;
1.1361    raeburn  12178:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12179:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12180:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12181:                 }
                   12182:             }
                   12183:         }
                   12184:     }
                   12185: 
                   12186:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12187:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12188:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12189:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12190:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12191:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12192:                     push(@{$allcourses},$sec);
1.1361    raeburn  12193:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12194:                 }
                   12195:             }
                   12196:         }
                   12197:     }
                   12198:     return;
                   12199: }
                   12200: 
1.971     raeburn  12201: sub get_standard_codeitems {
                   12202:     return ('Year','Semester','Department','Number','Section');
                   12203: }
                   12204: 
1.112     bowersj2 12205: =pod
                   12206: 
1.780     raeburn  12207: =head1 Slot Helpers
                   12208: 
                   12209: =over 4
                   12210: 
                   12211: =item * sorted_slots()
                   12212: 
1.1040    raeburn  12213: Sorts an array of slot names in order of an optional sort key,
                   12214: default sort is by slot start time (earliest first). 
1.780     raeburn  12215: 
                   12216: Inputs:
                   12217: 
                   12218: =over 4
                   12219: 
                   12220: slotsarr  - Reference to array of unsorted slot names.
                   12221: 
                   12222: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12223: 
1.1040    raeburn  12224: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12225: 
1.549     albertel 12226: =back
                   12227: 
1.780     raeburn  12228: Returns:
                   12229: 
                   12230: =over 4
                   12231: 
1.1040    raeburn  12232: sorted   - An array of slot names sorted by a specified sort key 
                   12233:            (default sort key is start time of the slot).
1.780     raeburn  12234: 
                   12235: =back
                   12236: 
                   12237: =cut
                   12238: 
                   12239: 
                   12240: sub sorted_slots {
1.1040    raeburn  12241:     my ($slotsarr,$slots,$sortkey) = @_;
                   12242:     if ($sortkey eq '') {
                   12243:         $sortkey = 'starttime';
                   12244:     }
1.780     raeburn  12245:     my @sorted;
                   12246:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12247:         @sorted =
                   12248:             sort {
                   12249:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12250:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12251:                      }
                   12252:                      if (ref($slots->{$a})) { return -1;}
                   12253:                      if (ref($slots->{$b})) { return 1;}
                   12254:                      return 0;
                   12255:                  } @{$slotsarr};
                   12256:     }
                   12257:     return @sorted;
                   12258: }
                   12259: 
1.1040    raeburn  12260: =pod
                   12261: 
                   12262: =item * get_future_slots()
                   12263: 
                   12264: Inputs:
                   12265: 
                   12266: =over 4
                   12267: 
                   12268: cnum - course number
                   12269: 
                   12270: cdom - course domain
                   12271: 
                   12272: now - current UNIX time
                   12273: 
                   12274: symb - optional symb
                   12275: 
                   12276: =back
                   12277: 
                   12278: Returns:
                   12279: 
                   12280: =over 4
                   12281: 
                   12282: sorted_reservable - ref to array of student_schedulable slots currently 
                   12283:                     reservable, ordered by end date of reservation period.
                   12284: 
                   12285: reservable_now - ref to hash of student_schedulable slots currently
                   12286:                  reservable.
                   12287: 
                   12288:     Keys in inner hash are:
                   12289:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12290:     (b) endreserve: end date of reservation period.
                   12291:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12292:         selected.
1.1040    raeburn  12293: 
                   12294: sorted_future - ref to array of student_schedulable slots reservable in
                   12295:                 the future, ordered by start date of reservation period.
                   12296: 
                   12297: future_reservable - ref to hash of student_schedulable slots reservable
                   12298:                     in the future.
                   12299: 
                   12300:     Keys in inner hash are:
                   12301:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12302:     (b) startreserve: start date of reservation period.
                   12303:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12304:         selected.
1.1040    raeburn  12305: 
                   12306: =back
                   12307: 
                   12308: =cut
                   12309: 
                   12310: sub get_future_slots {
                   12311:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12312:     my $map;
                   12313:     if ($symb) {
                   12314:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12315:     }
1.1040    raeburn  12316:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12317:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12318:     foreach my $slot (keys(%slots)) {
                   12319:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12320:         if ($symb) {
1.1229    raeburn  12321:             if ($slots{$slot}->{'symb'} ne '') {
                   12322:                 my $canuse;
                   12323:                 my %oksymbs;
                   12324:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12325:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12326:                 if ($oksymbs{$symb}) {
                   12327:                     $canuse = 1;
                   12328:                 } else {
                   12329:                     foreach my $item (@slotsymbs) {
                   12330:                         if ($item =~ /\.(page|sequence)$/) {
                   12331:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12332:                             if (($map ne '') && ($map eq $sloturl)) {
                   12333:                                 $canuse = 1;
                   12334:                                 last;
                   12335:                             }
                   12336:                         }
                   12337:                     }
                   12338:                 }
                   12339:                 next unless ($canuse);
                   12340:             }
1.1040    raeburn  12341:         }
                   12342:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12343:             ($slots{$slot}->{'endtime'} > $now)) {
                   12344:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12345:                 my $userallowed = 0;
                   12346:                 if ($slots{$slot}->{'allowedsections'}) {
                   12347:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12348:                     if (!defined($env{'request.role.sec'})
                   12349:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12350:                         $userallowed=1;
                   12351:                     } else {
                   12352:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12353:                             $userallowed=1;
                   12354:                         }
                   12355:                     }
                   12356:                     unless ($userallowed) {
                   12357:                         if (defined($env{'request.course.groups'})) {
                   12358:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12359:                             foreach my $group (@groups) {
                   12360:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12361:                                     $userallowed=1;
                   12362:                                     last;
                   12363:                                 }
                   12364:                             }
                   12365:                         }
                   12366:                     }
                   12367:                 }
                   12368:                 if ($slots{$slot}->{'allowedusers'}) {
                   12369:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12370:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12371:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12372:                         $userallowed = 1;
                   12373:                     }
                   12374:                 }
                   12375:                 next unless($userallowed);
                   12376:             }
                   12377:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12378:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12379:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12380:             my $uniqueperiod;
                   12381:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12382:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12383:             }
1.1040    raeburn  12384:             if (($startreserve < $now) &&
                   12385:                 (!$endreserve || $endreserve > $now)) {
                   12386:                 my $lastres = $endreserve;
                   12387:                 if (!$lastres) {
                   12388:                     $lastres = $slots{$slot}->{'starttime'};
                   12389:                 }
                   12390:                 $reservable_now{$slot} = {
                   12391:                                            symb       => $symb,
1.1250    raeburn  12392:                                            endreserve => $lastres,
                   12393:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12394:                                          };
                   12395:             } elsif (($startreserve > $now) &&
                   12396:                      (!$endreserve || $endreserve > $startreserve)) {
                   12397:                 $future_reservable{$slot} = {
                   12398:                                               symb         => $symb,
1.1250    raeburn  12399:                                               startreserve => $startreserve,
                   12400:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12401:                                             };
                   12402:             }
                   12403:         }
                   12404:     }
                   12405:     my @unsorted_reservable = keys(%reservable_now);
                   12406:     if (@unsorted_reservable > 0) {
                   12407:         @sorted_reservable = 
                   12408:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12409:     }
                   12410:     my @unsorted_future = keys(%future_reservable);
                   12411:     if (@unsorted_future > 0) {
                   12412:         @sorted_future =
                   12413:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12414:     }
                   12415:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12416: }
1.780     raeburn  12417: 
                   12418: =pod
                   12419: 
1.1057    foxr     12420: =back
                   12421: 
1.549     albertel 12422: =head1 HTTP Helpers
                   12423: 
                   12424: =over 4
                   12425: 
1.648     raeburn  12426: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12427: 
1.258     albertel 12428: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12429: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12430: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12431: 
                   12432: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12433: $possible_names is an ref to an array of form element names.  As an example:
                   12434: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12435: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12436: 
                   12437: =cut
1.1       albertel 12438: 
1.6       albertel 12439: sub get_unprocessed_cgi {
1.25      albertel 12440:   my ($query,$possible_names)= @_;
1.26      matthew  12441:   # $Apache::lonxml::debug=1;
1.356     albertel 12442:   foreach my $pair (split(/&/,$query)) {
                   12443:     my ($name, $value) = split(/=/,$pair);
1.369     www      12444:     $name = &unescape($name);
1.25      albertel 12445:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12446:       $value =~ tr/+/ /;
                   12447:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12448:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12449:     }
1.16      harris41 12450:   }
1.6       albertel 12451: }
                   12452: 
1.112     bowersj2 12453: =pod
                   12454: 
1.648     raeburn  12455: =item * &cacheheader() 
1.112     bowersj2 12456: 
                   12457: returns cache-controlling header code
                   12458: 
                   12459: =cut
                   12460: 
1.7       albertel 12461: sub cacheheader {
1.258     albertel 12462:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12463:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12464:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12465:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12466:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12467:     return $output;
1.7       albertel 12468: }
                   12469: 
1.112     bowersj2 12470: =pod
                   12471: 
1.648     raeburn  12472: =item * &no_cache($r) 
1.112     bowersj2 12473: 
                   12474: specifies header code to not have cache
                   12475: 
                   12476: =cut
                   12477: 
1.9       albertel 12478: sub no_cache {
1.216     albertel 12479:     my ($r) = @_;
                   12480:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12481: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12482:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12483:     $r->no_cache(1);
                   12484:     $r->header_out("Expires" => $date);
                   12485:     $r->header_out("Pragma" => "no-cache");
1.123     www      12486: }
                   12487: 
                   12488: sub content_type {
1.181     albertel 12489:     my ($r,$type,$charset) = @_;
1.299     foxr     12490:     if ($r) {
                   12491: 	#  Note that printout.pl calls this with undef for $r.
                   12492: 	&no_cache($r);
                   12493:     }
1.258     albertel 12494:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12495:     unless ($charset) {
                   12496: 	$charset=&Apache::lonlocal::current_encoding;
                   12497:     }
                   12498:     if ($charset) { $type.='; charset='.$charset; }
                   12499:     if ($r) {
                   12500: 	$r->content_type($type);
                   12501:     } else {
                   12502: 	print("Content-type: $type\n\n");
                   12503:     }
1.9       albertel 12504: }
1.25      albertel 12505: 
1.112     bowersj2 12506: =pod
                   12507: 
1.648     raeburn  12508: =item * &add_to_env($name,$value) 
1.112     bowersj2 12509: 
1.258     albertel 12510: adds $name to the %env hash with value
1.112     bowersj2 12511: $value, if $name already exists, the entry is converted to an array
                   12512: reference and $value is added to the array.
                   12513: 
                   12514: =cut
                   12515: 
1.25      albertel 12516: sub add_to_env {
                   12517:   my ($name,$value)=@_;
1.258     albertel 12518:   if (defined($env{$name})) {
                   12519:     if (ref($env{$name})) {
1.25      albertel 12520:       #already have multiple values
1.258     albertel 12521:       push(@{ $env{$name} },$value);
1.25      albertel 12522:     } else {
                   12523:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12524:       my $first=$env{$name};
                   12525:       undef($env{$name});
                   12526:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12527:     }
                   12528:   } else {
1.258     albertel 12529:     $env{$name}=$value;
1.25      albertel 12530:   }
1.31      albertel 12531: }
1.149     albertel 12532: 
                   12533: =pod
                   12534: 
1.648     raeburn  12535: =item * &get_env_multiple($name) 
1.149     albertel 12536: 
1.258     albertel 12537: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12538: values may be defined and end up as an array ref.
                   12539: 
                   12540: returns an array of values
                   12541: 
                   12542: =cut
                   12543: 
                   12544: sub get_env_multiple {
                   12545:     my ($name) = @_;
                   12546:     my @values;
1.258     albertel 12547:     if (defined($env{$name})) {
1.149     albertel 12548:         # exists is it an array
1.258     albertel 12549:         if (ref($env{$name})) {
                   12550:             @values=@{ $env{$name} };
1.149     albertel 12551:         } else {
1.258     albertel 12552:             $values[0]=$env{$name};
1.149     albertel 12553:         }
                   12554:     }
                   12555:     return(@values);
                   12556: }
                   12557: 
1.1249    damieng  12558: # Looks at given dependencies, and returns something depending on the context.
                   12559: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12560: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12561: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12562: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12563: # $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.
                   12564: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12565: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12566: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12567: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12568: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12569: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12570: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12571: # @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)
                   12572: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12573: sub ask_for_embedded_content {
1.1249    damieng  12574:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12575:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12576:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12577:         %currsubfile,%unused,$rem);
1.1071    raeburn  12578:     my $counter = 0;
                   12579:     my $numnew = 0;
1.987     raeburn  12580:     my $numremref = 0;
                   12581:     my $numinvalid = 0;
                   12582:     my $numpathchg = 0;
                   12583:     my $numexisting = 0;
1.1071    raeburn  12584:     my $numunused = 0;
                   12585:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12586:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12587:     my $heading = &mt('Upload embedded files');
                   12588:     my $buttontext = &mt('Upload');
                   12589: 
1.1249    damieng  12590:     # fills these variables based on the context:
                   12591:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12592:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12593:     if ($env{'request.course.id'}) {
1.1123    raeburn  12594:         if ($actionurl eq '/adm/dependencies') {
                   12595:             $navmap = Apache::lonnavmaps::navmap->new();
                   12596:         }
                   12597:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12598:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12599:     }
1.1123    raeburn  12600:     if (($actionurl eq '/adm/portfolio') || 
                   12601:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12602:         my $current_path='/';
                   12603:         if ($env{'form.currentpath'}) {
                   12604:             $current_path = $env{'form.currentpath'};
                   12605:         }
                   12606:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12607:             $udom = $cdom;
                   12608:             $uname = $cnum;
1.984     raeburn  12609:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12610:         } else {
                   12611:             $udom = $env{'user.domain'};
                   12612:             $uname = $env{'user.name'};
                   12613:             $url = '/userfiles/portfolio';
                   12614:         }
1.987     raeburn  12615:         $toplevel = $url.'/';
1.984     raeburn  12616:         $url .= $current_path;
                   12617:         $getpropath = 1;
1.987     raeburn  12618:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12619:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12620:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12621:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12622:         $toplevel = $url;
1.984     raeburn  12623:         if ($rest ne '') {
1.987     raeburn  12624:             $url .= $rest;
                   12625:         }
                   12626:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12627:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12628:             $url = $args->{'docs_url'};
                   12629:             $toplevel = $url;
1.1084    raeburn  12630:             if ($args->{'context'} eq 'paste') {
                   12631:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12632:                 ($path) = 
                   12633:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12634:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12635:                 $fileloc =~ s{^/}{};
                   12636:             }
1.1071    raeburn  12637:         }
1.1084    raeburn  12638:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12639:         if ($env{'request.course.id'} ne '') {
                   12640:             if (ref($args) eq 'HASH') {
                   12641:                 $url = $args->{'docs_url'};
                   12642:                 $title = $args->{'docs_title'};
1.1126    raeburn  12643:                 $toplevel = $url; 
                   12644:                 unless ($toplevel =~ m{^/}) {
                   12645:                     $toplevel = "/$url";
                   12646:                 }
1.1085    raeburn  12647:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12648:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12649:                     $path = $1;
                   12650:                 } else {
                   12651:                     ($path) =
                   12652:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12653:                 }
1.1195    raeburn  12654:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12655:                     $fileloc = $toplevel;
                   12656:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12657:                     my ($udom,$uname,$fname) =
                   12658:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12659:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12660:                 } else {
                   12661:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12662:                 }
1.1071    raeburn  12663:                 $fileloc =~ s{^/}{};
                   12664:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12665:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12666:             }
1.987     raeburn  12667:         }
1.1123    raeburn  12668:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12669:         $udom = $cdom;
                   12670:         $uname = $cnum;
                   12671:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12672:         $toplevel = $url;
                   12673:         $path = $url;
                   12674:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12675:         $fileloc =~ s{^/}{};
1.987     raeburn  12676:     }
1.1249    damieng  12677:     
                   12678:     # parses the dependency paths to get some info
                   12679:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12680:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12681:     # (will be completed later)
                   12682:     # $mapping:
                   12683:     #   for external URLs: external URL -> external URL
                   12684:     #   for relative paths: clean path -> original path
                   12685:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12686:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12687:     foreach my $file (keys(%{$allfiles})) {
                   12688:         my $embed_file;
                   12689:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12690:             $embed_file = $1;
                   12691:         } else {
                   12692:             $embed_file = $file;
                   12693:         }
1.1158    raeburn  12694:         my ($absolutepath,$cleaned_file);
                   12695:         if ($embed_file =~ m{^\w+://}) {
                   12696:             $cleaned_file = $embed_file;
1.1147    raeburn  12697:             $newfiles{$cleaned_file} = 1;
                   12698:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12699:         } else {
1.1158    raeburn  12700:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12701:             if ($embed_file =~ m{^/}) {
                   12702:                 $absolutepath = $embed_file;
                   12703:             }
1.1147    raeburn  12704:             if ($cleaned_file =~ m{/}) {
                   12705:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12706:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12707:                 my $item = $fname;
                   12708:                 if ($path ne '') {
                   12709:                     $item = $path.'/'.$fname;
                   12710:                     $subdependencies{$path}{$fname} = 1;
                   12711:                 } else {
                   12712:                     $dependencies{$item} = 1;
                   12713:                 }
                   12714:                 if ($absolutepath) {
                   12715:                     $mapping{$item} = $absolutepath;
                   12716:                 } else {
                   12717:                     $mapping{$item} = $embed_file;
                   12718:                 }
                   12719:             } else {
                   12720:                 $dependencies{$embed_file} = 1;
                   12721:                 if ($absolutepath) {
1.1147    raeburn  12722:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12723:                 } else {
1.1147    raeburn  12724:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12725:                 }
                   12726:             }
1.984     raeburn  12727:         }
                   12728:     }
1.1249    damieng  12729:     
                   12730:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12731:     # and lists
                   12732:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12733:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12734:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12735:     #                                    the path had to be cleaned up
                   12736:     # $existing: hash clean path -> 1 if the file exists
                   12737:     # $numexisting: number of keys in $existing
                   12738:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12739:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12740:     #                                      dependency subdirectories that are
                   12741:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12742:     my $dirptr = 16384;
1.984     raeburn  12743:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12744:         $currsubfile{$path} = {};
1.1123    raeburn  12745:         if (($actionurl eq '/adm/portfolio') || 
                   12746:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12747:             my ($sublistref,$listerror) =
                   12748:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12749:             if (ref($sublistref) eq 'ARRAY') {
                   12750:                 foreach my $line (@{$sublistref}) {
                   12751:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12752:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12753:                 }
1.984     raeburn  12754:             }
1.987     raeburn  12755:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12756:             if (opendir(my $dir,$url.'/'.$path)) {
                   12757:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12758:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12759:             }
1.1084    raeburn  12760:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12761:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12762:                   ($args->{'context'} eq 'paste')) ||
                   12763:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12764:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12765:                 my $dir;
                   12766:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12767:                     $dir = $fileloc;
                   12768:                 } else {
                   12769:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12770:                 }
1.1071    raeburn  12771:                 if ($dir ne '') {
                   12772:                     my ($sublistref,$listerror) =
                   12773:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12774:                     if (ref($sublistref) eq 'ARRAY') {
                   12775:                         foreach my $line (@{$sublistref}) {
                   12776:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12777:                                 undef,$mtime)=split(/\&/,$line,12);
                   12778:                             unless (($testdir&$dirptr) ||
                   12779:                                     ($file_name =~ /^\.\.?$/)) {
                   12780:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12781:                             }
                   12782:                         }
                   12783:                     }
                   12784:                 }
1.984     raeburn  12785:             }
                   12786:         }
                   12787:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12788:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12789:                 my $item = $path.'/'.$file;
                   12790:                 unless ($mapping{$item} eq $item) {
                   12791:                     $pathchanges{$item} = 1;
                   12792:                 }
                   12793:                 $existing{$item} = 1;
                   12794:                 $numexisting ++;
                   12795:             } else {
                   12796:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12797:             }
                   12798:         }
1.1071    raeburn  12799:         if ($actionurl eq '/adm/dependencies') {
                   12800:             foreach my $path (keys(%currsubfile)) {
                   12801:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12802:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12803:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12804:                              next if (($rem ne '') &&
                   12805:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12806:                                        (ref($navmap) &&
                   12807:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12808:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12809:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12810:                              $unused{$path.'/'.$file} = 1; 
                   12811:                          }
                   12812:                     }
                   12813:                 }
                   12814:             }
                   12815:         }
1.984     raeburn  12816:     }
1.1249    damieng  12817:     
                   12818:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12819:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12820:     my %currfile;
1.1123    raeburn  12821:     if (($actionurl eq '/adm/portfolio') ||
                   12822:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12823:         my ($dirlistref,$listerror) =
                   12824:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12825:         if (ref($dirlistref) eq 'ARRAY') {
                   12826:             foreach my $line (@{$dirlistref}) {
                   12827:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12828:                 $currfile{$file_name} = 1;
                   12829:             }
1.984     raeburn  12830:         }
1.987     raeburn  12831:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12832:         if (opendir(my $dir,$url)) {
1.987     raeburn  12833:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12834:             map {$currfile{$_} = 1;} @dir_list;
                   12835:         }
1.1084    raeburn  12836:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12837:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12838:               ($args->{'context'} eq 'paste')) ||
                   12839:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12840:         if ($env{'request.course.id'} ne '') {
                   12841:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12842:             if ($dir ne '') {
                   12843:                 my ($dirlistref,$listerror) =
                   12844:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12845:                 if (ref($dirlistref) eq 'ARRAY') {
                   12846:                     foreach my $line (@{$dirlistref}) {
                   12847:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12848:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12849:                         unless (($testdir&$dirptr) ||
                   12850:                                 ($file_name =~ /^\.\.?$/)) {
                   12851:                             $currfile{$file_name} = [$size,$mtime];
                   12852:                         }
                   12853:                     }
                   12854:                 }
                   12855:             }
                   12856:         }
1.984     raeburn  12857:     }
1.1249    damieng  12858:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12859:     # are not in subdirectories, using $currfile
1.984     raeburn  12860:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12861:         if (exists($currfile{$file})) {
1.987     raeburn  12862:             unless ($mapping{$file} eq $file) {
                   12863:                 $pathchanges{$file} = 1;
                   12864:             }
                   12865:             $existing{$file} = 1;
                   12866:             $numexisting ++;
                   12867:         } else {
1.984     raeburn  12868:             $newfiles{$file} = 1;
                   12869:         }
                   12870:     }
1.1071    raeburn  12871:     foreach my $file (keys(%currfile)) {
                   12872:         unless (($file eq $filename) ||
                   12873:                 ($file eq $filename.'.bak') ||
                   12874:                 ($dependencies{$file})) {
1.1085    raeburn  12875:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12876:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12877:                     next if (($rem ne '') &&
                   12878:                              (($env{"httpref.$rem".$file} ne '') ||
                   12879:                               (ref($navmap) &&
                   12880:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12881:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12882:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12883:                 }
1.1085    raeburn  12884:             }
1.1071    raeburn  12885:             $unused{$file} = 1;
                   12886:         }
                   12887:     }
1.1249    damieng  12888:     
                   12889:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12890:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12891:         ($args->{'context'} eq 'paste')) {
                   12892:         $counter = scalar(keys(%existing));
                   12893:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12894:         return ($output,$counter,$numpathchg,\%existing);
                   12895:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12896:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12897:         $counter = scalar(keys(%existing));
                   12898:         $numpathchg = scalar(keys(%pathchanges));
                   12899:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12900:     }
1.1249    damieng  12901:     
                   12902:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12903:     
                   12904:     # $upload_output: missing dependencies (with upload form)
                   12905:     # $modify_output: uploaded dependencies (in use)
                   12906:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12907:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12908:         if ($actionurl eq '/adm/dependencies') {
                   12909:             next if ($embed_file =~ m{^\w+://});
                   12910:         }
1.660     raeburn  12911:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12912:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12913:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12914:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12915:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12916:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12917:         }
1.1123    raeburn  12918:         $upload_output .= '</td>';
1.1071    raeburn  12919:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12920:             $upload_output.='<td align="right">'.
                   12921:                             '<span class="LC_info LC_fontsize_medium">'.
                   12922:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12923:             $numremref++;
1.660     raeburn  12924:         } elsif ($args->{'error_on_invalid_names'}
                   12925:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12926:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12927:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12928:             $numinvalid++;
1.660     raeburn  12929:         } else {
1.1123    raeburn  12930:             $upload_output .= '<td>'.
                   12931:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12932:                                                      $embed_file,\%mapping,
1.1071    raeburn  12933:                                                      $allfiles,$codebase,'upload');
                   12934:             $counter ++;
                   12935:             $numnew ++;
1.987     raeburn  12936:         }
                   12937:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12938:     }
                   12939:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12940:         if ($actionurl eq '/adm/dependencies') {
                   12941:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12942:             $modify_output .= &start_data_table_row().
                   12943:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12944:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12945:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12946:                               '<td>'.$size.'</td>'.
                   12947:                               '<td>'.$mtime.'</td>'.
                   12948:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12949:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12950:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12951:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12952:                               &embedded_file_element('upload_embedded',$counter,
                   12953:                                                      $embed_file,\%mapping,
                   12954:                                                      $allfiles,$codebase,'modify').
                   12955:                               '</div></td>'.
                   12956:                               &end_data_table_row()."\n";
                   12957:             $counter ++;
                   12958:         } else {
                   12959:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12960:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12961:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12962:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12963:                               &Apache::loncommon::end_data_table_row()."\n";
                   12964:         }
                   12965:     }
                   12966:     my $delidx = $counter;
                   12967:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12968:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12969:         $delete_output .= &start_data_table_row().
                   12970:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12971:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12972:                           '<td>'.$size.'</td>'.
                   12973:                           '<td>'.$mtime.'</td>'.
                   12974:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12975:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12976:                           &embedded_file_element('upload_embedded',$delidx,
                   12977:                                                  $oldfile,\%mapping,$allfiles,
                   12978:                                                  $codebase,'delete').'</td>'.
                   12979:                           &end_data_table_row()."\n"; 
                   12980:         $numunused ++;
                   12981:         $delidx ++;
1.987     raeburn  12982:     }
                   12983:     if ($upload_output) {
                   12984:         $upload_output = &start_data_table().
                   12985:                          $upload_output.
                   12986:                          &end_data_table()."\n";
                   12987:     }
1.1071    raeburn  12988:     if ($modify_output) {
                   12989:         $modify_output = &start_data_table().
                   12990:                          &start_data_table_header_row().
                   12991:                          '<th>'.&mt('File').'</th>'.
                   12992:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12993:                          '<th>'.&mt('Modified').'</th>'.
                   12994:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12995:                          &end_data_table_header_row().
                   12996:                          $modify_output.
                   12997:                          &end_data_table()."\n";
                   12998:     }
                   12999:     if ($delete_output) {
                   13000:         $delete_output = &start_data_table().
                   13001:                          &start_data_table_header_row().
                   13002:                          '<th>'.&mt('File').'</th>'.
                   13003:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13004:                          '<th>'.&mt('Modified').'</th>'.
                   13005:                          '<th>'.&mt('Delete?').'</th>'.
                   13006:                          &end_data_table_header_row().
                   13007:                          $delete_output.
                   13008:                          &end_data_table()."\n";
                   13009:     }
1.987     raeburn  13010:     my $applies = 0;
                   13011:     if ($numremref) {
                   13012:         $applies ++;
                   13013:     }
                   13014:     if ($numinvalid) {
                   13015:         $applies ++;
                   13016:     }
                   13017:     if ($numexisting) {
                   13018:         $applies ++;
                   13019:     }
1.1071    raeburn  13020:     if ($counter || $numunused) {
1.987     raeburn  13021:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13022:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13023:                   $state.'<h3>'.$heading.'</h3>'; 
                   13024:         if ($actionurl eq '/adm/dependencies') {
                   13025:             if ($numnew) {
                   13026:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13027:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13028:                            $upload_output.'<br />'."\n";
                   13029:             }
                   13030:             if ($numexisting) {
                   13031:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13032:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13033:                            $modify_output.'<br />'."\n";
                   13034:                            $buttontext = &mt('Save changes');
                   13035:             }
                   13036:             if ($numunused) {
                   13037:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13038:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13039:                            $delete_output.'<br />'."\n";
                   13040:                            $buttontext = &mt('Save changes');
                   13041:             }
                   13042:         } else {
                   13043:             $output .= $upload_output.'<br />'."\n";
                   13044:         }
                   13045:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13046:                    $counter.'" />'."\n";
                   13047:         if ($actionurl eq '/adm/dependencies') { 
                   13048:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13049:                        $numnew.'" />'."\n";
                   13050:         } elsif ($actionurl eq '') {
1.987     raeburn  13051:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13052:         }
                   13053:     } elsif ($applies) {
                   13054:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13055:         if ($applies > 1) {
                   13056:             $output .=  
1.1123    raeburn  13057:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13058:             if ($numremref) {
                   13059:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13060:             }
                   13061:             if ($numinvalid) {
                   13062:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13063:             }
                   13064:             if ($numexisting) {
                   13065:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13066:             }
                   13067:             $output .= '</ul><br />';
                   13068:         } elsif ($numremref) {
                   13069:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13070:         } elsif ($numinvalid) {
                   13071:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13072:         } elsif ($numexisting) {
                   13073:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13074:         }
                   13075:         $output .= $upload_output.'<br />';
                   13076:     }
                   13077:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13078:     $chgcount = $counter;
1.987     raeburn  13079:     if (keys(%pathchanges) > 0) {
                   13080:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13081:             if ($counter) {
1.987     raeburn  13082:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13083:                                                   $embed_file,\%mapping,
1.1071    raeburn  13084:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13085:             } else {
                   13086:                 $pathchange_output .= 
                   13087:                     &start_data_table_row().
                   13088:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13089:                     $chgcount.'" checked="checked" /></td>'.
                   13090:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13091:                     '<td>'.$embed_file.
                   13092:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13093:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13094:                     '</td>'.&end_data_table_row();
1.660     raeburn  13095:             }
1.987     raeburn  13096:             $numpathchg ++;
                   13097:             $chgcount ++;
1.660     raeburn  13098:         }
                   13099:     }
1.1127    raeburn  13100:     if (($counter) || ($numunused)) {
1.987     raeburn  13101:         if ($numpathchg) {
                   13102:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13103:                        $numpathchg.'" />'."\n";
                   13104:         }
                   13105:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13106:             ($actionurl eq '/adm/imsimport')) {
                   13107:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13108:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13109:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13110:         } elsif ($actionurl eq '/adm/dependencies') {
                   13111:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13112:         }
1.1123    raeburn  13113:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13114:     } elsif ($numpathchg) {
                   13115:         my %pathchange = ();
                   13116:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13117:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13118:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13119:         }
1.987     raeburn  13120:     }
1.1071    raeburn  13121:     return ($output,$counter,$numpathchg);
1.987     raeburn  13122: }
                   13123: 
1.1147    raeburn  13124: =pod
                   13125: 
                   13126: =item * clean_path($name)
                   13127: 
                   13128: Performs clean-up of directories, subdirectories and filename in an
                   13129: embedded object, referenced in an HTML file which is being uploaded
                   13130: to a course or portfolio, where 
                   13131: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13132: checked.
                   13133: 
                   13134: Clean-up is similar to replacements in lonnet::clean_filename()
                   13135: except each / between sub-directory and next level is preserved.
                   13136: 
                   13137: =cut
                   13138: 
                   13139: sub clean_path {
                   13140:     my ($embed_file) = @_;
                   13141:     $embed_file =~s{^/+}{};
                   13142:     my @contents;
                   13143:     if ($embed_file =~ m{/}) {
                   13144:         @contents = split(/\//,$embed_file);
                   13145:     } else {
                   13146:         @contents = ($embed_file);
                   13147:     }
                   13148:     my $lastidx = scalar(@contents)-1;
                   13149:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13150:         $contents[$i]=~s{\\}{/}g;
                   13151:         $contents[$i]=~s/\s+/\_/g;
                   13152:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13153:         if ($i == $lastidx) {
                   13154:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13155:         }
                   13156:     }
                   13157:     if ($lastidx > 0) {
                   13158:         return join('/',@contents);
                   13159:     } else {
                   13160:         return $contents[0];
                   13161:     }
                   13162: }
                   13163: 
1.987     raeburn  13164: sub embedded_file_element {
1.1071    raeburn  13165:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13166:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13167:                    (ref($codebase) eq 'HASH'));
                   13168:     my $output;
1.1071    raeburn  13169:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13170:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13171:     }
                   13172:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13173:                &escape($embed_file).'" />';
                   13174:     unless (($context eq 'upload_embedded') && 
                   13175:             ($mapping->{$embed_file} eq $embed_file)) {
                   13176:         $output .='
                   13177:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13178:     }
                   13179:     my $attrib;
                   13180:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13181:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13182:     }
                   13183:     $output .=
                   13184:         "\n\t\t".
                   13185:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13186:         $attrib.'" />';
                   13187:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13188:         $output .=
                   13189:             "\n\t\t".
                   13190:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13191:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13192:     }
1.987     raeburn  13193:     return $output;
1.660     raeburn  13194: }
                   13195: 
1.1071    raeburn  13196: sub get_dependency_details {
                   13197:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13198:     my ($size,$mtime,$showsize,$showmtime);
                   13199:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13200:         if ($embed_file =~ m{/}) {
                   13201:             my ($path,$fname) = split(/\//,$embed_file);
                   13202:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13203:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13204:             }
                   13205:         } else {
                   13206:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13207:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13208:             }
                   13209:         }
                   13210:         $showsize = $size/1024.0;
                   13211:         $showsize = sprintf("%.1f",$showsize);
                   13212:         if ($mtime > 0) {
                   13213:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13214:         }
                   13215:     }
                   13216:     return ($showsize,$showmtime);
                   13217: }
                   13218: 
                   13219: sub ask_embedded_js {
                   13220:     return <<"END";
                   13221: <script type="text/javascript"">
                   13222: // <![CDATA[
                   13223: function toggleBrowse(counter) {
                   13224:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13225:     var fileid = document.getElementById('embedded_item_'+counter);
                   13226:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13227:     if (chkboxid.checked == true) {
                   13228:         uploaddivid.style.display='block';
                   13229:     } else {
                   13230:         uploaddivid.style.display='none';
                   13231:         fileid.value = '';
                   13232:     }
                   13233: }
                   13234: // ]]>
                   13235: </script>
                   13236: 
                   13237: END
                   13238: }
                   13239: 
1.661     raeburn  13240: sub upload_embedded {
                   13241:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13242:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13243:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13244:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13245:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13246:         my $orig_uploaded_filename =
                   13247:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13248:         foreach my $type ('orig','ref','attrib','codebase') {
                   13249:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13250:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13251:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13252:             }
                   13253:         }
1.661     raeburn  13254:         my ($path,$fname) =
                   13255:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13256:         # no path, whole string is fname
                   13257:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13258:         $fname = &Apache::lonnet::clean_filename($fname);
                   13259:         # See if there is anything left
                   13260:         next if ($fname eq '');
                   13261: 
                   13262:         # Check if file already exists as a file or directory.
                   13263:         my ($state,$msg);
                   13264:         if ($context eq 'portfolio') {
                   13265:             my $port_path = $dirpath;
                   13266:             if ($group ne '') {
                   13267:                 $port_path = "groups/$group/$port_path";
                   13268:             }
1.987     raeburn  13269:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13270:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13271:                                               $dir_root,$port_path,$disk_quota,
                   13272:                                               $current_disk_usage,$uname,$udom);
                   13273:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13274:                 || $state eq 'file_locked') {
1.661     raeburn  13275:                 $output .= $msg;
                   13276:                 next;
                   13277:             }
                   13278:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13279:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13280:             if ($state eq 'exists') {
                   13281:                 $output .= $msg;
                   13282:                 next;
                   13283:             }
                   13284:         }
                   13285:         # Check if extension is valid
                   13286:         if (($fname =~ /\.(\w+)$/) &&
                   13287:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13288:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13289:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13290:             next;
                   13291:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13292:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13293:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13294:             next;
                   13295:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13296:             $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  13297:             next;
                   13298:         }
                   13299:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13300:         my $subdir = $path;
                   13301:         $subdir =~ s{/+$}{};
1.661     raeburn  13302:         if ($context eq 'portfolio') {
1.984     raeburn  13303:             my $result;
                   13304:             if ($state eq 'existingfile') {
                   13305:                 $result=
                   13306:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13307:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13308:             } else {
1.984     raeburn  13309:                 $result=
                   13310:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13311:                                                     $dirpath.
1.1123    raeburn  13312:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13313:                 if ($result !~ m|^/uploaded/|) {
                   13314:                     $output .= '<span class="LC_error">'
                   13315:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13316:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13317:                                .'</span><br />';
                   13318:                     next;
                   13319:                 } else {
1.987     raeburn  13320:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13321:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13322:                 }
1.661     raeburn  13323:             }
1.1123    raeburn  13324:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13325:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13326:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13327:             my $result =
1.1126    raeburn  13328:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13329:             if ($result !~ m|^/uploaded/|) {
                   13330:                 $output .= '<span class="LC_error">'
                   13331:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13332:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13333:                            .'</span><br />';
                   13334:                     next;
                   13335:             } else {
                   13336:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13337:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13338:                 if ($context eq 'syllabus') {
                   13339:                     &Apache::lonnet::make_public_indefinitely($result);
                   13340:                 }
1.987     raeburn  13341:             }
1.661     raeburn  13342:         } else {
                   13343: # Save the file
                   13344:             my $target = $env{'form.embedded_item_'.$i};
                   13345:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13346:             my $dest = $fullpath.$fname;
                   13347:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13348:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13349:             my $count;
                   13350:             my $filepath = $dir_root;
1.1027    raeburn  13351:             foreach my $subdir (@parts) {
                   13352:                 $filepath .= "/$subdir";
                   13353:                 if (!-e $filepath) {
1.661     raeburn  13354:                     mkdir($filepath,0770);
                   13355:                 }
                   13356:             }
                   13357:             my $fh;
                   13358:             if (!open($fh,'>'.$dest)) {
                   13359:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13360:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13361:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13362:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13363:                            '</span><br />';
                   13364:             } else {
                   13365:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13366:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13367:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13368:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13369:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13370:                               '</span><br />';
                   13371:                 } else {
1.987     raeburn  13372:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13373:                                $url.'</span>').'<br />';
                   13374:                     unless ($context eq 'testbank') {
                   13375:                         $footer .= &mt('View embedded file: [_1]',
                   13376:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13377:                     }
                   13378:                 }
                   13379:                 close($fh);
                   13380:             }
                   13381:         }
                   13382:         if ($env{'form.embedded_ref_'.$i}) {
                   13383:             $pathchange{$i} = 1;
                   13384:         }
                   13385:     }
                   13386:     if ($output) {
                   13387:         $output = '<p>'.$output.'</p>';
                   13388:     }
                   13389:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13390:     $returnflag = 'ok';
1.1071    raeburn  13391:     my $numpathchgs = scalar(keys(%pathchange));
                   13392:     if ($numpathchgs > 0) {
1.987     raeburn  13393:         if ($context eq 'portfolio') {
                   13394:             $output .= '<p>'.&mt('or').'</p>';
                   13395:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13396:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13397:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13398:             $returnflag = 'modify_orightml';
                   13399:         }
                   13400:     }
1.1071    raeburn  13401:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13402: }
                   13403: 
                   13404: sub modify_html_form {
                   13405:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13406:     my $end = 0;
                   13407:     my $modifyform;
                   13408:     if ($context eq 'upload_embedded') {
                   13409:         return unless (ref($pathchange) eq 'HASH');
                   13410:         if ($env{'form.number_embedded_items'}) {
                   13411:             $end += $env{'form.number_embedded_items'};
                   13412:         }
                   13413:         if ($env{'form.number_pathchange_items'}) {
                   13414:             $end += $env{'form.number_pathchange_items'};
                   13415:         }
                   13416:         if ($end) {
                   13417:             for (my $i=0; $i<$end; $i++) {
                   13418:                 if ($i < $env{'form.number_embedded_items'}) {
                   13419:                     next unless($pathchange->{$i});
                   13420:                 }
                   13421:                 $modifyform .=
                   13422:                     &start_data_table_row().
                   13423:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13424:                     'checked="checked" /></td>'.
                   13425:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13426:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13427:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13428:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13429:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13430:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13431:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13432:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13433:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13434:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13435:                     &end_data_table_row();
1.1071    raeburn  13436:             }
1.987     raeburn  13437:         }
                   13438:     } else {
                   13439:         $modifyform = $pathchgtable;
                   13440:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13441:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13442:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13443:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13444:         }
                   13445:     }
                   13446:     if ($modifyform) {
1.1071    raeburn  13447:         if ($actionurl eq '/adm/dependencies') {
                   13448:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13449:         }
1.987     raeburn  13450:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13451:                '<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".
                   13452:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13453:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13454:                '</ol></p>'."\n".'<p>'.
                   13455:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13456:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13457:                &start_data_table()."\n".
                   13458:                &start_data_table_header_row().
                   13459:                '<th>'.&mt('Change?').'</th>'.
                   13460:                '<th>'.&mt('Current reference').'</th>'.
                   13461:                '<th>'.&mt('Required reference').'</th>'.
                   13462:                &end_data_table_header_row()."\n".
                   13463:                $modifyform.
                   13464:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13465:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13466:                '</form>'."\n";
                   13467:     }
                   13468:     return;
                   13469: }
                   13470: 
                   13471: sub modify_html_refs {
1.1123    raeburn  13472:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13473:     my $container;
                   13474:     if ($context eq 'portfolio') {
                   13475:         $container = $env{'form.container'};
                   13476:     } elsif ($context eq 'coursedoc') {
                   13477:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13478:     } elsif ($context eq 'manage_dependencies') {
                   13479:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13480:         $container = "/$container";
1.1123    raeburn  13481:     } elsif ($context eq 'syllabus') {
                   13482:         $container = $url;
1.987     raeburn  13483:     } else {
1.1027    raeburn  13484:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13485:     }
                   13486:     my (%allfiles,%codebase,$output,$content);
                   13487:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13488:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13489:         if (wantarray) {
                   13490:             return ('',0,0); 
                   13491:         } else {
                   13492:             return;
                   13493:         }
                   13494:     }
                   13495:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13496:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13497:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13498:             if (wantarray) {
                   13499:                 return ('',0,0);
                   13500:             } else {
                   13501:                 return;
                   13502:             }
                   13503:         } 
1.987     raeburn  13504:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13505:         if ($content eq '-1') {
                   13506:             if (wantarray) {
                   13507:                 return ('',0,0);
                   13508:             } else {
                   13509:                 return;
                   13510:             }
                   13511:         }
1.987     raeburn  13512:     } else {
1.1071    raeburn  13513:         unless ($container =~ /^\Q$dir_root\E/) {
                   13514:             if (wantarray) {
                   13515:                 return ('',0,0);
                   13516:             } else {
                   13517:                 return;
                   13518:             }
                   13519:         } 
1.1317    raeburn  13520:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13521:             $content = join('', <$fh>);
                   13522:             close($fh);
                   13523:         } else {
1.1071    raeburn  13524:             if (wantarray) {
                   13525:                 return ('',0,0);
                   13526:             } else {
                   13527:                 return;
                   13528:             }
1.987     raeburn  13529:         }
                   13530:     }
                   13531:     my ($count,$codebasecount) = (0,0);
                   13532:     my $mm = new File::MMagic;
                   13533:     my $mime_type = $mm->checktype_contents($content);
                   13534:     if ($mime_type eq 'text/html') {
                   13535:         my $parse_result = 
                   13536:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13537:                                                     \%codebase,\$content);
                   13538:         if ($parse_result eq 'ok') {
                   13539:             foreach my $i (@changes) {
                   13540:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13541:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13542:                 if ($allfiles{$ref}) {
                   13543:                     my $newname =  $orig;
                   13544:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13545:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13546:                     if ($attrib_regexp =~ /:/) {
                   13547:                         $attrib_regexp =~ s/\:/|/g;
                   13548:                     }
                   13549:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13550:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13551:                         $count += $numchg;
1.1123    raeburn  13552:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13553:                         delete($allfiles{$ref});
1.987     raeburn  13554:                     }
                   13555:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13556:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13557:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13558:                         $codebasecount ++;
                   13559:                     }
                   13560:                 }
                   13561:             }
1.1123    raeburn  13562:             my $skiprewrites;
1.987     raeburn  13563:             if ($count || $codebasecount) {
                   13564:                 my $saveresult;
1.1071    raeburn  13565:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13566:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13567:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13568:                     if ($url eq $container) {
                   13569:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13570:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13571:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13572:                                             $fname.'</span>').'</p>';
1.987     raeburn  13573:                     } else {
                   13574:                          $output = '<p class="LC_error">'.
                   13575:                                    &mt('Error: update failed for: [_1].',
                   13576:                                    '<span class="LC_filename">'.
                   13577:                                    $container.'</span>').'</p>';
                   13578:                     }
1.1123    raeburn  13579:                     if ($context eq 'syllabus') {
                   13580:                         unless ($saveresult eq 'ok') {
                   13581:                             $skiprewrites = 1;
                   13582:                         }
                   13583:                     }
1.987     raeburn  13584:                 } else {
1.1317    raeburn  13585:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13586:                         print $fh $content;
                   13587:                         close($fh);
                   13588:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13589:                                   $count,'<span class="LC_filename">'.
                   13590:                                   $container.'</span>').'</p>';
1.661     raeburn  13591:                     } else {
1.987     raeburn  13592:                          $output = '<p class="LC_error">'.
                   13593:                                    &mt('Error: could not update [_1].',
                   13594:                                    '<span class="LC_filename">'.
                   13595:                                    $container.'</span>').'</p>';
1.661     raeburn  13596:                     }
                   13597:                 }
                   13598:             }
1.1123    raeburn  13599:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13600:                 my ($actionurl,$state);
                   13601:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13602:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13603:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13604:                                               \%codebase,
                   13605:                                               {'context' => 'rewrites',
                   13606:                                                'ignore_remote_references' => 1,});
                   13607:                 if (ref($mapping) eq 'HASH') {
                   13608:                     my $rewrites = 0;
                   13609:                     foreach my $key (keys(%{$mapping})) {
                   13610:                         next if ($key =~ m{^https?://});
                   13611:                         my $ref = $mapping->{$key};
                   13612:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13613:                         my $attrib;
                   13614:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13615:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13616:                         }
                   13617:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13618:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13619:                             $rewrites += $numchg;
                   13620:                         }
                   13621:                     }
                   13622:                     if ($rewrites) {
                   13623:                         my $saveresult; 
                   13624:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13625:                         if ($url eq $container) {
                   13626:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13627:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13628:                                             $count,'<span class="LC_filename">'.
                   13629:                                             $fname.'</span>').'</p>';
                   13630:                         } else {
                   13631:                             $output .= '<p class="LC_error">'.
                   13632:                                        &mt('Error: could not update links in [_1].',
                   13633:                                        '<span class="LC_filename">'.
                   13634:                                        $container.'</span>').'</p>';
                   13635: 
                   13636:                         }
                   13637:                     }
                   13638:                 }
                   13639:             }
1.987     raeburn  13640:         } else {
                   13641:             &logthis('Failed to parse '.$container.
                   13642:                      ' to modify references: '.$parse_result);
1.661     raeburn  13643:         }
                   13644:     }
1.1071    raeburn  13645:     if (wantarray) {
                   13646:         return ($output,$count,$codebasecount);
                   13647:     } else {
                   13648:         return $output;
                   13649:     }
1.661     raeburn  13650: }
                   13651: 
                   13652: sub check_for_existing {
                   13653:     my ($path,$fname,$element) = @_;
                   13654:     my ($state,$msg);
                   13655:     if (-d $path.'/'.$fname) {
                   13656:         $state = 'exists';
                   13657:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13658:     } elsif (-e $path.'/'.$fname) {
                   13659:         $state = 'exists';
                   13660:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13661:     }
                   13662:     if ($state eq 'exists') {
                   13663:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13664:     }
                   13665:     return ($state,$msg);
                   13666: }
                   13667: 
                   13668: sub check_for_upload {
                   13669:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13670:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13671:     my $filesize = length($env{'form.'.$element});
                   13672:     if (!$filesize) {
                   13673:         my $msg = '<span class="LC_error">'.
                   13674:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13675:                       '<span class="LC_filename">'.$fname.'</span>',
                   13676:                       $filesize).'<br />'.
1.1007    raeburn  13677:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13678:                   '</span>';
                   13679:         return ('zero_bytes',$msg);
                   13680:     }
                   13681:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13682:     my $getpropath = 1;
1.1021    raeburn  13683:     my ($dirlistref,$listerror) =
                   13684:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13685:     my $found_file = 0;
                   13686:     my $locked_file = 0;
1.991     raeburn  13687:     my @lockers;
                   13688:     my $navmap;
                   13689:     if ($env{'request.course.id'}) {
                   13690:         $navmap = Apache::lonnavmaps::navmap->new();
                   13691:     }
1.1021    raeburn  13692:     if (ref($dirlistref) eq 'ARRAY') {
                   13693:         foreach my $line (@{$dirlistref}) {
                   13694:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13695:             if ($file_name eq $fname){
                   13696:                 $file_name = $path.$file_name;
                   13697:                 if ($group ne '') {
                   13698:                     $file_name = $group.$file_name;
                   13699:                 }
                   13700:                 $found_file = 1;
                   13701:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13702:                     foreach my $lock (@lockers) {
                   13703:                         if (ref($lock) eq 'ARRAY') {
                   13704:                             my ($symb,$crsid) = @{$lock};
                   13705:                             if ($crsid eq $env{'request.course.id'}) {
                   13706:                                 if (ref($navmap)) {
                   13707:                                     my $res = $navmap->getBySymb($symb);
                   13708:                                     foreach my $part (@{$res->parts()}) { 
                   13709:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13710:                                         unless (($slot_status == $res->RESERVED) ||
                   13711:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13712:                                             $locked_file = 1;
                   13713:                                         }
1.991     raeburn  13714:                                     }
1.1021    raeburn  13715:                                 } else {
                   13716:                                     $locked_file = 1;
1.991     raeburn  13717:                                 }
                   13718:                             } else {
                   13719:                                 $locked_file = 1;
                   13720:                             }
                   13721:                         }
1.1021    raeburn  13722:                    }
                   13723:                 } else {
                   13724:                     my @info = split(/\&/,$rest);
                   13725:                     my $currsize = $info[6]/1000;
                   13726:                     if ($currsize < $filesize) {
                   13727:                         my $extra = $filesize - $currsize;
                   13728:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13729:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13730:                                       &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   13731:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13732:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13733:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13734:                             return ('will_exceed_quota',$msg);
                   13735:                         }
1.984     raeburn  13736:                     }
                   13737:                 }
1.661     raeburn  13738:             }
                   13739:         }
                   13740:     }
                   13741:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13742:         my $msg = '<p class="LC_warning">'.
                   13743:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13744:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13745:         return ('will_exceed_quota',$msg);
                   13746:     } elsif ($found_file) {
                   13747:         if ($locked_file) {
1.1179    bisitz   13748:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13749:             $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   13750:             $msg .= '</p>';
1.661     raeburn  13751:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13752:             return ('file_locked',$msg);
                   13753:         } else {
1.1179    bisitz   13754:             my $msg = '<p class="LC_error">';
1.984     raeburn  13755:             $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   13756:             $msg .= '</p>';
1.984     raeburn  13757:             return ('existingfile',$msg);
1.661     raeburn  13758:         }
                   13759:     }
                   13760: }
                   13761: 
1.987     raeburn  13762: sub check_for_traversal {
                   13763:     my ($path,$url,$toplevel) = @_;
                   13764:     my @parts=split(/\//,$path);
                   13765:     my $cleanpath;
                   13766:     my $fullpath = $url;
                   13767:     for (my $i=0;$i<@parts;$i++) {
                   13768:         next if ($parts[$i] eq '.');
                   13769:         if ($parts[$i] eq '..') {
                   13770:             $fullpath =~ s{([^/]+/)$}{};
                   13771:         } else {
                   13772:             $fullpath .= $parts[$i].'/';
                   13773:         }
                   13774:     }
                   13775:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13776:         $cleanpath = $1;
                   13777:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13778:         my $curr_toprel = $1;
                   13779:         my @parts = split(/\//,$curr_toprel);
                   13780:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13781:         my @urlparts = split(/\//,$url_toprel);
                   13782:         my $doubledots;
                   13783:         my $startdiff = -1;
                   13784:         for (my $i=0; $i<@urlparts; $i++) {
                   13785:             if ($startdiff == -1) {
                   13786:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13787:                     $startdiff = $i;
                   13788:                     $doubledots .= '../';
                   13789:                 }
                   13790:             } else {
                   13791:                 $doubledots .= '../';
                   13792:             }
                   13793:         }
                   13794:         if ($startdiff > -1) {
                   13795:             $cleanpath = $doubledots;
                   13796:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13797:                 $cleanpath .= $parts[$i].'/';
                   13798:             }
                   13799:         }
                   13800:     }
                   13801:     $cleanpath =~ s{(/)$}{};
                   13802:     return $cleanpath;
                   13803: }
1.31      albertel 13804: 
1.1053    raeburn  13805: sub is_archive_file {
                   13806:     my ($mimetype) = @_;
                   13807:     if (($mimetype eq 'application/octet-stream') ||
                   13808:         ($mimetype eq 'application/x-stuffit') ||
                   13809:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13810:         return 1;
                   13811:     }
                   13812:     return;
                   13813: }
                   13814: 
                   13815: sub decompress_form {
1.1065    raeburn  13816:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13817:     my %lt = &Apache::lonlocal::texthash (
                   13818:         this => 'This file is an archive file.',
1.1067    raeburn  13819:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13820:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13821:         youm => 'You may wish to extract its contents.',
                   13822:         extr => 'Extract contents',
1.1067    raeburn  13823:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13824:         proa => 'Process automatically?',
1.1053    raeburn  13825:         yes  => 'Yes',
                   13826:         no   => 'No',
1.1067    raeburn  13827:         fold => 'Title for folder containing movie',
                   13828:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13829:     );
1.1065    raeburn  13830:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13831:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13832:     my $info = &list_archive_contents($fileloc,\@paths);
                   13833:     if (@paths) {
                   13834:         foreach my $path (@paths) {
                   13835:             $path =~ s{^/}{};
1.1067    raeburn  13836:             if ($path =~ m{^([^/]+)/$}) {
                   13837:                 $topdir = $1;
                   13838:             }
1.1065    raeburn  13839:             if ($path =~ m{^([^/]+)/}) {
                   13840:                 $toplevel{$1} = $path;
                   13841:             } else {
                   13842:                 $toplevel{$path} = $path;
                   13843:             }
                   13844:         }
                   13845:     }
1.1067    raeburn  13846:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13847:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13848:                         "$topdir/media/",
                   13849:                         "$topdir/media/$topdir.mp4",
                   13850:                         "$topdir/media/FirstFrame.png",
                   13851:                         "$topdir/media/player.swf",
                   13852:                         "$topdir/media/swfobject.js",
                   13853:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13854:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13855:                          "$topdir/$topdir.mp4",
                   13856:                          "$topdir/$topdir\_config.xml",
                   13857:                          "$topdir/$topdir\_controller.swf",
                   13858:                          "$topdir/$topdir\_embed.css",
                   13859:                          "$topdir/$topdir\_First_Frame.png",
                   13860:                          "$topdir/$topdir\_player.html",
                   13861:                          "$topdir/$topdir\_Thumbnails.png",
                   13862:                          "$topdir/playerProductInstall.swf",
                   13863:                          "$topdir/scripts/",
                   13864:                          "$topdir/scripts/config_xml.js",
                   13865:                          "$topdir/scripts/handlebars.js",
                   13866:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13867:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13868:                          "$topdir/scripts/modernizr.js",
                   13869:                          "$topdir/scripts/player-min.js",
                   13870:                          "$topdir/scripts/swfobject.js",
                   13871:                          "$topdir/skins/",
                   13872:                          "$topdir/skins/configuration_express.xml",
                   13873:                          "$topdir/skins/express_show/",
                   13874:                          "$topdir/skins/express_show/player-min.css",
                   13875:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13876:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13877:                          "$topdir/$topdir.mp4",
                   13878:                          "$topdir/$topdir\_config.xml",
                   13879:                          "$topdir/$topdir\_controller.swf",
                   13880:                          "$topdir/$topdir\_embed.css",
                   13881:                          "$topdir/$topdir\_First_Frame.png",
                   13882:                          "$topdir/$topdir\_player.html",
                   13883:                          "$topdir/$topdir\_Thumbnails.png",
                   13884:                          "$topdir/playerProductInstall.swf",
                   13885:                          "$topdir/scripts/",
                   13886:                          "$topdir/scripts/config_xml.js",
                   13887:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13888:                          "$topdir/skins/",
                   13889:                          "$topdir/skins/configuration_express.xml",
                   13890:                          "$topdir/skins/express_show/",
                   13891:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13892:                          "$topdir/skins/express_show/spritesheet.png",
                   13893:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13894:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13895:         if (@diffs == 0) {
1.1164    raeburn  13896:             $is_camtasia = 6;
                   13897:         } else {
1.1197    raeburn  13898:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13899:             if (@diffs == 0) {
                   13900:                 $is_camtasia = 8;
1.1197    raeburn  13901:             } else {
                   13902:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13903:                 if (@diffs == 0) {
                   13904:                     $is_camtasia = 8;
                   13905:                 }
1.1164    raeburn  13906:             }
1.1067    raeburn  13907:         }
                   13908:     }
                   13909:     my $output;
                   13910:     if ($is_camtasia) {
                   13911:         $output = <<"ENDCAM";
                   13912: <script type="text/javascript" language="Javascript">
                   13913: // <![CDATA[
                   13914: 
                   13915: function camtasiaToggle() {
                   13916:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13917:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13918:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13919:                 document.getElementById('camtasia_titles').style.display='block';
                   13920:             } else {
                   13921:                 document.getElementById('camtasia_titles').style.display='none';
                   13922:             }
                   13923:         }
                   13924:     }
                   13925:     return;
                   13926: }
                   13927: 
                   13928: // ]]>
                   13929: </script>
                   13930: <p>$lt{'camt'}</p>
                   13931: ENDCAM
1.1065    raeburn  13932:     } else {
1.1067    raeburn  13933:         $output = '<p>'.$lt{'this'};
                   13934:         if ($info eq '') {
                   13935:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13936:         } else {
                   13937:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13938:                        '<div><pre>'.$info.'</pre></div>';
                   13939:         }
1.1065    raeburn  13940:     }
1.1067    raeburn  13941:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13942:     my $duplicates;
                   13943:     my $num = 0;
                   13944:     if (ref($dirlist) eq 'ARRAY') {
                   13945:         foreach my $item (@{$dirlist}) {
                   13946:             if (ref($item) eq 'ARRAY') {
                   13947:                 if (exists($toplevel{$item->[0]})) {
                   13948:                     $duplicates .= 
                   13949:                         &start_data_table_row().
                   13950:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13951:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13952:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13953:                         'value="1" />'.&mt('Yes').'</label>'.
                   13954:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13955:                         '<td>'.$item->[0].'</td>';
                   13956:                     if ($item->[2]) {
                   13957:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13958:                     } else {
                   13959:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13960:                     }
                   13961:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13962:                                    '<td>'.
                   13963:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13964:                                    '</td>'.
                   13965:                                    &end_data_table_row();
                   13966:                     $num ++;
                   13967:                 }
                   13968:             }
                   13969:         }
                   13970:     }
                   13971:     my $itemcount;
                   13972:     if (@paths > 0) {
                   13973:         $itemcount = scalar(@paths);
                   13974:     } else {
                   13975:         $itemcount = 1;
                   13976:     }
1.1067    raeburn  13977:     if ($is_camtasia) {
                   13978:         $output .= $lt{'auto'}.'<br />'.
                   13979:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13980:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13981:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13982:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13983:                    $lt{'no'}.'</label></span><br />'.
                   13984:                    '<div id="camtasia_titles" style="display:block">'.
                   13985:                    &Apache::lonhtmlcommon::start_pick_box().
                   13986:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13987:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13988:                    &Apache::lonhtmlcommon::row_closure().
                   13989:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13990:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13991:                    &Apache::lonhtmlcommon::row_closure(1).
                   13992:                    &Apache::lonhtmlcommon::end_pick_box().
                   13993:                    '</div>';
                   13994:     }
1.1065    raeburn  13995:     $output .= 
                   13996:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13997:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13998:         "\n";
1.1065    raeburn  13999:     if ($duplicates ne '') {
                   14000:         $output .= '<p><span class="LC_warning">'.
                   14001:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14002:                    &start_data_table().
                   14003:                    &start_data_table_header_row().
                   14004:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14005:                    '<th>'.&mt('Name').'</th>'.
                   14006:                    '<th>'.&mt('Type').'</th>'.
                   14007:                    '<th>'.&mt('Size').'</th>'.
                   14008:                    '<th>'.&mt('Last modified').'</th>'.
                   14009:                    &end_data_table_header_row().
                   14010:                    $duplicates.
                   14011:                    &end_data_table().
                   14012:                    '</p>';
                   14013:     }
1.1067    raeburn  14014:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14015:     if (ref($hiddenelements) eq 'HASH') {
                   14016:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14017:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14018:         }
                   14019:     }
                   14020:     $output .= <<"END";
1.1067    raeburn  14021: <br />
1.1053    raeburn  14022: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14023: </form>
                   14024: $noextract
                   14025: END
                   14026:     return $output;
                   14027: }
                   14028: 
1.1065    raeburn  14029: sub decompression_utility {
                   14030:     my ($program) = @_;
                   14031:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14032:     my $location;
                   14033:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14034:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14035:                          '/usr/sbin/') {
                   14036:             if (-x $dir.$program) {
                   14037:                 $location = $dir.$program;
                   14038:                 last;
                   14039:             }
                   14040:         }
                   14041:     }
                   14042:     return $location;
                   14043: }
                   14044: 
                   14045: sub list_archive_contents {
                   14046:     my ($file,$pathsref) = @_;
                   14047:     my (@cmd,$output);
                   14048:     my $needsregexp;
                   14049:     if ($file =~ /\.zip$/) {
                   14050:         @cmd = (&decompression_utility('unzip'),"-l");
                   14051:         $needsregexp = 1;
                   14052:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14053:              ($file =~ /\.tgz$/)) {
                   14054:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14055:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14056:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14057:     } elsif ($file =~ m|\.tar$|) {
                   14058:         @cmd = (&decompression_utility('tar'),"-tf");
                   14059:     }
                   14060:     if (@cmd) {
                   14061:         undef($!);
                   14062:         undef($@);
                   14063:         if (open(my $fh,"-|", @cmd, $file)) {
                   14064:             while (my $line = <$fh>) {
                   14065:                 $output .= $line;
                   14066:                 chomp($line);
                   14067:                 my $item;
                   14068:                 if ($needsregexp) {
                   14069:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14070:                 } else {
                   14071:                     $item = $line;
                   14072:                 }
                   14073:                 if ($item ne '') {
                   14074:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14075:                         push(@{$pathsref},$item);
                   14076:                     } 
                   14077:                 }
                   14078:             }
                   14079:             close($fh);
                   14080:         }
                   14081:     }
                   14082:     return $output;
                   14083: }
                   14084: 
1.1053    raeburn  14085: sub decompress_uploaded_file {
                   14086:     my ($file,$dir) = @_;
                   14087:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14088:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14089:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14090:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14091:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14092:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14093:     my $decompressed = $env{'cgi.decompressed'};
                   14094:     &Apache::lonnet::delenv('cgi.file');
                   14095:     &Apache::lonnet::delenv('cgi.dir');
                   14096:     &Apache::lonnet::delenv('cgi.decompressed');
                   14097:     return ($decompressed,$result);
                   14098: }
                   14099: 
1.1055    raeburn  14100: sub process_decompression {
                   14101:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14102:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14103:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14104:                &mt('Unexpected file path.').'</p>'."\n";
                   14105:     }
                   14106:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14107:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14108:                &mt('Unexpected course context.').'</p>'."\n";
                   14109:     }
1.1293    raeburn  14110:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14111:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14112:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14113:     }
1.1055    raeburn  14114:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14115:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14116:         $error = &mt('Filename not a supported archive file type.').
                   14117:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14118:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14119:     } else {
                   14120:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14121:         if ($docuhome eq 'no_host') {
                   14122:             $error = &mt('Could not determine home server for course.');
                   14123:         } else {
                   14124:             my @ids=&Apache::lonnet::current_machine_ids();
                   14125:             my $currdir = "$dir_root/$destination";
                   14126:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14127:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14128:                        "$dir_root/$destination";
                   14129:             } else {
                   14130:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14131:                        "$dir_root/$docudom/$docuname/$destination";
                   14132:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14133:                     $error = &mt('Archive file not found.');
                   14134:                 }
                   14135:             }
1.1065    raeburn  14136:             my (@to_overwrite,@to_skip);
                   14137:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14138:                 my $total = $env{'form.archive_overwrite_total'};
                   14139:                 for (my $i=0; $i<$total; $i++) {
                   14140:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14141:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14142:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14143:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14144:                     }
                   14145:                 }
                   14146:             }
                   14147:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14148:             my $numoverwrite = scalar(@to_overwrite);
                   14149:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14150:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14151:             } elsif ($dir eq '') {
1.1055    raeburn  14152:                 $error = &mt('Directory containing archive file unavailable.');
                   14153:             } elsif (!$error) {
1.1065    raeburn  14154:                 my ($decompressed,$display);
1.1292    raeburn  14155:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14156:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14157:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14158:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14159:                         ($decompressed,$display) = 
                   14160:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14161:                         foreach my $item (@to_skip) {
                   14162:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14163:                                 if (-f "$dir/$tempdir/$item") { 
                   14164:                                     unlink("$dir/$tempdir/$item");
                   14165:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14166:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14167:                                 }
                   14168:                             }
                   14169:                         }
                   14170:                         foreach my $item (@to_overwrite) {
                   14171:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14172:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14173:                                     if (-f "$dir/$item") {
                   14174:                                         unlink("$dir/$item");
                   14175:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14176:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14177:                                     }
                   14178:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14179:                                 }
1.1065    raeburn  14180:                             }
                   14181:                         }
1.1292    raeburn  14182:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14183:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14184:                         }
1.1065    raeburn  14185:                     }
                   14186:                 } else {
                   14187:                     ($decompressed,$display) = 
                   14188:                         &decompress_uploaded_file($file,$dir);
                   14189:                 }
1.1055    raeburn  14190:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14191:                     $output = '<p class="LC_info">'.
                   14192:                               &mt('Files extracted successfully from archive.').
                   14193:                               '</p>'."\n";
1.1055    raeburn  14194:                     my ($warning,$result,@contents);
                   14195:                     my ($newdirlistref,$newlisterror) =
                   14196:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14197:                                                  $docuname,1);
                   14198:                     my (%is_dir,%changes,@newitems);
                   14199:                     my $dirptr = 16384;
1.1065    raeburn  14200:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14201:                         foreach my $dir_line (@{$newdirlistref}) {
                   14202:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14203:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14204:                                 push(@newitems,$item);
                   14205:                                 if ($dirptr&$testdir) {
                   14206:                                     $is_dir{$item} = 1;
                   14207:                                 }
                   14208:                                 $changes{$item} = 1;
                   14209:                             }
                   14210:                         }
                   14211:                     }
                   14212:                     if (keys(%changes) > 0) {
                   14213:                         foreach my $item (sort(@newitems)) {
                   14214:                             if ($changes{$item}) {
                   14215:                                 push(@contents,$item);
                   14216:                             }
                   14217:                         }
                   14218:                     }
                   14219:                     if (@contents > 0) {
1.1067    raeburn  14220:                         my $wantform;
                   14221:                         unless ($env{'form.autoextract_camtasia'}) {
                   14222:                             $wantform = 1;
                   14223:                         }
1.1056    raeburn  14224:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14225:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14226:                                                                 $currdir,\%is_dir,
                   14227:                                                                 \%children,\%parent,
1.1056    raeburn  14228:                                                                 \@contents,\%dirorder,
                   14229:                                                                 \%titles,$wantform);
1.1055    raeburn  14230:                         if ($datatable ne '') {
                   14231:                             $output .= &archive_options_form('decompressed',$datatable,
                   14232:                                                              $count,$hiddenelem);
1.1065    raeburn  14233:                             my $startcount = 6;
1.1055    raeburn  14234:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14235:                                                            \%titles,\%children);
1.1055    raeburn  14236:                         }
1.1067    raeburn  14237:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14238:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14239:                             my %displayed;
                   14240:                             my $total = 1;
                   14241:                             $env{'form.archive_directory'} = [];
                   14242:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14243:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14244:                                 $path =~ s{/$}{};
                   14245:                                 my $item;
                   14246:                                 if ($path ne '') {
                   14247:                                     $item = "$path/$titles{$i}";
                   14248:                                 } else {
                   14249:                                     $item = $titles{$i};
                   14250:                                 }
                   14251:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14252:                                 if ($item eq $contents[0]) {
                   14253:                                     push(@{$env{'form.archive_directory'}},$i);
                   14254:                                     $env{'form.archive_'.$i} = 'display';
                   14255:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14256:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14257:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14258:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14259:                                     $env{'form.archive_'.$i} = 'display';
                   14260:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14261:                                     $displayed{'web'} = $i;
                   14262:                                 } else {
1.1164    raeburn  14263:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14264:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14265:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14266:                                         push(@{$env{'form.archive_directory'}},$i);
                   14267:                                     }
                   14268:                                     $env{'form.archive_'.$i} = 'dependency';
                   14269:                                 }
                   14270:                                 $total ++;
                   14271:                             }
                   14272:                             for (my $i=1; $i<$total; $i++) {
                   14273:                                 next if ($i == $displayed{'web'});
                   14274:                                 next if ($i == $displayed{'folder'});
                   14275:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14276:                             }
                   14277:                             $env{'form.phase'} = 'decompress_cleanup';
                   14278:                             $env{'form.archivedelete'} = 1;
                   14279:                             $env{'form.archive_count'} = $total-1;
                   14280:                             $output .=
                   14281:                                 &process_extracted_files('coursedocs',$docudom,
                   14282:                                                          $docuname,$destination,
                   14283:                                                          $dir_root,$hiddenelem);
                   14284:                         }
1.1055    raeburn  14285:                     } else {
                   14286:                         $warning = &mt('No new items extracted from archive file.');
                   14287:                     }
                   14288:                 } else {
                   14289:                     $output = $display;
                   14290:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14291:                 }
                   14292:             }
                   14293:         }
                   14294:     }
                   14295:     if ($error) {
                   14296:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14297:                    $error.'</p>'."\n";
                   14298:     }
                   14299:     if ($warning) {
                   14300:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14301:     }
                   14302:     return $output;
                   14303: }
                   14304: 
                   14305: sub get_extracted {
1.1056    raeburn  14306:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14307:         $titles,$wantform) = @_;
1.1055    raeburn  14308:     my $count = 0;
                   14309:     my $depth = 0;
                   14310:     my $datatable;
1.1056    raeburn  14311:     my @hierarchy;
1.1055    raeburn  14312:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14313:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14314:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14315:     foreach my $item (@{$contents}) {
                   14316:         $count ++;
1.1056    raeburn  14317:         @{$dirorder->{$count}} = @hierarchy;
                   14318:         $titles->{$count} = $item;
1.1055    raeburn  14319:         &archive_hierarchy($depth,$count,$parent,$children);
                   14320:         if ($wantform) {
                   14321:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14322:                                        $currdir,$depth,$count);
                   14323:         }
                   14324:         if ($is_dir->{$item}) {
                   14325:             $depth ++;
1.1056    raeburn  14326:             push(@hierarchy,$count);
                   14327:             $parent->{$depth} = $count;
1.1055    raeburn  14328:             $datatable .=
                   14329:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14330:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14331:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14332:             $depth --;
1.1056    raeburn  14333:             pop(@hierarchy);
1.1055    raeburn  14334:         }
                   14335:     }
                   14336:     return ($count,$datatable);
                   14337: }
                   14338: 
                   14339: sub recurse_extracted_archive {
1.1056    raeburn  14340:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14341:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14342:     my $result='';
1.1056    raeburn  14343:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14344:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14345:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14346:         return $result;
                   14347:     }
                   14348:     my $dirptr = 16384;
                   14349:     my ($newdirlistref,$newlisterror) =
                   14350:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14351:     if (ref($newdirlistref) eq 'ARRAY') {
                   14352:         foreach my $dir_line (@{$newdirlistref}) {
                   14353:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14354:             unless ($item =~ /^\.+$/) {
                   14355:                 $$count ++;
1.1056    raeburn  14356:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14357:                 $titles->{$$count} = $item;
1.1055    raeburn  14358:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14359: 
1.1055    raeburn  14360:                 my $is_dir;
                   14361:                 if ($dirptr&$testdir) {
                   14362:                     $is_dir = 1;
                   14363:                 }
                   14364:                 if ($wantform) {
                   14365:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14366:                 }
                   14367:                 if ($is_dir) {
                   14368:                     $$depth ++;
1.1056    raeburn  14369:                     push(@{$hierarchy},$$count);
                   14370:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14371:                     $result .=
                   14372:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14373:                                                    $docuname,$depth,$count,
1.1056    raeburn  14374:                                                    $hierarchy,$dirorder,$children,
                   14375:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14376:                     $$depth --;
1.1056    raeburn  14377:                     pop(@{$hierarchy});
1.1055    raeburn  14378:                 }
                   14379:             }
                   14380:         }
                   14381:     }
                   14382:     return $result;
                   14383: }
                   14384: 
                   14385: sub archive_hierarchy {
                   14386:     my ($depth,$count,$parent,$children) =@_;
                   14387:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14388:         if (exists($parent->{$depth})) {
                   14389:              $children->{$parent->{$depth}} .= $count.':';
                   14390:         }
                   14391:     }
                   14392:     return;
                   14393: }
                   14394: 
                   14395: sub archive_row {
                   14396:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14397:     my ($name) = ($item =~ m{([^/]+)$});
                   14398:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14399:                                        'display'    => 'Add as file',
1.1055    raeburn  14400:                                        'dependency' => 'Include as dependency',
                   14401:                                        'discard'    => 'Discard',
                   14402:                                       );
                   14403:     if ($is_dir) {
1.1059    raeburn  14404:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14405:     }
1.1056    raeburn  14406:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14407:     my $offset = 0;
1.1055    raeburn  14408:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14409:         $offset ++;
1.1065    raeburn  14410:         if ($action ne 'display') {
                   14411:             $offset ++;
                   14412:         }  
1.1055    raeburn  14413:         $output .= '<td><span class="LC_nobreak">'.
                   14414:                    '<label><input type="radio" name="archive_'.$count.
                   14415:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14416:         my $text = $choices{$action};
                   14417:         if ($is_dir) {
                   14418:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14419:             if ($action eq 'display') {
1.1059    raeburn  14420:                 $text = &mt('Add as folder');
1.1055    raeburn  14421:             }
1.1056    raeburn  14422:         } else {
                   14423:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14424: 
                   14425:         }
                   14426:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14427:         if ($action eq 'dependency') {
                   14428:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14429:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14430:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14431:                        '<option value=""></option>'."\n".
                   14432:                        '</select>'."\n".
                   14433:                        '</div>';
1.1059    raeburn  14434:         } elsif ($action eq 'display') {
                   14435:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14436:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14437:                        '</div>';
1.1055    raeburn  14438:         }
1.1056    raeburn  14439:         $output .= '</td>';
1.1055    raeburn  14440:     }
                   14441:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14442:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14443:     for (my $i=0; $i<$depth; $i++) {
                   14444:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14445:     }
                   14446:     if ($is_dir) {
                   14447:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14448:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14449:     } else {
                   14450:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14451:     }
                   14452:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14453:                &end_data_table_row();
                   14454:     return $output;
                   14455: }
                   14456: 
                   14457: sub archive_options_form {
1.1065    raeburn  14458:     my ($form,$display,$count,$hiddenelem) = @_;
                   14459:     my %lt = &Apache::lonlocal::texthash(
                   14460:                perm => 'Permanently remove archive file?',
                   14461:                hows => 'How should each extracted item be incorporated in the course?',
                   14462:                cont => 'Content actions for all',
                   14463:                addf => 'Add as folder/file',
                   14464:                incd => 'Include as dependency for a displayed file',
                   14465:                disc => 'Discard',
                   14466:                no   => 'No',
                   14467:                yes  => 'Yes',
                   14468:                save => 'Save',
                   14469:     );
                   14470:     my $output = <<"END";
                   14471: <form name="$form" method="post" action="">
                   14472: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14473: <label>
                   14474:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14475: </label>
                   14476: &nbsp;
                   14477: <label>
                   14478:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14479: </span>
                   14480: </p>
                   14481: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14482: <br />$lt{'hows'}
                   14483: <div class="LC_columnSection">
                   14484:   <fieldset>
                   14485:     <legend>$lt{'cont'}</legend>
                   14486:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14487:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14488:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14489:   </fieldset>
                   14490: </div>
                   14491: END
                   14492:     return $output.
1.1055    raeburn  14493:            &start_data_table()."\n".
1.1065    raeburn  14494:            $display."\n".
1.1055    raeburn  14495:            &end_data_table()."\n".
                   14496:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14497:            $hiddenelem.
1.1065    raeburn  14498:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14499:            '</form>';
                   14500: }
                   14501: 
                   14502: sub archive_javascript {
1.1056    raeburn  14503:     my ($startcount,$numitems,$titles,$children) = @_;
                   14504:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14505:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14506:     my $scripttag = <<START;
                   14507: <script type="text/javascript">
                   14508: // <![CDATA[
                   14509: 
                   14510: function checkAll(form,prefix) {
                   14511:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14512:     for (var i=0; i < form.elements.length; i++) {
                   14513:         var id = form.elements[i].id;
                   14514:         if ((id != '') && (id != undefined)) {
                   14515:             if (idstr.test(id)) {
                   14516:                 if (form.elements[i].type == 'radio') {
                   14517:                     form.elements[i].checked = true;
1.1056    raeburn  14518:                     var nostart = i-$startcount;
1.1059    raeburn  14519:                     var offset = nostart%7;
                   14520:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14521:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14522:                 }
                   14523:             }
                   14524:         }
                   14525:     }
                   14526: }
                   14527: 
                   14528: function propagateCheck(form,count) {
                   14529:     if (count > 0) {
1.1059    raeburn  14530:         var startelement = $startcount + ((count-1) * 7);
                   14531:         for (var j=1; j<6; j++) {
                   14532:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14533:                 var item = startelement + j; 
                   14534:                 if (form.elements[item].type == 'radio') {
                   14535:                     if (form.elements[item].checked) {
                   14536:                         containerCheck(form,count,j);
                   14537:                         break;
                   14538:                     }
1.1055    raeburn  14539:                 }
                   14540:             }
                   14541:         }
                   14542:     }
                   14543: }
                   14544: 
                   14545: numitems = $numitems
1.1056    raeburn  14546: var titles = new Array(numitems);
                   14547: var parents = new Array(numitems);
1.1055    raeburn  14548: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14549:     parents[i] = new Array;
1.1055    raeburn  14550: }
1.1059    raeburn  14551: var maintitle = '$maintitle';
1.1055    raeburn  14552: 
                   14553: START
                   14554: 
1.1056    raeburn  14555:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14556:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14557:         for (my $i=0; $i<@contents; $i ++) {
                   14558:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14559:         }
                   14560:     }
                   14561: 
1.1056    raeburn  14562:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14563:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14564:     }
                   14565: 
1.1055    raeburn  14566:     $scripttag .= <<END;
                   14567: 
                   14568: function containerCheck(form,count,offset) {
                   14569:     if (count > 0) {
1.1056    raeburn  14570:         dependencyCheck(form,count,offset);
1.1059    raeburn  14571:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14572:         form.elements[item].checked = true;
                   14573:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14574:             if (parents[count].length > 0) {
                   14575:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14576:                     containerCheck(form,parents[count][j],offset);
                   14577:                 }
                   14578:             }
                   14579:         }
                   14580:     }
                   14581: }
                   14582: 
                   14583: function dependencyCheck(form,count,offset) {
                   14584:     if (count > 0) {
1.1059    raeburn  14585:         var chosen = (offset+$startcount)+7*(count-1);
                   14586:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14587:         var currtype = form.elements[depitem].type;
                   14588:         if (form.elements[chosen].value == 'dependency') {
                   14589:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14590:             form.elements[depitem].options.length = 0;
                   14591:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14592:             for (var i=1; i<=numitems; i++) {
                   14593:                 if (i == count) {
                   14594:                     continue;
                   14595:                 }
1.1059    raeburn  14596:                 var startelement = $startcount + (i-1) * 7;
                   14597:                 for (var j=1; j<6; j++) {
                   14598:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14599:                         var item = startelement + j;
                   14600:                         if (form.elements[item].type == 'radio') {
                   14601:                             if (form.elements[item].checked) {
                   14602:                                 if (form.elements[item].value == 'display') {
                   14603:                                     var n = form.elements[depitem].options.length;
                   14604:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14605:                                 }
                   14606:                             }
                   14607:                         }
                   14608:                     }
                   14609:                 }
                   14610:             }
                   14611:         } else {
                   14612:             document.getElementById('arc_depon_'+count).style.display='none';
                   14613:             form.elements[depitem].options.length = 0;
                   14614:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14615:         }
1.1059    raeburn  14616:         titleCheck(form,count,offset);
1.1056    raeburn  14617:     }
                   14618: }
                   14619: 
                   14620: function propagateSelect(form,count,offset) {
                   14621:     if (count > 0) {
1.1065    raeburn  14622:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14623:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14624:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14625:             if (parents[count].length > 0) {
                   14626:                 for (var j=0; j<parents[count].length; j++) {
                   14627:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14628:                 }
                   14629:             }
                   14630:         }
                   14631:     }
                   14632: }
1.1056    raeburn  14633: 
                   14634: function containerSelect(form,count,offset,picked) {
                   14635:     if (count > 0) {
1.1065    raeburn  14636:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14637:         if (form.elements[item].type == 'radio') {
                   14638:             if (form.elements[item].value == 'dependency') {
                   14639:                 if (form.elements[item+1].type == 'select-one') {
                   14640:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14641:                         if (form.elements[item+1].options[i].value == picked) {
                   14642:                             form.elements[item+1].selectedIndex = i;
                   14643:                             break;
                   14644:                         }
                   14645:                     }
                   14646:                 }
                   14647:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14648:                     if (parents[count].length > 0) {
                   14649:                         for (var j=0; j<parents[count].length; j++) {
                   14650:                             containerSelect(form,parents[count][j],offset,picked);
                   14651:                         }
                   14652:                     }
                   14653:                 }
                   14654:             }
                   14655:         }
                   14656:     }
                   14657: }
                   14658: 
1.1059    raeburn  14659: function titleCheck(form,count,offset) {
                   14660:     if (count > 0) {
                   14661:         var chosen = (offset+$startcount)+7*(count-1);
                   14662:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14663:         var currtype = form.elements[depitem].type;
                   14664:         if (form.elements[chosen].value == 'display') {
                   14665:             document.getElementById('arc_title_'+count).style.display='block';
                   14666:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14667:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14668:             }
                   14669:         } else {
                   14670:             document.getElementById('arc_title_'+count).style.display='none';
                   14671:             if (currtype == 'text') { 
                   14672:                 document.getElementById('archive_title_'+count).value='';
                   14673:             }
                   14674:         }
                   14675:     }
                   14676:     return;
                   14677: }
                   14678: 
1.1055    raeburn  14679: // ]]>
                   14680: </script>
                   14681: END
                   14682:     return $scripttag;
                   14683: }
                   14684: 
                   14685: sub process_extracted_files {
1.1067    raeburn  14686:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14687:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14688:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14689:     my @ids=&Apache::lonnet::current_machine_ids();
                   14690:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14691:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14692:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14693:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14694:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14695:         $pathtocheck = "$dir_root/$destination";
                   14696:         $dir = $dir_root;
                   14697:         $ishome = 1;
                   14698:     } else {
                   14699:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14700:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14701:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14702:     }
                   14703:     my $currdir = "$dir_root/$destination";
                   14704:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14705:     if ($env{'form.folderpath'}) {
                   14706:         my @items = split('&',$env{'form.folderpath'});
                   14707:         $folders{'0'} = $items[-2];
1.1099    raeburn  14708:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14709:             $containers{'0'}='page';
                   14710:         } else {  
                   14711:             $containers{'0'}='sequence';
                   14712:         }
1.1055    raeburn  14713:     }
                   14714:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14715:     if ($numitems) {
                   14716:         for (my $i=1; $i<=$numitems; $i++) {
                   14717:             my $path = $env{'form.archive_content_'.$i};
                   14718:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14719:                 my $item = $1;
                   14720:                 $toplevelitems{$item} = $i;
                   14721:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14722:                     $is_dir{$item} = 1;
                   14723:                 }
                   14724:             }
                   14725:         }
                   14726:     }
1.1067    raeburn  14727:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14728:     if (keys(%toplevelitems) > 0) {
                   14729:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14730:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14731:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14732:     }
1.1066    raeburn  14733:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14734:     if ($numitems) {
                   14735:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14736:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14737:             my $path = $env{'form.archive_content_'.$i};
                   14738:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14739:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14740:                     if ($prefix ne '' && $path ne '') {
                   14741:                         if (-e $prefix.$path) {
1.1066    raeburn  14742:                             if ((@archdirs > 0) && 
                   14743:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14744:                                 $todeletedir{$prefix.$path} = 1;
                   14745:                             } else {
                   14746:                                 $todelete{$prefix.$path} = 1;
                   14747:                             }
1.1055    raeburn  14748:                         }
                   14749:                     }
                   14750:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14751:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14752:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14753:                     $docstitle = $env{'form.archive_title_'.$i};
                   14754:                     if ($docstitle eq '') {
                   14755:                         $docstitle = $title;
                   14756:                     }
1.1055    raeburn  14757:                     $outer = 0;
1.1056    raeburn  14758:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14759:                         if (@{$dirorder{$i}} > 0) {
                   14760:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14761:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14762:                                     $outer = $item;
                   14763:                                     last;
                   14764:                                 }
                   14765:                             }
                   14766:                         }
                   14767:                     }
                   14768:                     my ($errtext,$fatal) = 
                   14769:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14770:                                                '/'.$folders{$outer}.'.'.
                   14771:                                                $containers{$outer});
                   14772:                     next if ($fatal);
                   14773:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14774:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14775:                             $mapinner{$i} = time;
1.1055    raeburn  14776:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14777:                             $containers{$i} = 'sequence';
                   14778:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14779:                                       $folders{$i}.'.'.$containers{$i};
                   14780:                             my $newidx = &LONCAPA::map::getresidx();
                   14781:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14782:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14783:                             push(@LONCAPA::map::order,$newidx);
                   14784:                             my ($outtext,$errtext) =
                   14785:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14786:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14787:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14788:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14789:                             unless ($errtext) {
1.1294    raeburn  14790:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14791:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14792:                                             '</li>'."\n";
1.1067    raeburn  14793:                             }
1.1055    raeburn  14794:                         }
                   14795:                     } else {
                   14796:                         if ($context eq 'coursedocs') {
                   14797:                             my $newidx=&LONCAPA::map::getresidx();
                   14798:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14799:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14800:                                       $title;
1.1392    raeburn  14801:                             if (($outer !~ /\D/) &&
                   14802:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14803:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14804:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14805:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14806:                                 }
                   14807:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14808:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14809:                                 }
                   14810:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14811:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14812:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14813:                                         unless ($ishome) {
                   14814:                                             my $fetch = "$newdest{$i}/$title";
                   14815:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14816:                                             $prompttofetch{$fetch} = 1;
                   14817:                                         }
1.1292    raeburn  14818:                                     }
1.1067    raeburn  14819:                                 }
1.1294    raeburn  14820:                                 $LONCAPA::map::resources[$newidx]=
                   14821:                                     $docstitle.':'.$url.':false:normal:res';
                   14822:                                 push(@LONCAPA::map::order, $newidx);
                   14823:                                 my ($outtext,$errtext)=
                   14824:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14825:                                                             $docuname.'/'.$folders{$outer}.
                   14826:                                                             '.'.$containers{$outer},1,1);
                   14827:                                 unless ($errtext) {
                   14828:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14829:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14830:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14831:                                                    '</li>'."\n";
                   14832:                                     }
1.1067    raeburn  14833:                                 }
1.1294    raeburn  14834:                             } else {
                   14835:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14836:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14837:                             }
1.1055    raeburn  14838:                         }
                   14839:                     }
1.1086    raeburn  14840:                 }
                   14841:             } else {
1.1294    raeburn  14842:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14843:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14844:             }
                   14845:         }
                   14846:         for (my $i=1; $i<=$numitems; $i++) {
                   14847:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14848:             my $path = $env{'form.archive_content_'.$i};
                   14849:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14850:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14851:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14852:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14853:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14854:                         my ($itemidx,$fullpath,$relpath);
                   14855:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14856:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14857:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14858:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14859:                                     $itemidx = $j;
1.1056    raeburn  14860:                                 }
                   14861:                             }
1.1086    raeburn  14862:                         }
                   14863:                         if ($itemidx eq '') {
                   14864:                             $itemidx =  0;
                   14865:                         } 
                   14866:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14867:                             if ($mapinner{$referrer{$i}}) {
                   14868:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14869:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14870:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14871:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14872:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14873:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14874:                                             if (!-e $fullpath) {
                   14875:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14876:                                             }
                   14877:                                         }
1.1086    raeburn  14878:                                     } else {
                   14879:                                         last;
1.1056    raeburn  14880:                                     }
1.1086    raeburn  14881:                                 }
                   14882:                             }
                   14883:                         } elsif ($newdest{$referrer{$i}}) {
                   14884:                             $fullpath = $newdest{$referrer{$i}};
                   14885:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14886:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14887:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14888:                                     last;
                   14889:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14890:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14891:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14892:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14893:                                         if (!-e $fullpath) {
                   14894:                                             mkdir($fullpath,0755);
1.1056    raeburn  14895:                                         }
                   14896:                                     }
1.1086    raeburn  14897:                                 } else {
                   14898:                                     last;
1.1056    raeburn  14899:                                 }
1.1055    raeburn  14900:                             }
                   14901:                         }
1.1086    raeburn  14902:                         if ($fullpath ne '') {
                   14903:                             if (-e "$prefix$path") {
1.1292    raeburn  14904:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14905:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14906:                                 }
1.1086    raeburn  14907:                             }
                   14908:                             if (-e "$fullpath/$title") {
                   14909:                                 my $showpath;
                   14910:                                 if ($relpath ne '') {
                   14911:                                     $showpath = "$relpath/$title";
                   14912:                                 } else {
                   14913:                                     $showpath = "/$title";
                   14914:                                 } 
1.1294    raeburn  14915:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14916:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14917:                                            '</li>'."\n";
1.1292    raeburn  14918:                                 unless ($ishome) {
                   14919:                                     my $fetch = "$fullpath/$title";
                   14920:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14921:                                     $prompttofetch{$fetch} = 1;
                   14922:                                 }
1.1086    raeburn  14923:                             }
                   14924:                         }
1.1055    raeburn  14925:                     }
1.1086    raeburn  14926:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14927:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14928:                                     &HTML::Entities::encode($path,'<>&"'),
                   14929:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14930:                                 '<br />';
1.1055    raeburn  14931:                 }
                   14932:             } else {
1.1294    raeburn  14933:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14934:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14935:             }
                   14936:         }
                   14937:         if (keys(%todelete)) {
                   14938:             foreach my $key (keys(%todelete)) {
                   14939:                 unlink($key);
1.1066    raeburn  14940:             }
                   14941:         }
                   14942:         if (keys(%todeletedir)) {
                   14943:             foreach my $key (keys(%todeletedir)) {
                   14944:                 rmdir($key);
                   14945:             }
                   14946:         }
                   14947:         foreach my $dir (sort(keys(%is_dir))) {
                   14948:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14949:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14950:             }
                   14951:         }
1.1067    raeburn  14952:         if ($result ne '') {
                   14953:             $output .= '<ul>'."\n".
                   14954:                        $result."\n".
                   14955:                        '</ul>';
                   14956:         }
                   14957:         unless ($ishome) {
                   14958:             my $replicationfail;
                   14959:             foreach my $item (keys(%prompttofetch)) {
                   14960:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14961:                 unless ($fetchresult eq 'ok') {
                   14962:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14963:                 }
                   14964:             }
                   14965:             if ($replicationfail) {
                   14966:                 $output .= '<p class="LC_error">'.
                   14967:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14968:                            $replicationfail.
                   14969:                            '</ul></p>';
                   14970:             }
                   14971:         }
1.1055    raeburn  14972:     } else {
                   14973:         $warning = &mt('No items found in archive.');
                   14974:     }
                   14975:     if ($error) {
                   14976:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14977:                    $error.'</p>'."\n";
                   14978:     }
                   14979:     if ($warning) {
                   14980:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14981:     }
                   14982:     return $output;
                   14983: }
                   14984: 
1.1066    raeburn  14985: sub cleanup_empty_dirs {
                   14986:     my ($path) = @_;
                   14987:     if (($path ne '') && (-d $path)) {
                   14988:         if (opendir(my $dirh,$path)) {
                   14989:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14990:             my $numitems = 0;
                   14991:             foreach my $item (@dircontents) {
                   14992:                 if (-d "$path/$item") {
1.1111    raeburn  14993:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14994:                     if (-e "$path/$item") {
                   14995:                         $numitems ++;
                   14996:                     }
                   14997:                 } else {
                   14998:                     $numitems ++;
                   14999:                 }
                   15000:             }
                   15001:             if ($numitems == 0) {
                   15002:                 rmdir($path);
                   15003:             }
                   15004:             closedir($dirh);
                   15005:         }
                   15006:     }
                   15007:     return;
                   15008: }
                   15009: 
1.41      ng       15010: =pod
1.45      matthew  15011: 
1.1162    raeburn  15012: =item * &get_folder_hierarchy()
1.1068    raeburn  15013: 
                   15014: Provides hierarchy of names of folders/sub-folders containing the current
                   15015: item,
                   15016: 
                   15017: Inputs: 3
                   15018:      - $navmap - navmaps object
                   15019: 
                   15020:      - $map - url for map (either the trigger itself, or map containing
                   15021:                            the resource, which is the trigger).
                   15022: 
                   15023:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15024: 
                   15025: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15026: 
                   15027: =cut
                   15028: 
                   15029: sub get_folder_hierarchy {
                   15030:     my ($navmap,$map,$showitem) = @_;
                   15031:     my @pathitems;
                   15032:     if (ref($navmap)) {
                   15033:         my $mapres = $navmap->getResourceByUrl($map);
                   15034:         if (ref($mapres)) {
                   15035:             my $pcslist = $mapres->map_hierarchy();
                   15036:             if ($pcslist ne '') {
                   15037:                 my @pcs = split(/,/,$pcslist);
                   15038:                 foreach my $pc (@pcs) {
                   15039:                     if ($pc == 1) {
1.1129    raeburn  15040:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15041:                     } else {
                   15042:                         my $res = $navmap->getByMapPc($pc);
                   15043:                         if (ref($res)) {
                   15044:                             my $title = $res->compTitle();
                   15045:                             $title =~ s/\W+/_/g;
                   15046:                             if ($title ne '') {
                   15047:                                 push(@pathitems,$title);
                   15048:                             }
                   15049:                         }
                   15050:                     }
                   15051:                 }
                   15052:             }
1.1071    raeburn  15053:             if ($showitem) {
                   15054:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15055:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15056:                 } else {
                   15057:                     my $maptitle = $mapres->compTitle();
                   15058:                     $maptitle =~ s/\W+/_/g;
                   15059:                     if ($maptitle ne '') {
                   15060:                         push(@pathitems,$maptitle);
                   15061:                     }
1.1068    raeburn  15062:                 }
                   15063:             }
                   15064:         }
                   15065:     }
                   15066:     return @pathitems;
                   15067: }
                   15068: 
                   15069: =pod
                   15070: 
1.1015    raeburn  15071: =item * &get_turnedin_filepath()
                   15072: 
                   15073: Determines path in a user's portfolio file for storage of files uploaded
                   15074: to a specific essayresponse or dropbox item.
                   15075: 
                   15076: Inputs: 3 required + 1 optional.
                   15077: $symb is symb for resource, $uname and $udom are for current user (required).
                   15078: $caller is optional (can be "submission", if routine is called when storing
                   15079: an upoaded file when "Submit Answer" button was pressed).
                   15080: 
                   15081: Returns array containing $path and $multiresp. 
                   15082: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15083: than one file upload item.  Callers of routine should append partid as a 
                   15084: subdirectory to $path in cases where $multiresp is 1.
                   15085: 
                   15086: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15087: 
                   15088: =cut
                   15089: 
                   15090: sub get_turnedin_filepath {
                   15091:     my ($symb,$uname,$udom,$caller) = @_;
                   15092:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15093:     my $turnindir;
                   15094:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15095:     $turnindir = $userhash{'turnindir'};
                   15096:     my ($path,$multiresp);
                   15097:     if ($turnindir eq '') {
                   15098:         if ($caller eq 'submission') {
                   15099:             $turnindir = &mt('turned in');
                   15100:             $turnindir =~ s/\W+/_/g;
                   15101:             my %newhash = (
                   15102:                             'turnindir' => $turnindir,
                   15103:                           );
                   15104:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15105:         }
                   15106:     }
                   15107:     if ($turnindir ne '') {
                   15108:         $path = '/'.$turnindir.'/';
                   15109:         my ($multipart,$turnin,@pathitems);
                   15110:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15111:         if (defined($navmap)) {
                   15112:             my $mapres = $navmap->getResourceByUrl($map);
                   15113:             if (ref($mapres)) {
                   15114:                 my $pcslist = $mapres->map_hierarchy();
                   15115:                 if ($pcslist ne '') {
                   15116:                     foreach my $pc (split(/,/,$pcslist)) {
                   15117:                         my $res = $navmap->getByMapPc($pc);
                   15118:                         if (ref($res)) {
                   15119:                             my $title = $res->compTitle();
                   15120:                             $title =~ s/\W+/_/g;
                   15121:                             if ($title ne '') {
1.1149    raeburn  15122:                                 if (($pc > 1) && (length($title) > 12)) {
                   15123:                                     $title = substr($title,0,12);
                   15124:                                 }
1.1015    raeburn  15125:                                 push(@pathitems,$title);
                   15126:                             }
                   15127:                         }
                   15128:                     }
                   15129:                 }
                   15130:                 my $maptitle = $mapres->compTitle();
                   15131:                 $maptitle =~ s/\W+/_/g;
                   15132:                 if ($maptitle ne '') {
1.1149    raeburn  15133:                     if (length($maptitle) > 12) {
                   15134:                         $maptitle = substr($maptitle,0,12);
                   15135:                     }
1.1015    raeburn  15136:                     push(@pathitems,$maptitle);
                   15137:                 }
                   15138:                 unless ($env{'request.state'} eq 'construct') {
                   15139:                     my $res = $navmap->getBySymb($symb);
                   15140:                     if (ref($res)) {
                   15141:                         my $partlist = $res->parts();
                   15142:                         my $totaluploads = 0;
                   15143:                         if (ref($partlist) eq 'ARRAY') {
                   15144:                             foreach my $part (@{$partlist}) {
                   15145:                                 my @types = $res->responseType($part);
                   15146:                                 my @ids = $res->responseIds($part);
                   15147:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15148:                                     if ($types[$i] eq 'essay') {
                   15149:                                         my $partid = $part.'_'.$ids[$i];
                   15150:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15151:                                             $totaluploads ++;
                   15152:                                         }
                   15153:                                     }
                   15154:                                 }
                   15155:                             }
                   15156:                             if ($totaluploads > 1) {
                   15157:                                 $multiresp = 1;
                   15158:                             }
                   15159:                         }
                   15160:                     }
                   15161:                 }
                   15162:             } else {
                   15163:                 return;
                   15164:             }
                   15165:         } else {
                   15166:             return;
                   15167:         }
                   15168:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15169:         $restitle =~ s/\W+/_/g;
                   15170:         if ($restitle eq '') {
                   15171:             $restitle = ($resurl =~ m{/[^/]+$});
                   15172:             if ($restitle eq '') {
                   15173:                 $restitle = time;
                   15174:             }
                   15175:         }
1.1149    raeburn  15176:         if (length($restitle) > 12) {
                   15177:             $restitle = substr($restitle,0,12);
                   15178:         }
1.1015    raeburn  15179:         push(@pathitems,$restitle);
                   15180:         $path .= join('/',@pathitems);
                   15181:     }
                   15182:     return ($path,$multiresp);
                   15183: }
                   15184: 
                   15185: =pod
                   15186: 
1.464     albertel 15187: =back
1.41      ng       15188: 
1.112     bowersj2 15189: =head1 CSV Upload/Handling functions
1.38      albertel 15190: 
1.41      ng       15191: =over 4
                   15192: 
1.648     raeburn  15193: =item * &upfile_store($r)
1.41      ng       15194: 
                   15195: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15196: needs $env{'form.upfile'}
1.41      ng       15197: returns $datatoken to be put into hidden field
                   15198: 
                   15199: =cut
1.31      albertel 15200: 
                   15201: sub upfile_store {
                   15202:     my $r=shift;
1.258     albertel 15203:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15204:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15205:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15206:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15207: 
1.1299    raeburn  15208:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15209:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15210:                                      time.'_'.$$);
                   15211:     return if ($datatoken eq '');
                   15212: 
1.31      albertel 15213:     {
1.158     raeburn  15214:         my $datafile = $r->dir_config('lonDaemons').
                   15215:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15216:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15217:             print $fh $env{'form.upfile'};
1.158     raeburn  15218:             close($fh);
                   15219:         }
1.31      albertel 15220:     }
                   15221:     return $datatoken;
                   15222: }
                   15223: 
1.56      matthew  15224: =pod
                   15225: 
1.1290    raeburn  15226: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15227: 
                   15228: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15229: $datatoken is the name to assign to the temporary file.
1.258     albertel 15230: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15231: 
                   15232: =cut
1.31      albertel 15233: 
                   15234: sub load_tmp_file {
1.1290    raeburn  15235:     my ($r,$datatoken) = @_;
                   15236:     return if ($datatoken eq '');
1.31      albertel 15237:     my @studentdata=();
                   15238:     {
1.158     raeburn  15239:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15240:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15241:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15242:             @studentdata=<$fh>;
                   15243:             close($fh);
                   15244:         }
1.31      albertel 15245:     }
1.258     albertel 15246:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15247: }
                   15248: 
1.1290    raeburn  15249: sub valid_datatoken {
                   15250:     my ($datatoken) = @_;
1.1325    raeburn  15251:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15252:         return $datatoken;
                   15253:     }
                   15254:     return;
                   15255: }
                   15256: 
1.56      matthew  15257: =pod
                   15258: 
1.648     raeburn  15259: =item * &upfile_record_sep()
1.41      ng       15260: 
                   15261: Separate uploaded file into records
                   15262: returns array of records,
1.258     albertel 15263: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15264: 
                   15265: =cut
1.31      albertel 15266: 
                   15267: sub upfile_record_sep {
1.258     albertel 15268:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15269:     } else {
1.248     albertel 15270: 	my @records;
1.258     albertel 15271: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15272: 	    if ($line=~/^\s*$/) { next; }
                   15273: 	    push(@records,$line);
                   15274: 	}
                   15275: 	return @records;
1.31      albertel 15276:     }
                   15277: }
                   15278: 
1.56      matthew  15279: =pod
                   15280: 
1.648     raeburn  15281: =item * &record_sep($record)
1.41      ng       15282: 
1.258     albertel 15283: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15284: 
                   15285: =cut
                   15286: 
1.263     www      15287: sub takeleft {
                   15288:     my $index=shift;
                   15289:     return substr('0000'.$index,-4,4);
                   15290: }
                   15291: 
1.31      albertel 15292: sub record_sep {
                   15293:     my $record=shift;
                   15294:     my %components=();
1.258     albertel 15295:     if ($env{'form.upfiletype'} eq 'xml') {
                   15296:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15297:         my $i=0;
1.356     albertel 15298:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15299:             $field=~s/^(\"|\')//;
                   15300:             $field=~s/(\"|\')$//;
1.263     www      15301:             $components{&takeleft($i)}=$field;
1.31      albertel 15302:             $i++;
                   15303:         }
1.258     albertel 15304:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15305:         my $i=0;
1.356     albertel 15306:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15307:             $field=~s/^(\"|\')//;
                   15308:             $field=~s/(\"|\')$//;
1.263     www      15309:             $components{&takeleft($i)}=$field;
1.31      albertel 15310:             $i++;
                   15311:         }
                   15312:     } else {
1.561     www      15313:         my $separator=',';
1.480     banghart 15314:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15315:             $separator=';';
1.480     banghart 15316:         }
1.31      albertel 15317:         my $i=0;
1.561     www      15318: # the character we are looking for to indicate the end of a quote or a record 
                   15319:         my $looking_for=$separator;
                   15320: # do not add the characters to the fields
                   15321:         my $ignore=0;
                   15322: # we just encountered a separator (or the beginning of the record)
                   15323:         my $just_found_separator=1;
                   15324: # store the field we are working on here
                   15325:         my $field='';
                   15326: # work our way through all characters in record
                   15327:         foreach my $character ($record=~/(.)/g) {
                   15328:             if ($character eq $looking_for) {
                   15329:                if ($character ne $separator) {
                   15330: # Found the end of a quote, again looking for separator
                   15331:                   $looking_for=$separator;
                   15332:                   $ignore=1;
                   15333:                } else {
                   15334: # Found a separator, store away what we got
                   15335:                   $components{&takeleft($i)}=$field;
                   15336: 	          $i++;
                   15337:                   $just_found_separator=1;
                   15338:                   $ignore=0;
                   15339:                   $field='';
                   15340:                }
                   15341:                next;
                   15342:             }
                   15343: # single or double quotation marks after a separator indicate beginning of a quote
                   15344: # we are now looking for the end of the quote and need to ignore separators
                   15345:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15346:                $looking_for=$character;
                   15347:                next;
                   15348:             }
                   15349: # ignore would be true after we reached the end of a quote
                   15350:             if ($ignore) { next; }
                   15351:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15352:             $field.=$character;
                   15353:             $just_found_separator=0; 
1.31      albertel 15354:         }
1.561     www      15355: # catch the very last entry, since we never encountered the separator
                   15356:         $components{&takeleft($i)}=$field;
1.31      albertel 15357:     }
                   15358:     return %components;
                   15359: }
                   15360: 
1.144     matthew  15361: ######################################################
                   15362: ######################################################
                   15363: 
1.56      matthew  15364: =pod
                   15365: 
1.648     raeburn  15366: =item * &upfile_select_html()
1.41      ng       15367: 
1.144     matthew  15368: Return HTML code to select a file from the users machine and specify 
                   15369: the file type.
1.41      ng       15370: 
                   15371: =cut
                   15372: 
1.144     matthew  15373: ######################################################
                   15374: ######################################################
1.31      albertel 15375: sub upfile_select_html {
1.144     matthew  15376:     my %Types = (
                   15377:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15378:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15379:                  space => &mt('Space separated'),
                   15380:                  tab   => &mt('Tabulator separated'),
                   15381: #                 xml   => &mt('HTML/XML'),
                   15382:                  );
                   15383:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15384:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15385:     foreach my $type (sort(keys(%Types))) {
                   15386:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15387:     }
                   15388:     $Str .= "</select>\n";
                   15389:     return $Str;
1.31      albertel 15390: }
                   15391: 
1.301     albertel 15392: sub get_samples {
                   15393:     my ($records,$toget) = @_;
                   15394:     my @samples=({});
                   15395:     my $got=0;
                   15396:     foreach my $rec (@$records) {
                   15397: 	my %temp = &record_sep($rec);
                   15398: 	if (! grep(/\S/, values(%temp))) { next; }
                   15399: 	if (%temp) {
                   15400: 	    $samples[$got]=\%temp;
                   15401: 	    $got++;
                   15402: 	    if ($got == $toget) { last; }
                   15403: 	}
                   15404:     }
                   15405:     return \@samples;
                   15406: }
                   15407: 
1.144     matthew  15408: ######################################################
                   15409: ######################################################
                   15410: 
1.56      matthew  15411: =pod
                   15412: 
1.648     raeburn  15413: =item * &csv_print_samples($r,$records)
1.41      ng       15414: 
                   15415: Prints a table of sample values from each column uploaded $r is an
                   15416: Apache Request ref, $records is an arrayref from
                   15417: &Apache::loncommon::upfile_record_sep
                   15418: 
                   15419: =cut
                   15420: 
1.144     matthew  15421: ######################################################
                   15422: ######################################################
1.31      albertel 15423: sub csv_print_samples {
                   15424:     my ($r,$records) = @_;
1.662     bisitz   15425:     my $samples = &get_samples($records,5);
1.301     albertel 15426: 
1.594     raeburn  15427:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15428:               &start_data_table_header_row());
1.356     albertel 15429:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15430:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15431:     $r->print(&end_data_table_header_row());
1.301     albertel 15432:     foreach my $hash (@$samples) {
1.594     raeburn  15433: 	$r->print(&start_data_table_row());
1.356     albertel 15434: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15435: 	    $r->print('<td>');
1.356     albertel 15436: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15437: 	    $r->print('</td>');
                   15438: 	}
1.594     raeburn  15439: 	$r->print(&end_data_table_row());
1.31      albertel 15440:     }
1.594     raeburn  15441:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15442: }
                   15443: 
1.144     matthew  15444: ######################################################
                   15445: ######################################################
                   15446: 
1.56      matthew  15447: =pod
                   15448: 
1.648     raeburn  15449: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15450: 
                   15451: Prints a table to create associations between values and table columns.
1.144     matthew  15452: 
1.41      ng       15453: $r is an Apache Request ref,
                   15454: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15455: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15456: 
                   15457: =cut
                   15458: 
1.144     matthew  15459: ######################################################
                   15460: ######################################################
1.31      albertel 15461: sub csv_print_select_table {
                   15462:     my ($r,$records,$d) = @_;
1.301     albertel 15463:     my $i=0;
                   15464:     my $samples = &get_samples($records,1);
1.144     matthew  15465:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15466: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15467:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15468:               '<th>'.&mt('Column').'</th>'.
                   15469:               &end_data_table_header_row()."\n");
1.356     albertel 15470:     foreach my $array_ref (@$d) {
                   15471: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15472: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15473: 
1.875     bisitz   15474: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15475: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15476: 	$r->print('<option value="none"></option>');
1.356     albertel 15477: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15478: 	    $r->print('<option value="'.$sample.'"'.
                   15479:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15480:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15481: 	}
1.594     raeburn  15482: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15483: 	$i++;
                   15484:     }
1.594     raeburn  15485:     $r->print(&end_data_table());
1.31      albertel 15486:     $i--;
                   15487:     return $i;
                   15488: }
1.56      matthew  15489: 
1.144     matthew  15490: ######################################################
                   15491: ######################################################
                   15492: 
1.56      matthew  15493: =pod
1.31      albertel 15494: 
1.648     raeburn  15495: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15496: 
                   15497: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15498: 
                   15499: $r is an Apache Request ref,
                   15500: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15501: $d is an array of 2 element arrays (internal name, displayed name)
                   15502: 
                   15503: =cut
                   15504: 
1.144     matthew  15505: ######################################################
                   15506: ######################################################
1.31      albertel 15507: sub csv_samples_select_table {
                   15508:     my ($r,$records,$d) = @_;
                   15509:     my $i=0;
1.144     matthew  15510:     #
1.662     bisitz   15511:     my $max_samples = 5;
                   15512:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15513:     $r->print(&start_data_table().
                   15514:               &start_data_table_header_row().'<th>'.
                   15515:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15516:               &end_data_table_header_row());
1.301     albertel 15517: 
                   15518:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15519: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15520: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15521: 	foreach my $option (@$d) {
                   15522: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15523: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15524:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15525:                       $display.'</option>');
1.31      albertel 15526: 	}
                   15527: 	$r->print('</select></td><td>');
1.662     bisitz   15528: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15529: 	    if (defined($samples->[$line]{$key})) { 
                   15530: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15531: 	    }
                   15532: 	}
1.594     raeburn  15533: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15534: 	$i++;
                   15535:     }
1.594     raeburn  15536:     $r->print(&end_data_table());
1.31      albertel 15537:     $i--;
                   15538:     return($i);
1.115     matthew  15539: }
                   15540: 
1.144     matthew  15541: ######################################################
                   15542: ######################################################
                   15543: 
1.115     matthew  15544: =pod
                   15545: 
1.648     raeburn  15546: =item * &clean_excel_name($name)
1.115     matthew  15547: 
                   15548: Returns a replacement for $name which does not contain any illegal characters.
                   15549: 
                   15550: =cut
                   15551: 
1.144     matthew  15552: ######################################################
                   15553: ######################################################
1.115     matthew  15554: sub clean_excel_name {
                   15555:     my ($name) = @_;
                   15556:     $name =~ s/[:\*\?\/\\]//g;
                   15557:     if (length($name) > 31) {
                   15558:         $name = substr($name,0,31);
                   15559:     }
                   15560:     return $name;
1.25      albertel 15561: }
1.84      albertel 15562: 
1.85      albertel 15563: =pod
                   15564: 
1.648     raeburn  15565: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15566: 
                   15567: Returns either 1 or undef
                   15568: 
                   15569: 1 if the part is to be hidden, undef if it is to be shown
                   15570: 
                   15571: Arguments are:
                   15572: 
                   15573: $id the id of the part to be checked
                   15574: $symb, optional the symb of the resource to check
                   15575: $udom, optional the domain of the user to check for
                   15576: $uname, optional the username of the user to check for
                   15577: 
                   15578: =cut
1.84      albertel 15579: 
                   15580: sub check_if_partid_hidden {
                   15581:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15582:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15583: 					 $symb,$udom,$uname);
1.141     albertel 15584:     my $truth=1;
                   15585:     #if the string starts with !, then the list is the list to show not hide
                   15586:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15587:     my @hiddenlist=split(/,/,$hiddenparts);
                   15588:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15589: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15590:     }
1.141     albertel 15591:     return !$truth;
1.84      albertel 15592: }
1.127     matthew  15593: 
1.138     matthew  15594: 
                   15595: ############################################################
                   15596: ############################################################
                   15597: 
                   15598: =pod
                   15599: 
1.157     matthew  15600: =back 
                   15601: 
1.138     matthew  15602: =head1 cgi-bin script and graphing routines
                   15603: 
1.157     matthew  15604: =over 4
                   15605: 
1.648     raeburn  15606: =item * &get_cgi_id()
1.138     matthew  15607: 
                   15608: Inputs: none
                   15609: 
                   15610: Returns an id which can be used to pass environment variables
                   15611: to various cgi-bin scripts.  These environment variables will
                   15612: be removed from the users environment after a given time by
                   15613: the routine &Apache::lonnet::transfer_profile_to_env.
                   15614: 
                   15615: =cut
                   15616: 
                   15617: ############################################################
                   15618: ############################################################
1.152     albertel 15619: my $uniq=0;
1.136     matthew  15620: sub get_cgi_id {
1.154     albertel 15621:     $uniq=($uniq+1)%100000;
1.280     albertel 15622:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15623: }
                   15624: 
1.127     matthew  15625: ############################################################
                   15626: ############################################################
                   15627: 
                   15628: =pod
                   15629: 
1.648     raeburn  15630: =item * &DrawBarGraph()
1.127     matthew  15631: 
1.138     matthew  15632: Facilitates the plotting of data in a (stacked) bar graph.
                   15633: Puts plot definition data into the users environment in order for 
                   15634: graph.png to plot it.  Returns an <img> tag for the plot.
                   15635: The bars on the plot are labeled '1','2',...,'n'.
                   15636: 
                   15637: Inputs:
                   15638: 
                   15639: =over 4
                   15640: 
                   15641: =item $Title: string, the title of the plot
                   15642: 
                   15643: =item $xlabel: string, text describing the X-axis of the plot
                   15644: 
                   15645: =item $ylabel: string, text describing the Y-axis of the plot
                   15646: 
                   15647: =item $Max: scalar, the maximum Y value to use in the plot
                   15648: If $Max is < any data point, the graph will not be rendered.
                   15649: 
1.140     matthew  15650: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15651: they are plotted.  If undefined, default values will be used.
                   15652: 
1.178     matthew  15653: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15654: 
1.138     matthew  15655: =item @Values: An array of array references.  Each array reference holds data
                   15656: to be plotted in a stacked bar chart.
                   15657: 
1.239     matthew  15658: =item If the final element of @Values is a hash reference the key/value
                   15659: pairs will be added to the graph definition.
                   15660: 
1.138     matthew  15661: =back
                   15662: 
                   15663: Returns:
                   15664: 
                   15665: An <img> tag which references graph.png and the appropriate identifying
                   15666: information for the plot.
                   15667: 
1.127     matthew  15668: =cut
                   15669: 
                   15670: ############################################################
                   15671: ############################################################
1.134     matthew  15672: sub DrawBarGraph {
1.178     matthew  15673:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15674:     #
                   15675:     if (! defined($colors)) {
                   15676:         $colors = ['#33ff00', 
                   15677:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15678:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15679:                   ]; 
                   15680:     }
1.228     matthew  15681:     my $extra_settings = {};
                   15682:     if (ref($Values[-1]) eq 'HASH') {
                   15683:         $extra_settings = pop(@Values);
                   15684:     }
1.127     matthew  15685:     #
1.136     matthew  15686:     my $identifier = &get_cgi_id();
                   15687:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15688:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15689:         return '';
                   15690:     }
1.225     matthew  15691:     #
                   15692:     my @Labels;
                   15693:     if (defined($labels)) {
                   15694:         @Labels = @$labels;
                   15695:     } else {
                   15696:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15697:             push(@Labels,$i+1);
1.225     matthew  15698:         }
                   15699:     }
                   15700:     #
1.129     matthew  15701:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15702:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15703:     my %ValuesHash;
                   15704:     my $NumSets=1;
                   15705:     foreach my $array (@Values) {
                   15706:         next if (! ref($array));
1.136     matthew  15707:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15708:             join(',',@$array);
1.129     matthew  15709:     }
1.127     matthew  15710:     #
1.136     matthew  15711:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15712:     if ($NumBars < 3) {
                   15713:         $width = 120+$NumBars*32;
1.220     matthew  15714:         $xskip = 1;
1.225     matthew  15715:         $bar_width = 30;
                   15716:     } elsif ($NumBars < 5) {
                   15717:         $width = 120+$NumBars*20;
                   15718:         $xskip = 1;
                   15719:         $bar_width = 20;
1.220     matthew  15720:     } elsif ($NumBars < 10) {
1.136     matthew  15721:         $width = 120+$NumBars*15;
                   15722:         $xskip = 1;
                   15723:         $bar_width = 15;
                   15724:     } elsif ($NumBars <= 25) {
                   15725:         $width = 120+$NumBars*11;
                   15726:         $xskip = 5;
                   15727:         $bar_width = 8;
                   15728:     } elsif ($NumBars <= 50) {
                   15729:         $width = 120+$NumBars*8;
                   15730:         $xskip = 5;
                   15731:         $bar_width = 4;
                   15732:     } else {
                   15733:         $width = 120+$NumBars*8;
                   15734:         $xskip = 5;
                   15735:         $bar_width = 4;
                   15736:     }
                   15737:     #
1.137     matthew  15738:     $Max = 1 if ($Max < 1);
                   15739:     if ( int($Max) < $Max ) {
                   15740:         $Max++;
                   15741:         $Max = int($Max);
                   15742:     }
1.127     matthew  15743:     $Title  = '' if (! defined($Title));
                   15744:     $xlabel = '' if (! defined($xlabel));
                   15745:     $ylabel = '' if (! defined($ylabel));
1.369     www      15746:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15747:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15748:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15749:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15750:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15751:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15752:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15753:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15754:     $ValuesHash{$id.'.height'}   = $height;
                   15755:     $ValuesHash{$id.'.width'}    = $width;
                   15756:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15757:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15758:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15759:     #
1.228     matthew  15760:     # Deal with other parameters
                   15761:     while (my ($key,$value) = each(%$extra_settings)) {
                   15762:         $ValuesHash{$id.'.'.$key} = $value;
                   15763:     }
                   15764:     #
1.646     raeburn  15765:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15766:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15767: }
                   15768: 
                   15769: ############################################################
                   15770: ############################################################
                   15771: 
                   15772: =pod
                   15773: 
1.648     raeburn  15774: =item * &DrawXYGraph()
1.137     matthew  15775: 
1.138     matthew  15776: Facilitates the plotting of data in an XY graph.
                   15777: Puts plot definition data into the users environment in order for 
                   15778: graph.png to plot it.  Returns an <img> tag for the plot.
                   15779: 
                   15780: Inputs:
                   15781: 
                   15782: =over 4
                   15783: 
                   15784: =item $Title: string, the title of the plot
                   15785: 
                   15786: =item $xlabel: string, text describing the X-axis of the plot
                   15787: 
                   15788: =item $ylabel: string, text describing the Y-axis of the plot
                   15789: 
                   15790: =item $Max: scalar, the maximum Y value to use in the plot
                   15791: If $Max is < any data point, the graph will not be rendered.
                   15792: 
                   15793: =item $colors: Array ref containing the hex color codes for the data to be 
                   15794: plotted in.  If undefined, default values will be used.
                   15795: 
                   15796: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15797: 
                   15798: =item $Ydata: Array ref containing Array refs.  
1.185     www      15799: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15800: 
                   15801: =item %Values: hash indicating or overriding any default values which are 
                   15802: passed to graph.png.  
                   15803: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15804: 
                   15805: =back
                   15806: 
                   15807: Returns:
                   15808: 
                   15809: An <img> tag which references graph.png and the appropriate identifying
                   15810: information for the plot.
                   15811: 
1.137     matthew  15812: =cut
                   15813: 
                   15814: ############################################################
                   15815: ############################################################
                   15816: sub DrawXYGraph {
                   15817:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15818:     #
                   15819:     # Create the identifier for the graph
                   15820:     my $identifier = &get_cgi_id();
                   15821:     my $id = 'cgi.'.$identifier;
                   15822:     #
                   15823:     $Title  = '' if (! defined($Title));
                   15824:     $xlabel = '' if (! defined($xlabel));
                   15825:     $ylabel = '' if (! defined($ylabel));
                   15826:     my %ValuesHash = 
                   15827:         (
1.369     www      15828:          $id.'.title'  => &escape($Title),
                   15829:          $id.'.xlabel' => &escape($xlabel),
                   15830:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15831:          $id.'.y_max_value'=> $Max,
                   15832:          $id.'.labels'     => join(',',@$Xlabels),
                   15833:          $id.'.PlotType'   => 'XY',
                   15834:          );
                   15835:     #
                   15836:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15837:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15838:     }
                   15839:     #
                   15840:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15841:         return '';
                   15842:     }
                   15843:     my $NumSets=1;
1.138     matthew  15844:     foreach my $array (@{$Ydata}){
1.137     matthew  15845:         next if (! ref($array));
                   15846:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15847:     }
1.138     matthew  15848:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15849:     #
                   15850:     # Deal with other parameters
                   15851:     while (my ($key,$value) = each(%Values)) {
                   15852:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15853:     }
                   15854:     #
1.646     raeburn  15855:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15856:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15857: }
                   15858: 
                   15859: ############################################################
                   15860: ############################################################
                   15861: 
                   15862: =pod
                   15863: 
1.648     raeburn  15864: =item * &DrawXYYGraph()
1.138     matthew  15865: 
                   15866: Facilitates the plotting of data in an XY graph with two Y axes.
                   15867: Puts plot definition data into the users environment in order for 
                   15868: graph.png to plot it.  Returns an <img> tag for the plot.
                   15869: 
                   15870: Inputs:
                   15871: 
                   15872: =over 4
                   15873: 
                   15874: =item $Title: string, the title of the plot
                   15875: 
                   15876: =item $xlabel: string, text describing the X-axis of the plot
                   15877: 
                   15878: =item $ylabel: string, text describing the Y-axis of the plot
                   15879: 
                   15880: =item $colors: Array ref containing the hex color codes for the data to be 
                   15881: plotted in.  If undefined, default values will be used.
                   15882: 
                   15883: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15884: 
                   15885: =item $Ydata1: The first data set
                   15886: 
                   15887: =item $Min1: The minimum value of the left Y-axis
                   15888: 
                   15889: =item $Max1: The maximum value of the left Y-axis
                   15890: 
                   15891: =item $Ydata2: The second data set
                   15892: 
                   15893: =item $Min2: The minimum value of the right Y-axis
                   15894: 
                   15895: =item $Max2: The maximum value of the left Y-axis
                   15896: 
                   15897: =item %Values: hash indicating or overriding any default values which are 
                   15898: passed to graph.png.  
                   15899: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15900: 
                   15901: =back
                   15902: 
                   15903: Returns:
                   15904: 
                   15905: An <img> tag which references graph.png and the appropriate identifying
                   15906: information for the plot.
1.136     matthew  15907: 
                   15908: =cut
                   15909: 
                   15910: ############################################################
                   15911: ############################################################
1.137     matthew  15912: sub DrawXYYGraph {
                   15913:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15914:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15915:     #
                   15916:     # Create the identifier for the graph
                   15917:     my $identifier = &get_cgi_id();
                   15918:     my $id = 'cgi.'.$identifier;
                   15919:     #
                   15920:     $Title  = '' if (! defined($Title));
                   15921:     $xlabel = '' if (! defined($xlabel));
                   15922:     $ylabel = '' if (! defined($ylabel));
                   15923:     my %ValuesHash = 
                   15924:         (
1.369     www      15925:          $id.'.title'  => &escape($Title),
                   15926:          $id.'.xlabel' => &escape($xlabel),
                   15927:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15928:          $id.'.labels' => join(',',@$Xlabels),
                   15929:          $id.'.PlotType' => 'XY',
                   15930:          $id.'.NumSets' => 2,
1.137     matthew  15931:          $id.'.two_axes' => 1,
                   15932:          $id.'.y1_max_value' => $Max1,
                   15933:          $id.'.y1_min_value' => $Min1,
                   15934:          $id.'.y2_max_value' => $Max2,
                   15935:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15936:          );
                   15937:     #
1.137     matthew  15938:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15939:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15940:     }
                   15941:     #
                   15942:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15943:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15944:         return '';
                   15945:     }
                   15946:     my $NumSets=1;
1.137     matthew  15947:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15948:         next if (! ref($array));
                   15949:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15950:     }
                   15951:     #
                   15952:     # Deal with other parameters
                   15953:     while (my ($key,$value) = each(%Values)) {
                   15954:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15955:     }
                   15956:     #
1.646     raeburn  15957:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15958:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15959: }
                   15960: 
                   15961: ############################################################
                   15962: ############################################################
                   15963: 
                   15964: =pod
                   15965: 
1.157     matthew  15966: =back 
                   15967: 
1.139     matthew  15968: =head1 Statistics helper routines?  
                   15969: 
                   15970: Bad place for them but what the hell.
                   15971: 
1.157     matthew  15972: =over 4
                   15973: 
1.648     raeburn  15974: =item * &chartlink()
1.139     matthew  15975: 
                   15976: Returns a link to the chart for a specific student.  
                   15977: 
                   15978: Inputs:
                   15979: 
                   15980: =over 4
                   15981: 
                   15982: =item $linktext: The text of the link
                   15983: 
                   15984: =item $sname: The students username
                   15985: 
                   15986: =item $sdomain: The students domain
                   15987: 
                   15988: =back
                   15989: 
1.157     matthew  15990: =back
                   15991: 
1.139     matthew  15992: =cut
                   15993: 
                   15994: ############################################################
                   15995: ############################################################
                   15996: sub chartlink {
                   15997:     my ($linktext, $sname, $sdomain) = @_;
                   15998:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15999:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16000:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16001:        '">'.$linktext.'</a>';
1.153     matthew  16002: }
                   16003: 
                   16004: #######################################################
                   16005: #######################################################
                   16006: 
                   16007: =pod
                   16008: 
                   16009: =head1 Course Environment Routines
1.157     matthew  16010: 
                   16011: =over 4
1.153     matthew  16012: 
1.648     raeburn  16013: =item * &restore_course_settings()
1.153     matthew  16014: 
1.648     raeburn  16015: =item * &store_course_settings()
1.153     matthew  16016: 
                   16017: Restores/Store indicated form parameters from the course environment.
                   16018: Will not overwrite existing values of the form parameters.
                   16019: 
                   16020: Inputs: 
                   16021: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16022: 
                   16023: a hash ref describing the data to be stored.  For example:
                   16024:    
                   16025: %Save_Parameters = ('Status' => 'scalar',
                   16026:     'chartoutputmode' => 'scalar',
                   16027:     'chartoutputdata' => 'scalar',
                   16028:     'Section' => 'array',
1.373     raeburn  16029:     'Group' => 'array',
1.153     matthew  16030:     'StudentData' => 'array',
                   16031:     'Maps' => 'array');
                   16032: 
                   16033: Returns: both routines return nothing
                   16034: 
1.631     raeburn  16035: =back
                   16036: 
1.153     matthew  16037: =cut
                   16038: 
                   16039: #######################################################
                   16040: #######################################################
                   16041: sub store_course_settings {
1.496     albertel 16042:     return &store_settings($env{'request.course.id'},@_);
                   16043: }
                   16044: 
                   16045: sub store_settings {
1.153     matthew  16046:     # save to the environment
                   16047:     # appenv the same items, just to be safe
1.300     albertel 16048:     my $udom  = $env{'user.domain'};
                   16049:     my $uname = $env{'user.name'};
1.496     albertel 16050:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16051:     my %SaveHash;
                   16052:     my %AppHash;
                   16053:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16054:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16055:         my $envname = 'environment.'.$basename;
1.258     albertel 16056:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16057:             # Save this value away
                   16058:             if ($type eq 'scalar' &&
1.258     albertel 16059:                 (! exists($env{$envname}) || 
                   16060:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16061:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16062:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16063:             } elsif ($type eq 'array') {
                   16064:                 my $stored_form;
1.258     albertel 16065:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16066:                     $stored_form = join(',',
                   16067:                                         map {
1.369     www      16068:                                             &escape($_);
1.258     albertel 16069:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16070:                 } else {
                   16071:                     $stored_form = 
1.369     www      16072:                         &escape($env{'form.'.$setting});
1.153     matthew  16073:                 }
                   16074:                 # Determine if the array contents are the same.
1.258     albertel 16075:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16076:                     $SaveHash{$basename} = $stored_form;
                   16077:                     $AppHash{$envname}   = $stored_form;
                   16078:                 }
                   16079:             }
                   16080:         }
                   16081:     }
                   16082:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16083:                                           $udom,$uname);
1.153     matthew  16084:     if ($put_result !~ /^(ok|delayed)/) {
                   16085:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16086:                                  'got error:'.$put_result);
                   16087:     }
                   16088:     # Make sure these settings stick around in this session, too
1.646     raeburn  16089:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16090:     return;
                   16091: }
                   16092: 
                   16093: sub restore_course_settings {
1.499     albertel 16094:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16095: }
                   16096: 
                   16097: sub restore_settings {
                   16098:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16099:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16100:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16101:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16102:             '.'.$setting;
1.258     albertel 16103:         if (exists($env{$envname})) {
1.153     matthew  16104:             if ($type eq 'scalar') {
1.258     albertel 16105:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16106:             } elsif ($type eq 'array') {
1.258     albertel 16107:                 $env{'form.'.$setting} = [ 
1.153     matthew  16108:                                            map { 
1.369     www      16109:                                                &unescape($_); 
1.258     albertel 16110:                                            } split(',',$env{$envname})
1.153     matthew  16111:                                            ];
                   16112:             }
                   16113:         }
                   16114:     }
1.127     matthew  16115: }
                   16116: 
1.618     raeburn  16117: #######################################################
                   16118: #######################################################
                   16119: 
                   16120: =pod
                   16121: 
                   16122: =head1 Domain E-mail Routines  
                   16123: 
                   16124: =over 4
                   16125: 
1.648     raeburn  16126: =item * &build_recipient_list()
1.618     raeburn  16127: 
1.1144    raeburn  16128: Build recipient lists for following types of e-mail:
1.766     raeburn  16129: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16130: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16131: module change checking, student/employee ID conflict checks, as
                   16132: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16133: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16134: 
                   16135: Inputs:
1.619     raeburn  16136: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16137: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16138: requestsmail, updatesmail, or idconflictsmail).
                   16139: 
1.619     raeburn  16140: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16141: 
1.619     raeburn  16142: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16143: i.e., predates configuration by DC via domainprefs.pm
                   16144: 
                   16145: $requname username of requester (if mailing type is helpdeskmail)
                   16146: 
                   16147: $requdom domain of requester (if mailing type is helpdeskmail)
                   16148: 
                   16149: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16150: 
1.618     raeburn  16151: 
1.655     raeburn  16152: Returns: comma separated list of addresses to which to send e-mail.
                   16153: 
                   16154: =back
1.618     raeburn  16155: 
                   16156: =cut
                   16157: 
                   16158: ############################################################
                   16159: ############################################################
                   16160: sub build_recipient_list {
1.1297    raeburn  16161:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16162:     my @recipients;
1.1270    raeburn  16163:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16164:     my %domconfig =
1.1270    raeburn  16165:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16166:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16167:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16168:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16169:                 my @contacts = ('adminemail','supportemail');
                   16170:                 foreach my $item (@contacts) {
                   16171:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16172:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16173:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16174:                             push(@recipients,$addr);
                   16175:                         }
1.619     raeburn  16176:                     }
1.1270    raeburn  16177:                 }
                   16178:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16179:                 if ($mailing eq 'helpdeskmail') {
                   16180:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16181:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16182:                         my @ok_bccs;
                   16183:                         foreach my $bcc (@bccs) {
                   16184:                             $bcc =~ s/^\s+//g;
                   16185:                             $bcc =~ s/\s+$//g;
                   16186:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16187:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16188:                                     push(@ok_bccs,$bcc);
                   16189:                                 }
                   16190:                             }
                   16191:                         }
                   16192:                         if (@ok_bccs > 0) {
                   16193:                             $allbcc = join(', ',@ok_bccs);
                   16194:                         }
                   16195:                     }
                   16196:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16197:                 }
                   16198:             }
1.766     raeburn  16199:         } elsif ($origmail ne '') {
1.1270    raeburn  16200:             $lastresort = $origmail;
1.618     raeburn  16201:         }
1.1297    raeburn  16202:         if ($mailing eq 'helpdeskmail') {
                   16203:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16204:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16205:                 my ($inststatus,$inststatus_checked);
                   16206:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16207:                     ($env{'user.domain'} ne 'public')) {
                   16208:                     $inststatus_checked = 1;
                   16209:                     $inststatus = $env{'environment.inststatus'};
                   16210:                 }
                   16211:                 unless ($inststatus_checked) {
                   16212:                     if (($requname ne '') && ($requdom ne '')) {
                   16213:                         if (($requname =~ /^$match_username$/) &&
                   16214:                             ($requdom =~ /^$match_domain$/) &&
                   16215:                             (&Apache::lonnet::domain($requdom))) {
                   16216:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16217:                                                                       $requdom);
                   16218:                             unless ($requhome eq 'no_host') {
                   16219:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16220:                                 $inststatus = $userenv{'inststatus'};
                   16221:                                 $inststatus_checked = 1;
                   16222:                             }
                   16223:                         }
                   16224:                     }
                   16225:                 }
                   16226:                 unless ($inststatus_checked) {
                   16227:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16228:                         my %srch = (srchby     => 'email',
                   16229:                                     srchdomain => $defdom,
                   16230:                                     srchterm   => $reqemail,
                   16231:                                     srchtype   => 'exact');
                   16232:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16233:                         foreach my $uname (keys(%srch_results)) {
                   16234:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16235:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16236:                                 $inststatus_checked = 1;
                   16237:                                 last;
                   16238:                             }
                   16239:                         }
                   16240:                         unless ($inststatus_checked) {
                   16241:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16242:                             if ($dirsrchres eq 'ok') {
                   16243:                                 foreach my $uname (keys(%srch_results)) {
                   16244:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16245:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16246:                                         $inststatus_checked = 1;
                   16247:                                         last;
                   16248:                                     }
                   16249:                                 }
                   16250:                             }
                   16251:                         }
                   16252:                     }
                   16253:                 }
                   16254:                 if ($inststatus ne '') {
                   16255:                     foreach my $status (split(/\:/,$inststatus)) {
                   16256:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16257:                             my @contacts = ('adminemail','supportemail');
                   16258:                             foreach my $item (@contacts) {
                   16259:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16260:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16261:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16262:                                         push(@recipients,$addr);
                   16263:                                     }
                   16264:                                 }
                   16265:                             }
                   16266:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16267:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16268:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16269:                                 my @ok_bccs;
                   16270:                                 foreach my $bcc (@bccs) {
                   16271:                                     $bcc =~ s/^\s+//g;
                   16272:                                     $bcc =~ s/\s+$//g;
                   16273:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16274:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16275:                                             push(@ok_bccs,$bcc);
                   16276:                                         }
                   16277:                                     }
                   16278:                                 }
                   16279:                                 if (@ok_bccs > 0) {
                   16280:                                     $allbcc = join(', ',@ok_bccs);
                   16281:                                 }
                   16282:                             }
                   16283:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16284:                             last;
                   16285:                         }
                   16286:                     }
                   16287:                 }
                   16288:             }
                   16289:         }
1.619     raeburn  16290:     } elsif ($origmail ne '') {
1.1270    raeburn  16291:         $lastresort = $origmail;
                   16292:     }
1.1297    raeburn  16293:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16294:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16295:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16296:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16297:             my %what = (
                   16298:                           perlvar => 1,
                   16299:                        );
                   16300:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16301:             if ($primary) {
                   16302:                 my $gotaddr;
                   16303:                 my ($result,$returnhash) =
                   16304:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16305:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16306:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16307:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16308:                         $gotaddr = 1;
                   16309:                     }
                   16310:                 }
                   16311:                 unless ($gotaddr) {
                   16312:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16313:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16314:                     unless ($uintdom eq $intdom) {
                   16315:                         my %domconfig =
                   16316:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16317:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16318:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16319:                                 my @contacts = ('adminemail','supportemail');
                   16320:                                 foreach my $item (@contacts) {
                   16321:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16322:                                         my $addr = $domconfig{'contacts'}{$item};
                   16323:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16324:                                             push(@recipients,$addr);
                   16325:                                         }
                   16326:                                     }
                   16327:                                 }
                   16328:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16329:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16330:                                 }
                   16331:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16332:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16333:                                     my @ok_bccs;
                   16334:                                     foreach my $bcc (@bccs) {
                   16335:                                         $bcc =~ s/^\s+//g;
                   16336:                                         $bcc =~ s/\s+$//g;
                   16337:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16338:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16339:                                                 push(@ok_bccs,$bcc);
                   16340:                                             }
                   16341:                                         }
                   16342:                                     }
                   16343:                                     if (@ok_bccs > 0) {
                   16344:                                         $allbcc = join(', ',@ok_bccs);
                   16345:                                     }
                   16346:                                 }
                   16347:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16348:                             }
                   16349:                         }
                   16350:                     }
                   16351:                 }
                   16352:             }
                   16353:         }
1.618     raeburn  16354:     }
1.688     raeburn  16355:     if (defined($defmail)) {
                   16356:         if ($defmail ne '') {
                   16357:             push(@recipients,$defmail);
                   16358:         }
1.618     raeburn  16359:     }
                   16360:     if ($otheremails) {
1.619     raeburn  16361:         my @others;
                   16362:         if ($otheremails =~ /,/) {
                   16363:             @others = split(/,/,$otheremails);
1.618     raeburn  16364:         } else {
1.619     raeburn  16365:             push(@others,$otheremails);
                   16366:         }
                   16367:         foreach my $addr (@others) {
                   16368:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16369:                 push(@recipients,$addr);
                   16370:             }
1.618     raeburn  16371:         }
                   16372:     }
1.1298    raeburn  16373:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16374:         if ((!@recipients) && ($lastresort ne '')) {
                   16375:             push(@recipients,$lastresort);
                   16376:         }
                   16377:     } elsif ($lastresort ne '') {
                   16378:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16379:             push(@recipients,$lastresort);
                   16380:         }
                   16381:     }
1.1271    raeburn  16382:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16383:     if (wantarray) {
                   16384:         return ($recipientlist,$allbcc,$addtext);
                   16385:     } else {
                   16386:         return $recipientlist;
                   16387:     }
1.618     raeburn  16388: }
                   16389: 
1.127     matthew  16390: ############################################################
                   16391: ############################################################
1.154     albertel 16392: 
1.655     raeburn  16393: =pod
                   16394: 
1.1224    musolffc 16395: =over 4
                   16396: 
1.1223    musolffc 16397: =item * &mime_email()
                   16398: 
                   16399: Sends an email with a possible attachment
                   16400: 
                   16401: Inputs:
                   16402: 
                   16403: =over 4
                   16404: 
                   16405: from -              Sender's email address
                   16406: 
1.1343    raeburn  16407: replyto -           Reply-To email address
                   16408: 
1.1223    musolffc 16409: to -                Email address of recipient
                   16410: 
                   16411: subject -           Subject of email
                   16412: 
                   16413: body -              Body of email
                   16414: 
                   16415: cc_string -         Carbon copy email address
                   16416: 
                   16417: bcc -               Blind carbon copy email address
                   16418: 
                   16419: attachment_path -   Path of file to be attached
                   16420: 
                   16421: file_name -         Name of file to be attached
                   16422: 
                   16423: attachment_text -   The body of an attachment of type "TEXT"
                   16424: 
                   16425: =back
                   16426: 
                   16427: =back
                   16428: 
                   16429: =cut
                   16430: 
                   16431: ############################################################
                   16432: ############################################################
                   16433: 
                   16434: sub mime_email {
1.1343    raeburn  16435:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16436:         $file_name,$attachment_text) = @_;
                   16437:  
1.1223    musolffc 16438:     my $msg = MIME::Lite->new(
                   16439:              From    => $from,
                   16440:              To      => $to,
                   16441:              Subject => $subject,
                   16442:              Type    =>'TEXT',
                   16443:              Data    => $body,
                   16444:              );
1.1343    raeburn  16445:     if ($replyto ne '') {
                   16446:         $msg->add("Reply-To" => $replyto);
                   16447:     }
1.1223    musolffc 16448:     if ($cc_string ne '') {
                   16449:         $msg->add("Cc" => $cc_string);
                   16450:     }
                   16451:     if ($bcc ne '') {
                   16452:         $msg->add("Bcc" => $bcc);
                   16453:     }
                   16454:     $msg->attr("content-type"         => "text/plain");
                   16455:     $msg->attr("content-type.charset" => "UTF-8");
                   16456:     # Attach file if given
                   16457:     if ($attachment_path) {
                   16458:         unless ($file_name) {
                   16459:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16460:         }
                   16461:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16462:         $msg->attach(Type     => $type,
                   16463:                      Path     => $attachment_path,
                   16464:                      Filename => $file_name
                   16465:                      );
                   16466:     # Otherwise attach text if given
                   16467:     } elsif ($attachment_text) {
                   16468:         $msg->attach(Type => 'TEXT',
                   16469:                      Data => $attachment_text);
                   16470:     }
                   16471:     # Send it
                   16472:     $msg->send('sendmail');
                   16473: }
                   16474: 
                   16475: ############################################################
                   16476: ############################################################
                   16477: 
                   16478: =pod
                   16479: 
1.655     raeburn  16480: =head1 Course Catalog Routines
                   16481: 
                   16482: =over 4
                   16483: 
                   16484: =item * &gather_categories()
                   16485: 
                   16486: Converts category definitions - keys of categories hash stored in  
                   16487: coursecategories in configuration.db on the primary library server in a 
                   16488: domain - to an array.  Also generates javascript and idx hash used to 
                   16489: generate Domain Coordinator interface for editing Course Categories.
                   16490: 
                   16491: Inputs:
1.663     raeburn  16492: 
1.655     raeburn  16493: categories (reference to hash of category definitions).
1.663     raeburn  16494: 
1.655     raeburn  16495: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16496:       categories and subcategories).
1.663     raeburn  16497: 
1.655     raeburn  16498: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16499:       editing Course Categories).
1.663     raeburn  16500: 
1.655     raeburn  16501: jsarray (reference to array of categories used to create Javascript arrays for
                   16502:          Domain Coordinator interface for editing Course Categories).
                   16503: 
                   16504: Returns: nothing
                   16505: 
                   16506: Side effects: populates cats, idx and jsarray. 
                   16507: 
                   16508: =cut
                   16509: 
                   16510: sub gather_categories {
                   16511:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16512:     my %counters;
                   16513:     my $num = 0;
                   16514:     foreach my $item (keys(%{$categories})) {
                   16515:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16516:         if ($container eq '' && $depth == 0) {
                   16517:             $cats->[$depth][$categories->{$item}] = $cat;
                   16518:         } else {
                   16519:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16520:         }
                   16521:         my ($escitem,$tail) = split(/:/,$item,2);
                   16522:         if ($counters{$tail} eq '') {
                   16523:             $counters{$tail} = $num;
                   16524:             $num ++;
                   16525:         }
                   16526:         if (ref($idx) eq 'HASH') {
                   16527:             $idx->{$item} = $counters{$tail};
                   16528:         }
                   16529:         if (ref($jsarray) eq 'ARRAY') {
                   16530:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16531:         }
                   16532:     }
                   16533:     return;
                   16534: }
                   16535: 
                   16536: =pod
                   16537: 
                   16538: =item * &extract_categories()
                   16539: 
                   16540: Used to generate breadcrumb trails for course categories.
                   16541: 
                   16542: Inputs:
1.663     raeburn  16543: 
1.655     raeburn  16544: categories (reference to hash of category definitions).
1.663     raeburn  16545: 
1.655     raeburn  16546: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16547:       categories and subcategories).
1.663     raeburn  16548: 
1.655     raeburn  16549: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16550: 
1.655     raeburn  16551: allitems (reference to hash - key is category key 
                   16552:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16553: 
1.655     raeburn  16554: idx (reference to hash of counters used in Domain Coordinator interface for
                   16555:       editing Course Categories).
1.663     raeburn  16556: 
1.655     raeburn  16557: jsarray (reference to array of categories used to create Javascript arrays for
                   16558:          Domain Coordinator interface for editing Course Categories).
                   16559: 
1.665     raeburn  16560: subcats (reference to hash of arrays containing all subcategories within each 
                   16561:          category, -recursive)
                   16562: 
1.1321    raeburn  16563: maxd (reference to hash used to hold max depth for all top-level categories).
                   16564: 
1.655     raeburn  16565: Returns: nothing
                   16566: 
                   16567: Side effects: populates trails and allitems hash references.
                   16568: 
                   16569: =cut
                   16570: 
                   16571: sub extract_categories {
1.1321    raeburn  16572:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16573:     if (ref($categories) eq 'HASH') {
                   16574:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16575:         if (ref($cats->[0]) eq 'ARRAY') {
                   16576:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16577:                 my $name = $cats->[0][$i];
                   16578:                 my $item = &escape($name).'::0';
                   16579:                 my $trailstr;
                   16580:                 if ($name eq 'instcode') {
                   16581:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16582:                 } elsif ($name eq 'communities') {
                   16583:                     $trailstr = &mt('Communities');
1.1239    raeburn  16584:                 } elsif ($name eq 'placement') {
                   16585:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16586:                 } else {
                   16587:                     $trailstr = $name;
                   16588:                 }
                   16589:                 if ($allitems->{$item} eq '') {
                   16590:                     push(@{$trails},$trailstr);
                   16591:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16592:                 }
                   16593:                 my @parents = ($name);
                   16594:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16595:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16596:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16597:                         if (ref($subcats) eq 'HASH') {
                   16598:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16599:                         }
1.1321    raeburn  16600:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16601:                     }
                   16602:                 } else {
                   16603:                     if (ref($subcats) eq 'HASH') {
                   16604:                         $subcats->{$item} = [];
1.655     raeburn  16605:                     }
1.1321    raeburn  16606:                     if (ref($maxd) eq 'HASH') {
                   16607:                         $maxd->{$name} = 1;
                   16608:                     }
1.655     raeburn  16609:                 }
                   16610:             }
                   16611:         }
                   16612:     }
                   16613:     return;
                   16614: }
                   16615: 
                   16616: =pod
                   16617: 
1.1162    raeburn  16618: =item * &recurse_categories()
1.655     raeburn  16619: 
                   16620: Recursively used to generate breadcrumb trails for course categories.
                   16621: 
                   16622: Inputs:
1.663     raeburn  16623: 
1.655     raeburn  16624: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16625:       categories and subcategories).
1.663     raeburn  16626: 
1.655     raeburn  16627: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16628: 
                   16629: category (current course category, for which breadcrumb trail is being generated).
                   16630: 
                   16631: trails (reference to array of breadcrumb trails for each category).
                   16632: 
1.655     raeburn  16633: allitems (reference to hash - key is category key
                   16634:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16635: 
1.655     raeburn  16636: parents (array containing containers directories for current category, 
                   16637:          back to top level). 
                   16638: 
                   16639: Returns: nothing
                   16640: 
                   16641: Side effects: populates trails and allitems hash references
                   16642: 
                   16643: =cut
                   16644: 
                   16645: sub recurse_categories {
1.1321    raeburn  16646:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16647:     my $shallower = $depth - 1;
                   16648:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16649:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16650:             my $name = $cats->[$depth]{$category}[$k];
                   16651:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16652:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16653:             if ($allitems->{$item} eq '') {
                   16654:                 push(@{$trails},$trailstr);
                   16655:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16656:             }
                   16657:             my $deeper = $depth+1;
                   16658:             push(@{$parents},$category);
1.665     raeburn  16659:             if (ref($subcats) eq 'HASH') {
                   16660:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16661:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16662:                     my $higher;
                   16663:                     if ($j > 0) {
                   16664:                         $higher = &escape($parents->[$j]).':'.
                   16665:                                   &escape($parents->[$j-1]).':'.$j;
                   16666:                     } else {
                   16667:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16668:                     }
                   16669:                     push(@{$subcats->{$higher}},$subcat);
                   16670:                 }
                   16671:             }
                   16672:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16673:                                 $subcats,$maxd);
1.655     raeburn  16674:             pop(@{$parents});
                   16675:         }
                   16676:     } else {
                   16677:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16678:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16679:         if ($allitems->{$item} eq '') {
                   16680:             push(@{$trails},$trailstr);
                   16681:             $allitems->{$item} = scalar(@{$trails})-1;
                   16682:         }
1.1321    raeburn  16683:         if (ref($maxd) eq 'HASH') {
                   16684:             if ($depth > $maxd->{$parents->[0]}) {
                   16685:                 $maxd->{$parents->[0]} = $depth;
                   16686:             }
                   16687:         }
1.655     raeburn  16688:     }
                   16689:     return;
                   16690: }
                   16691: 
1.663     raeburn  16692: =pod
                   16693: 
1.1162    raeburn  16694: =item * &assign_categories_table()
1.663     raeburn  16695: 
                   16696: Create a datatable for display of hierarchical categories in a domain,
                   16697: with checkboxes to allow a course to be categorized. 
                   16698: 
                   16699: Inputs:
                   16700: 
                   16701: cathash - reference to hash of categories defined for the domain (from
                   16702:           configuration.db)
                   16703: 
                   16704: currcat - scalar with an & separated list of categories assigned to a course. 
                   16705: 
1.919     raeburn  16706: type    - scalar contains course type (Course or Community).
                   16707: 
1.1260    raeburn  16708: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16709:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16710: 
1.663     raeburn  16711: Returns: $output (markup to be displayed) 
                   16712: 
                   16713: =cut
                   16714: 
                   16715: sub assign_categories_table {
1.1259    raeburn  16716:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16717:     my $output;
                   16718:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16719:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16720:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16721:         $maxdepth = scalar(@cats);
                   16722:         if (@cats > 0) {
                   16723:             my $itemcount = 0;
                   16724:             if (ref($cats[0]) eq 'ARRAY') {
                   16725:                 my @currcategories;
                   16726:                 if ($currcat ne '') {
                   16727:                     @currcategories = split('&',$currcat);
                   16728:                 }
1.919     raeburn  16729:                 my $table;
1.663     raeburn  16730:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16731:                     my $parent = $cats[0][$i];
1.919     raeburn  16732:                     next if ($parent eq 'instcode');
                   16733:                     if ($type eq 'Community') {
                   16734:                         next unless ($parent eq 'communities');
1.1239    raeburn  16735:                     } elsif ($type eq 'Placement') {
                   16736:                         next unless ($parent eq 'placement');
1.919     raeburn  16737:                     } else {
1.1239    raeburn  16738:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16739:                     }
1.663     raeburn  16740:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16741:                     my $item = &escape($parent).'::0';
                   16742:                     my $checked = '';
                   16743:                     if (@currcategories > 0) {
                   16744:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16745:                             $checked = ' checked="checked"';
1.663     raeburn  16746:                         }
                   16747:                     }
1.919     raeburn  16748:                     my $parent_title = $parent;
                   16749:                     if ($parent eq 'communities') {
                   16750:                         $parent_title = &mt('Communities');
1.1239    raeburn  16751:                     } elsif ($parent eq 'placement') {
                   16752:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16753:                     }
                   16754:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16755:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16756:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16757:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16758:                     my $depth = 1;
                   16759:                     push(@path,$parent);
1.1259    raeburn  16760:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16761:                     pop(@path);
1.919     raeburn  16762:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16763:                     $itemcount ++;
                   16764:                 }
1.919     raeburn  16765:                 if ($itemcount) {
                   16766:                     $output = &Apache::loncommon::start_data_table().
                   16767:                               $table.
                   16768:                               &Apache::loncommon::end_data_table();
                   16769:                 }
1.663     raeburn  16770:             }
                   16771:         }
                   16772:     }
                   16773:     return $output;
                   16774: }
                   16775: 
                   16776: =pod
                   16777: 
1.1162    raeburn  16778: =item * &assign_category_rows()
1.663     raeburn  16779: 
                   16780: Create a datatable row for display of nested categories in a domain,
                   16781: with checkboxes to allow a course to be categorized,called recursively.
                   16782: 
                   16783: Inputs:
                   16784: 
                   16785: itemcount - track row number for alternating colors
                   16786: 
                   16787: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16788:       categories and subcategories.
                   16789: 
                   16790: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16791: 
                   16792: parent - parent of current category item
                   16793: 
                   16794: path - Array containing all categories back up through the hierarchy from the
                   16795:        current category to the top level.
                   16796: 
                   16797: currcategories - reference to array of current categories assigned to the course
                   16798: 
1.1260    raeburn  16799: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16800:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16801: 
1.663     raeburn  16802: Returns: $output (markup to be displayed).
                   16803: 
                   16804: =cut
                   16805: 
                   16806: sub assign_category_rows {
1.1259    raeburn  16807:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16808:     my ($text,$name,$item,$chgstr);
                   16809:     if (ref($cats) eq 'ARRAY') {
                   16810:         my $maxdepth = scalar(@{$cats});
                   16811:         if (ref($cats->[$depth]) eq 'HASH') {
                   16812:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16813:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16814:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16815:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16816:                 for (my $j=0; $j<$numchildren; $j++) {
                   16817:                     $name = $cats->[$depth]{$parent}[$j];
                   16818:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16819:                     my $deeper = $depth+1;
                   16820:                     my $checked = '';
                   16821:                     if (ref($currcategories) eq 'ARRAY') {
                   16822:                         if (@{$currcategories} > 0) {
                   16823:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16824:                                 $checked = ' checked="checked"';
1.663     raeburn  16825:                             }
                   16826:                         }
                   16827:                     }
1.664     raeburn  16828:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16829:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16830:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16831:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16832:                              '</td><td>';
1.663     raeburn  16833:                     if (ref($path) eq 'ARRAY') {
                   16834:                         push(@{$path},$name);
1.1259    raeburn  16835:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16836:                         pop(@{$path});
                   16837:                     }
                   16838:                     $text .= '</td></tr>';
                   16839:                 }
                   16840:                 $text .= '</table></td>';
                   16841:             }
                   16842:         }
                   16843:     }
                   16844:     return $text;
                   16845: }
                   16846: 
1.1181    raeburn  16847: =pod
                   16848: 
                   16849: =back
                   16850: 
                   16851: =cut
                   16852: 
1.655     raeburn  16853: ############################################################
                   16854: ############################################################
                   16855: 
                   16856: 
1.443     albertel 16857: sub commit_customrole {
1.1408    raeburn  16858:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  16859:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  16860:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   16861:                      $context,$othdomby,$requester);
1.630     raeburn  16862:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16863:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  16864:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   16865:     if (wantarray) {
                   16866:         return ($output,$result);
                   16867:     } else {
                   16868:         return $output;
                   16869:     }
1.443     albertel 16870: }
                   16871: 
                   16872: sub commit_standardrole {
1.1408    raeburn  16873:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   16874:         $othdomby,$requester) = @_;
1.1399    raeburn  16875:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  16876:     if ($context eq 'auto') {
                   16877:         $linefeed = "\n";
                   16878:     } else {
                   16879:         $linefeed = "<br />\n";
                   16880:     }  
1.443     albertel 16881:     if ($three eq 'st') {
1.1399    raeburn  16882:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  16883:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   16884:                                       $requester);
1.541     raeburn  16885:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16886:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16887:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16888:         } else {
1.541     raeburn  16889:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16890:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16891:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16892:             if ($context eq 'auto') {
                   16893:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16894:             } else {
                   16895:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16896:                &mt('Add to classlist').': <b>ok</b>';
                   16897:             }
                   16898:             $output .= $linefeed;
1.443     albertel 16899:         }
                   16900:     } else {
                   16901:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16902:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16903:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  16904:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   16905:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  16906:         if ($context eq 'auto') {
                   16907:             $output .= $result.$linefeed;
                   16908:         } else {
                   16909:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16910:         }
1.443     albertel 16911:     }
1.1399    raeburn  16912:     if (wantarray) {
                   16913:         return ($output,$result);
                   16914:     } else {
                   16915:         return $output;
                   16916:     }
1.443     albertel 16917: }
                   16918: 
                   16919: sub commit_studentrole {
1.1116    raeburn  16920:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  16921:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  16922:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16923:     if ($context eq 'auto') {
                   16924:         $linefeed = "\n";
                   16925:     } else {
                   16926:         $linefeed = '<br />'."\n";
                   16927:     }
1.443     albertel 16928:     if (defined($one) && defined($two)) {
                   16929:         my $cid=$one.'_'.$two;
                   16930:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16931:         my $secchange = 0;
                   16932:         my $expire_role_result;
                   16933:         my $modify_section_result;
1.628     raeburn  16934:         if ($oldsec ne '-1') { 
                   16935:             if ($oldsec ne $sec) {
1.443     albertel 16936:                 $secchange = 1;
1.628     raeburn  16937:                 my $now = time;
1.443     albertel 16938:                 my $uurl='/'.$cid;
                   16939:                 $uurl=~s/\_/\//g;
                   16940:                 if ($oldsec) {
                   16941:                     $uurl.='/'.$oldsec;
                   16942:                 }
1.626     raeburn  16943:                 $oldsecurl = $uurl;
1.628     raeburn  16944:                 $expire_role_result = 
1.1408    raeburn  16945:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   16946:                                                 '','','',$context,$othdomby,$requester);
                   16947:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  16948:                     if ($expire_role_result eq 'refused') {
                   16949:                         my @roles = ('st');
                   16950:                         my @statuses = ('previous');
                   16951:                         my @roledoms = ($one);
                   16952:                         my $withsec = 1;
                   16953:                         my %roleshash = 
                   16954:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16955:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16956:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16957:                             my ($oldstart,$oldend) = 
                   16958:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16959:                             if ($oldend > 0 && $oldend <= $now) {
                   16960:                                 $expire_role_result = 'ok';
                   16961:                             }
                   16962:                         }
                   16963:                     }
                   16964:                 }
1.443     albertel 16965:                 $result = $expire_role_result;
                   16966:             }
                   16967:         }
                   16968:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16969:             $modify_section_result = 
                   16970:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16971:                                                            undef,undef,undef,$sec,
                   16972:                                                            $end,$start,'','',$cid,
1.1408    raeburn  16973:                                                            '',$context,$credits,'',
                   16974:                                                            $othdomby,$requester);
1.443     albertel 16975:             if ($modify_section_result =~ /^ok/) {
                   16976:                 if ($secchange == 1) {
1.628     raeburn  16977:                     if ($sec eq '') {
                   16978:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16979:                     } else {
                   16980:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16981:                     }
1.443     albertel 16982:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16983:                     if ($sec eq '') {
                   16984:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16985:                     } else {
                   16986:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16987:                     }
1.443     albertel 16988:                 } else {
1.628     raeburn  16989:                     if ($sec eq '') {
                   16990:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16991:                     } else {
                   16992:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16993:                     }
1.443     albertel 16994:                 }
                   16995:             } else {
1.1115    raeburn  16996:                 if ($secchange) { 
1.628     raeburn  16997:                     $$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;
                   16998:                 } else {
                   16999:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17000:                 }
1.443     albertel 17001:             }
                   17002:             $result = $modify_section_result;
                   17003:         } elsif ($secchange == 1) {
1.628     raeburn  17004:             if ($oldsec eq '') {
1.1103    raeburn  17005:                 $$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  17006:             } else {
                   17007:                 $$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;
                   17008:             }
1.626     raeburn  17009:             if ($expire_role_result eq 'refused') {
                   17010:                 my $newsecurl = '/'.$cid;
                   17011:                 $newsecurl =~ s/\_/\//g;
                   17012:                 if ($sec ne '') {
                   17013:                     $newsecurl.='/'.$sec;
                   17014:                 }
                   17015:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17016:                     if ($sec eq '') {
                   17017:                         $$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;
                   17018:                     } else {
                   17019:                         $$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;
                   17020:                     }
                   17021:                 }
                   17022:             }
1.443     albertel 17023:         }
                   17024:     } else {
1.626     raeburn  17025:         $$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 17026:         $result = "error: incomplete course id\n";
                   17027:     }
                   17028:     return $result;
                   17029: }
                   17030: 
1.1108    raeburn  17031: sub show_role_extent {
                   17032:     my ($scope,$context,$role) = @_;
                   17033:     $scope =~ s{^/}{};
                   17034:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17035:     push(@courseroles,'co');
                   17036:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17037:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17038:         $scope =~ s{/}{_};
                   17039:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17040:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17041:         my ($audom,$auname) = split(/\//,$scope);
                   17042:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17043:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17044:     } else {
                   17045:         $scope =~ s{/$}{};
                   17046:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17047:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17048:     }
                   17049: }
                   17050: 
1.443     albertel 17051: ############################################################
                   17052: ############################################################
                   17053: 
1.566     albertel 17054: sub check_clone {
1.578     raeburn  17055:     my ($args,$linefeed) = @_;
1.566     albertel 17056:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17057:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17058:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17059:     my $clonetitle;
                   17060:     my @clonemsg;
1.566     albertel 17061:     my $can_clone = 0;
1.944     raeburn  17062:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17063:     if ($lctype ne 'community') {
                   17064:         $lctype = 'course';
                   17065:     }
1.566     albertel 17066:     if ($clonehome eq 'no_host') {
1.944     raeburn  17067:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17068:             push(@clonemsg,({
                   17069:                               mt => 'No new community created.',
                   17070:                               args => [],
                   17071:                             },
                   17072:                             {
                   17073:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17074:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17075:                             }));
1.908     raeburn  17076:         } else {
1.1344    raeburn  17077:             push(@clonemsg,({
                   17078:                               mt => 'No new course created.',
                   17079:                               args => [],
                   17080:                             },
                   17081:                             {
                   17082:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17083:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17084:                             }));
                   17085:         }
1.566     albertel 17086:     } else {
                   17087: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17088:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17089:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17090:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17091:                 push(@clonemsg,({
                   17092:                                   mt => 'No new community created.',
                   17093:                                   args => [],
                   17094:                                 },
                   17095:                                 {
                   17096:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17097:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17098:                                 }));
                   17099:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17100:             }
                   17101:         }
1.1262    raeburn  17102: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17103:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17104: 	    $can_clone = 1;
                   17105: 	} else {
1.1221    raeburn  17106: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17107: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17108:             if ($clonehash{'cloners'} eq '') {
                   17109:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17110:                 if ($domdefs{'canclone'}) {
                   17111:                     unless ($domdefs{'canclone'} eq 'none') {
                   17112:                         if ($domdefs{'canclone'} eq 'domain') {
                   17113:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17114:                                 $can_clone = 1;
                   17115:                             }
                   17116:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17117:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17118:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17119:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17120:                                 $can_clone = 1;
                   17121:                             }
                   17122:                         }
                   17123:                     }
                   17124:                 }
1.578     raeburn  17125:             } else {
1.1221    raeburn  17126: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17127:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17128:                     $can_clone = 1;
1.1221    raeburn  17129:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17130:                     $can_clone = 1;
1.1225    raeburn  17131:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17132:                     $can_clone = 1;
1.1221    raeburn  17133:                 }
                   17134:                 unless ($can_clone) {
1.1225    raeburn  17135:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17136:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17137:                         my (%gotdomdefaults,%gotcodedefaults);
                   17138:                         foreach my $cloner (@cloners) {
                   17139:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17140:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17141:                                 my (%codedefaults,@code_order);
                   17142:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17143:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17144:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17145:                                     }
                   17146:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17147:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17148:                                     }
                   17149:                                 } else {
                   17150:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17151:                                                                             \%codedefaults,
                   17152:                                                                             \@code_order);
                   17153:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17154:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17155:                                 }
                   17156:                                 if (@code_order > 0) {
                   17157:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17158:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17159:                                                                                 $args->{'crscode'})) {
                   17160:                                         $can_clone = 1;
                   17161:                                         last;
                   17162:                                     }
                   17163:                                 }
                   17164:                             }
                   17165:                         }
                   17166:                     }
1.1225    raeburn  17167:                 }
                   17168:             }
                   17169:             unless ($can_clone) {
                   17170:                 my $ccrole = 'cc';
                   17171:                 if ($args->{'crstype'} eq 'Community') {
                   17172:                     $ccrole = 'co';
                   17173:                 }
                   17174: 	        my %roleshash =
                   17175: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17176: 					          $args->{'ccdomain'},
                   17177:                                                   'userroles',['active'],[$ccrole],
                   17178: 					          [$args->{'clonedomain'}]);
                   17179: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17180:                     $can_clone = 1;
                   17181:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17182:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17183:                     $can_clone = 1;
1.1221    raeburn  17184:                 }
                   17185:             }
                   17186:             unless ($can_clone) {
                   17187:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17188:                     push(@clonemsg,({
                   17189:                                       mt => 'No new community created.',
                   17190:                                       args => [],
                   17191:                                     },
                   17192:                                     {
                   17193:                                       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]).',
                   17194:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17195:                                     }));
1.942     raeburn  17196:                 } else {
1.1344    raeburn  17197:                     push(@clonemsg,({
                   17198:                                       mt => 'No new course created.',
                   17199:                                       args => [],
                   17200:                                     },
                   17201:                                     {
                   17202:                                       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]).',
                   17203:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17204:                                     }));
1.1221    raeburn  17205:                 }
1.566     albertel 17206: 	    }
1.578     raeburn  17207:         }
1.566     albertel 17208:     }
1.1344    raeburn  17209:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17210: }
                   17211: 
1.444     albertel 17212: sub construct_course {
1.1262    raeburn  17213:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17214:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17215:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17216:     my $linefeed =  '<br />'."\n";
                   17217:     if ($context eq 'auto') {
                   17218:         $linefeed = "\n";
                   17219:     }
1.566     albertel 17220: 
                   17221: #
                   17222: # Are we cloning?
                   17223: #
1.1344    raeburn  17224:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17225:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17226: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17227:         if (!$can_clone) {
1.1344    raeburn  17228: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17229: 	}
                   17230:     }
                   17231: 
1.444     albertel 17232: #
                   17233: # Open course
                   17234: #
1.1239    raeburn  17235:     my $showncrstype;
                   17236:     if ($args->{'crstype'} eq 'Placement') {
                   17237:         $showncrstype = 'placement test'; 
                   17238:     } else {  
                   17239:         $showncrstype = lc($args->{'crstype'});
                   17240:     }
1.444     albertel 17241:     my %cenv=();
                   17242:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17243:                                              $args->{'cdescr'},
                   17244:                                              $args->{'curl'},
                   17245:                                              $args->{'course_home'},
                   17246:                                              $args->{'nonstandard'},
                   17247:                                              $args->{'crscode'},
                   17248:                                              $args->{'ccuname'}.':'.
                   17249:                                              $args->{'ccdomain'},
1.882     raeburn  17250:                                              $args->{'crstype'},
1.1344    raeburn  17251:                                              $cnum,$context,$category,
                   17252:                                              $callercontext);
1.444     albertel 17253: 
                   17254:     # Note: The testing routines depend on this being output; see 
                   17255:     # Utils::Course. This needs to at least be output as a comment
                   17256:     # if anyone ever decides to not show this, and Utils::Course::new
                   17257:     # will need to be suitably modified.
1.1344    raeburn  17258:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17259:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17260:     } else {
                   17261:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17262:     }
1.943     raeburn  17263:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17264:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17265:     }
                   17266: 
1.444     albertel 17267: #
                   17268: # Check if created correctly
                   17269: #
1.479     albertel 17270:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17271:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17272:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17273:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17274:             $outcome .= &mt_user($user_lh,
                   17275:                             'Course creation failed, unrecognized course home server.');
                   17276:         } else {
                   17277:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17278:         }
                   17279:         $outcome .= $linefeed;
                   17280:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17281:     }
1.541     raeburn  17282:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17283: 
1.444     albertel 17284: #
1.566     albertel 17285: # Do the cloning
                   17286: #   
1.1344    raeburn  17287:     my @clonemsg;
1.566     albertel 17288:     if ($can_clone && $cloneid) {
1.1344    raeburn  17289:         push(@clonemsg,
                   17290:                       {
                   17291:                           mt => 'Created [_1] by cloning from [_2]',
                   17292:                           args => [$showncrstype,$clonetitle],
                   17293:                       });
1.566     albertel 17294: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17295: # Copy all files
1.1344    raeburn  17296:         my @info =
                   17297: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17298: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17299:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17300:                                                      $args->{'tinyurls'});
                   17301:         if (@info) {
                   17302:             push(@clonemsg,@info);
                   17303:         }
1.444     albertel 17304: # Restore URL
1.566     albertel 17305: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17306: # Restore title
1.566     albertel 17307: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17308: # Restore creation date, creator and creation context.
                   17309:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17310:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17311:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17312: # Mark as cloned
1.566     albertel 17313: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17314: # Need to clone grading mode
                   17315:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17316:         $cenv{'grading'}=$newenv{'grading'};
                   17317: # Do not clone these environment entries
                   17318:         &Apache::lonnet::del('environment',
                   17319:                   ['default_enrollment_start_date',
                   17320:                    'default_enrollment_end_date',
                   17321:                    'question.email',
                   17322:                    'policy.email',
                   17323:                    'comment.email',
                   17324:                    'pch.users.denied',
1.725     raeburn  17325:                    'plc.users.denied',
                   17326:                    'hidefromcat',
1.1121    raeburn  17327:                    'checkforpriv',
1.1355    raeburn  17328:                    'categories'],
1.638     www      17329:                    $$crsudom,$$crsunum);
1.1170    raeburn  17330:         if ($args->{'textbook'}) {
                   17331:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17332:         }
1.444     albertel 17333:     }
1.566     albertel 17334: 
1.444     albertel 17335: #
                   17336: # Set environment (will override cloned, if existing)
                   17337: #
                   17338:     my @sections = ();
                   17339:     my @xlists = ();
                   17340:     if ($args->{'crstype'}) {
                   17341:         $cenv{'type'}=$args->{'crstype'};
                   17342:     }
1.1371    raeburn  17343:     if ($args->{'lti'}) {
                   17344:         $cenv{'internal.lti'}=$args->{'lti'};
                   17345:     }
1.444     albertel 17346:     if ($args->{'crsid'}) {
                   17347:         $cenv{'courseid'}=$args->{'crsid'};
                   17348:     }
                   17349:     if ($args->{'crscode'}) {
                   17350:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17351:     }
                   17352:     if ($args->{'crsquota'} ne '') {
                   17353:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17354:     } else {
                   17355:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17356:     }
                   17357:     if ($args->{'ccuname'}) {
                   17358:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17359:                                         ':'.$args->{'ccdomain'};
                   17360:     } else {
                   17361:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17362:     }
1.1116    raeburn  17363:     if ($args->{'defaultcredits'}) {
                   17364:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17365:     }
1.444     albertel 17366:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17367:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17368:     if ($args->{'crssections'}) {
                   17369:         $cenv{'internal.sectionnums'} = '';
                   17370:         if ($args->{'crssections'} =~ m/,/) {
                   17371:             @sections = split/,/,$args->{'crssections'};
                   17372:         } else {
                   17373:             $sections[0] = $args->{'crssections'};
                   17374:         }
                   17375:         if (@sections > 0) {
                   17376:             foreach my $item (@sections) {
                   17377:                 my ($sec,$gp) = split/:/,$item;
                   17378:                 my $class = $args->{'crscode'}.$sec;
                   17379:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17380:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17381:                 if ($addcheck eq 'ok') {
                   17382:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17383:                         push(@oklcsecs,$gp);
                   17384:                     }
                   17385:                 } else {
1.1263    raeburn  17386:                     push(@badclasses,$class);
1.444     albertel 17387:                 }
                   17388:             }
                   17389:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17390:         }
                   17391:     }
                   17392: # do not hide course coordinator from staff listing, 
                   17393: # even if privileged
                   17394:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17395: # add course coordinator's domain to domains to check for privileged users
                   17396: # if different to course domain
                   17397:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17398:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17399:     }
1.444     albertel 17400: # add crosslistings
                   17401:     if ($args->{'crsxlist'}) {
                   17402:         $cenv{'internal.crosslistings'}='';
                   17403:         if ($args->{'crsxlist'} =~ m/,/) {
                   17404:             @xlists = split/,/,$args->{'crsxlist'};
                   17405:         } else {
                   17406:             $xlists[0] = $args->{'crsxlist'};
                   17407:         }
                   17408:         if (@xlists > 0) {
                   17409:             foreach my $item (@xlists) {
                   17410:                 my ($xl,$gp) = split/:/,$item;
                   17411:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17412:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17413:                 if ($addcheck eq 'ok') {
                   17414:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17415:                         push(@oklcsecs,$gp);
                   17416:                     }
                   17417:                 } else {
1.1263    raeburn  17418:                     push(@badclasses,$xl);
1.444     albertel 17419:                 }
                   17420:             }
                   17421:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17422:         }
                   17423:     }
                   17424:     if ($args->{'autoadds'}) {
                   17425:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17426:     }
                   17427:     if ($args->{'autodrops'}) {
                   17428:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17429:     }
                   17430: # check for notification of enrollment changes
                   17431:     my @notified = ();
                   17432:     if ($args->{'notify_owner'}) {
                   17433:         if ($args->{'ccuname'} ne '') {
                   17434:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17435:         }
                   17436:     }
                   17437:     if ($args->{'notify_dc'}) {
                   17438:         if ($uname ne '') { 
1.630     raeburn  17439:             push(@notified,$uname.':'.$udom);
1.444     albertel 17440:         }
                   17441:     }
                   17442:     if (@notified > 0) {
                   17443:         my $notifylist;
                   17444:         if (@notified > 1) {
                   17445:             $notifylist = join(',',@notified);
                   17446:         } else {
                   17447:             $notifylist = $notified[0];
                   17448:         }
                   17449:         $cenv{'internal.notifylist'} = $notifylist;
                   17450:     }
                   17451:     if (@badclasses > 0) {
                   17452:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17453:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17454:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17455:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17456:         );
1.1264    raeburn  17457:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17458:                            &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  17459:         if ($context eq 'auto') {
                   17460:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17461:         } else {
1.566     albertel 17462:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17463:         }
                   17464:         foreach my $item (@badclasses) {
1.541     raeburn  17465:             if ($context eq 'auto') {
1.1261    raeburn  17466:                 $outcome .= " - $item\n";
1.541     raeburn  17467:             } else {
1.1261    raeburn  17468:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17469:             }
1.1261    raeburn  17470:         }
                   17471:         if ($context eq 'auto') {
                   17472:             $outcome .= $linefeed;
                   17473:         } else {
                   17474:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17475:         } 
1.444     albertel 17476:     }
                   17477:     if ($args->{'no_end_date'}) {
                   17478:         $args->{'endaccess'} = 0;
                   17479:     }
1.1412    raeburn  17480: #  If an official course with institutional sections is created by cloning 
                   17481: #  an existing course, section-specific hiding of course totals in student's
                   17482: #  view of grades as copied from cloned course, will be checked for valid 
                   17483: #  sections.
                   17484:     if (($can_clone && $cloneid) &&
                   17485:         ($cenv{'internal.coursecode'} ne '') &&
                   17486:         ($cenv{'grading'} eq 'standard') &&
                   17487:         ($cenv{'hidetotals'} ne '') &&
                   17488:         ($cenv{'hidetotals'} ne 'all')) {
                   17489:         my @hidesecs;
                   17490:         my $deletehidetotals;
                   17491:         if (@oklcsecs) {
                   17492:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17493:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17494:                     push(@hidesecs,$sec);
                   17495:                 }
                   17496:             }
                   17497:             if (@hidesecs) {
                   17498:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17499:             } else {
                   17500:                 $deletehidetotals = 1;
                   17501:             }
                   17502:         } else {
                   17503:             $deletehidetotals = 1;
                   17504:         }
                   17505:         if ($deletehidetotals) {
                   17506:             delete($cenv{'hidetotals'});
                   17507:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17508:         }
                   17509:     }
1.444     albertel 17510:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17511:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17512:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17513:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17514:     if ($args->{'showphotos'}) {
                   17515:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17516:     }
                   17517:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17518:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17519:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17520:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17521:             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'); 
                   17522:             if ($context eq 'auto') {
                   17523:                 $outcome .= $krb_msg;
                   17524:             } else {
1.566     albertel 17525:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17526:             }
                   17527:             $outcome .= $linefeed;
1.444     albertel 17528:         }
                   17529:     }
                   17530:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17531:        if ($args->{'setpolicy'}) {
                   17532:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17533:        }
                   17534:        if ($args->{'setcontent'}) {
                   17535:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17536:        }
1.1251    raeburn  17537:        if ($args->{'setcomment'}) {
                   17538:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17539:        }
1.444     albertel 17540:     }
                   17541:     if ($args->{'reshome'}) {
                   17542: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17543: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17544:     }
                   17545: #
                   17546: # course has keyed access
                   17547: #
                   17548:     if ($args->{'setkeys'}) {
                   17549:        $cenv{'keyaccess'}='yes';
                   17550:     }
                   17551: # if specified, key authority is not course, but user
                   17552: # only active if keyaccess is yes
                   17553:     if ($args->{'keyauth'}) {
1.487     albertel 17554: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17555: 	$user = &LONCAPA::clean_username($user);
                   17556: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17557: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17558: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17559: 	}
                   17560:     }
                   17561: 
1.1166    raeburn  17562: #
1.1167    raeburn  17563: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17564: #
                   17565:     if ($args->{'uniquecode'}) {
                   17566:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17567:         if ($code) {
                   17568:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17569:             my %crsinfo =
                   17570:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17571:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17572:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17573:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17574:             } 
1.1166    raeburn  17575:             if (ref($coderef)) {
                   17576:                 $$coderef = $code;
                   17577:             }
                   17578:         }
                   17579:     }
                   17580: 
1.444     albertel 17581:     if ($args->{'disresdis'}) {
                   17582:         $cenv{'pch.roles.denied'}='st';
                   17583:     }
                   17584:     if ($args->{'disablechat'}) {
                   17585:         $cenv{'plc.roles.denied'}='st';
                   17586:     }
                   17587: 
                   17588:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17589:     # course
                   17590:     $cenv{'course.helper.not.run'} = 1;
                   17591:     #
                   17592:     # Use new Randomseed
                   17593:     #
                   17594:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17595:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17596:     #
                   17597:     # The encryption code and receipt prefix for this course
                   17598:     #
                   17599:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17600:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17601:     #
                   17602:     # By default, use standard grading
                   17603:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17604: 
1.541     raeburn  17605:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17606:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17607: #
                   17608: # Open all assignments
                   17609: #
                   17610:     if ($args->{'openall'}) {
1.1341    raeburn  17611:        my $opendate = time;
                   17612:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17613:            $opendate = $args->{'openallfrom'};
                   17614:        }
1.444     albertel 17615:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17616:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17617:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17618:        $outcome .= &mt('All assignments open starting [_1]',
                   17619:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17620:                    &Apache::lonnet::cput
                   17621:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17622:    }
                   17623: #
                   17624: # Set first page
                   17625: #
                   17626:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17627: 	    || ($cloneid)) {
                   17628: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17629: 
                   17630: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17631:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17632: 
1.444     albertel 17633:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17634:         my $title; my $url;
                   17635:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17636: 	    $title=&mt('Syllabus');
1.444     albertel 17637:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17638:         } else {
1.963     raeburn  17639:             $title=&mt('Table of Contents');
1.444     albertel 17640:             $url='/adm/navmaps';
                   17641:         }
1.445     albertel 17642: 
                   17643:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17644: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17645: 
                   17646: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17647:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17648:     }
1.566     albertel 17649: 
1.1237    raeburn  17650: # 
                   17651: # Set params for Placement Tests
                   17652: #
1.1239    raeburn  17653:     if ($args->{'crstype'} eq 'Placement') {
                   17654:        my %storecontent; 
                   17655:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17656:        my %defaults = (
                   17657:                         buttonshide   => { value => 'yes',
                   17658:                                            type => 'string_yesno',},
                   17659:                         type          => { value => 'randomizetry',
                   17660:                                            type  => 'string_questiontype',},
                   17661:                         maxtries      => { value => 1,
                   17662:                                            type => 'int_pos',},
                   17663:                         problemstatus => { value => 'no',
                   17664:                                            type  => 'string_problemstatus',},
                   17665:                       );
                   17666:        foreach my $key (keys(%defaults)) {
                   17667:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17668:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17669:        }
1.1237    raeburn  17670:        &Apache::lonnet::cput
                   17671:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17672:     }
                   17673: 
1.1344    raeburn  17674:     return (1,$outcome,\@clonemsg);
1.444     albertel 17675: }
                   17676: 
1.1166    raeburn  17677: sub make_unique_code {
                   17678:     my ($cdom,$cnum) = @_;
                   17679:     # get lock on uniquecodes db
                   17680:     my $lockhash = {
                   17681:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17682:                                                   ':'.$env{'user.domain'},
                   17683:                    };
                   17684:     my $tries = 0;
                   17685:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17686:     my ($code,$error);
                   17687:   
                   17688:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17689:         $tries ++;
                   17690:         sleep 1;
                   17691:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17692:     }
                   17693:     if ($gotlock eq 'ok') {
                   17694:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17695:         my $gotcode;
                   17696:         my $attempts = 0;
                   17697:         while ((!$gotcode) && ($attempts < 100)) {
                   17698:             $code = &generate_code();
                   17699:             if (!exists($currcodes{$code})) {
                   17700:                 $gotcode = 1;
                   17701:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17702:                     $error = 'nostore';
                   17703:                 }
                   17704:             }
                   17705:             $attempts ++;
                   17706:         }
                   17707:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17708:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17709:     } else {
                   17710:         $error = 'nolock';
                   17711:     }
                   17712:     return ($code,$error);
                   17713: }
                   17714: 
                   17715: sub generate_code {
                   17716:     my $code;
                   17717:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17718:     for (my $i=0; $i<6; $i++) {
                   17719:         my $lettnum = int (rand 2);
                   17720:         my $item = '';
                   17721:         if ($lettnum) {
                   17722:             $item = $letts[int( rand(18) )];
                   17723:         } else {
                   17724:             $item = 1+int( rand(8) );
                   17725:         }
                   17726:         $code .= $item;
                   17727:     }
                   17728:     return $code;
                   17729: }
                   17730: 
1.444     albertel 17731: ############################################################
                   17732: ############################################################
                   17733: 
1.1237    raeburn  17734: # Community, Course and Placement Test
1.378     raeburn  17735: sub course_type {
                   17736:     my ($cid) = @_;
                   17737:     if (!defined($cid)) {
                   17738:         $cid = $env{'request.course.id'};
                   17739:     }
1.404     albertel 17740:     if (defined($env{'course.'.$cid.'.type'})) {
                   17741:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17742:     } else {
                   17743:         return 'Course';
1.377     raeburn  17744:     }
                   17745: }
1.156     albertel 17746: 
1.406     raeburn  17747: sub group_term {
                   17748:     my $crstype = &course_type();
                   17749:     my %names = (
                   17750:                   'Course' => 'group',
1.865     raeburn  17751:                   'Community' => 'group',
1.1237    raeburn  17752:                   'Placement' => 'group',
1.406     raeburn  17753:                 );
                   17754:     return $names{$crstype};
                   17755: }
                   17756: 
1.902     raeburn  17757: sub course_types {
1.1310    raeburn  17758:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17759:     my %typename = (
                   17760:                          official   => 'Official course',
                   17761:                          unofficial => 'Unofficial course',
                   17762:                          community  => 'Community',
1.1165    raeburn  17763:                          textbook   => 'Textbook course',
1.1237    raeburn  17764:                          placement  => 'Placement test',
1.1310    raeburn  17765:                          lti        => 'LTI provider',
1.902     raeburn  17766:                    );
                   17767:     return (\@types,\%typename);
                   17768: }
                   17769: 
1.156     albertel 17770: sub icon {
                   17771:     my ($file)=@_;
1.505     albertel 17772:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17773:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17774:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17775:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17776: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17777: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17778: 	            $curfext.".gif") {
                   17779: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17780: 		$curfext.".gif";
                   17781: 	}
                   17782:     }
1.249     albertel 17783:     return &lonhttpdurl($iconname);
1.154     albertel 17784: } 
1.84      albertel 17785: 
1.575     albertel 17786: sub lonhttpdurl {
1.692     www      17787: #
                   17788: # Had been used for "small fry" static images on separate port 8080.
                   17789: # Modify here if lightweight http functionality desired again.
                   17790: # Currently eliminated due to increasing firewall issues.
                   17791: #
1.575     albertel 17792:     my ($url)=@_;
1.692     www      17793:     return $url;
1.215     albertel 17794: }
                   17795: 
1.213     albertel 17796: sub connection_aborted {
                   17797:     my ($r)=@_;
                   17798:     $r->print(" ");$r->rflush();
                   17799:     my $c = $r->connection;
                   17800:     return $c->aborted();
                   17801: }
                   17802: 
1.221     foxr     17803: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17804: #    strings as 'strings'.
                   17805: sub escape_single {
1.221     foxr     17806:     my ($input) = @_;
1.223     albertel 17807:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17808:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17809:     return $input;
                   17810: }
1.223     albertel 17811: 
1.222     foxr     17812: #  Same as escape_single, but escape's "'s  This 
                   17813: #  can be used for  "strings"
                   17814: sub escape_double {
                   17815:     my ($input) = @_;
                   17816:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17817:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17818:     return $input;
                   17819: }
1.223     albertel 17820:  
1.222     foxr     17821: #   Escapes the last element of a full URL.
                   17822: sub escape_url {
                   17823:     my ($url)   = @_;
1.238     raeburn  17824:     my @urlslices = split(/\//, $url,-1);
1.369     www      17825:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17826:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17827: }
1.462     albertel 17828: 
1.820     raeburn  17829: sub compare_arrays {
                   17830:     my ($arrayref1,$arrayref2) = @_;
                   17831:     my (@difference,%count);
                   17832:     @difference = ();
                   17833:     %count = ();
                   17834:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17835:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17836:         foreach my $element (keys(%count)) {
                   17837:             if ($count{$element} == 1) {
                   17838:                 push(@difference,$element);
                   17839:             }
                   17840:         }
                   17841:     }
                   17842:     return @difference;
                   17843: }
                   17844: 
1.1322    raeburn  17845: sub lon_status_items {
                   17846:     my %defaults = (
                   17847:                      E         => 100,
                   17848:                      W         => 4,
                   17849:                      N         => 1,
1.1324    raeburn  17850:                      U         => 5,
1.1322    raeburn  17851:                      threshold => 200,
                   17852:                      sysmail   => 2500,
                   17853:                    );
                   17854:     my %names = (
                   17855:                    E => 'Errors',
                   17856:                    W => 'Warnings',
                   17857:                    N => 'Notices',
1.1324    raeburn  17858:                    U => 'Unsent',
1.1322    raeburn  17859:                 );
                   17860:     return (\%defaults,\%names);
                   17861: }
                   17862: 
1.817     bisitz   17863: # -------------------------------------------------------- Initialize user login
1.462     albertel 17864: sub init_user_environment {
1.463     albertel 17865:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17866:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17867: 
                   17868:     my $public=($username eq 'public' && $domain eq 'public');
                   17869: 
1.1415    raeburn  17870:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   17871:         $coauthorenv);
1.462     albertel 17872:     my $now=time;
                   17873: 
                   17874:     if ($public) {
                   17875: 	my $max_public=100;
                   17876: 	my $oldest;
                   17877: 	my $oldest_time=0;
                   17878: 	for(my $next=1;$next<=$max_public;$next++) {
                   17879: 	    if (-e $lonids."/publicuser_$next.id") {
                   17880: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17881: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17882: 		    $oldest_time=$mtime;
                   17883: 		    $oldest=$next;
                   17884: 		}
                   17885: 	    } else {
                   17886: 		$cookie="publicuser_$next";
                   17887: 		last;
                   17888: 	    }
                   17889: 	}
                   17890: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17891:     } else {
1.1275    raeburn  17892: 	# See if old ID present, if so, remove if this isn't a robot,
                   17893: 	# killing any existing non-robot sessions
1.463     albertel 17894: 	if (!$args->{'robot'}) {
                   17895: 	    opendir(DIR,$lonids);
                   17896: 	    while ($filename=readdir(DIR)) {
                   17897: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17898:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17899:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17900:                         my $linkedfile;
1.1320    raeburn  17901:                         if (exists($oldenv{'user.linkedenv'})) {
                   17902:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17903:                         }
1.1320    raeburn  17904:                         untie(%oldenv);
                   17905:                         if (unlink("$lonids/$filename")) {
                   17906:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17907:                                 if (-l "$lonids/$linkedfile.id") {
                   17908:                                     unlink("$lonids/$linkedfile.id");
                   17909:                                 }
1.1295    raeburn  17910:                             }
                   17911:                         }
                   17912:                     } else {
                   17913:                         unlink($lonids.'/'.$filename);
                   17914:                     }
1.463     albertel 17915: 		}
1.462     albertel 17916: 	    }
1.463     albertel 17917: 	    closedir(DIR);
1.1204    raeburn  17918: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17919:             my $namespace = 'nohist_courseeditor';
                   17920:             my $lockingkey = 'paste'."\0".'locked_num';
                   17921:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17922:                                                 $domain,$username);
                   17923:             if (exists($lockhash{$lockingkey})) {
                   17924:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17925:                 unless ($delresult eq 'ok') {
                   17926:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17927:                 }
                   17928:             }
1.462     albertel 17929: 	}
                   17930: # Give them a new cookie
1.463     albertel 17931: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17932: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17933: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17934:     
                   17935: # Initialize roles
                   17936: 
1.1414    raeburn  17937: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  17938:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17939:     }
                   17940: # ------------------------------------ Check browser type and MathML capability
                   17941: 
1.1194    raeburn  17942:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17943:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17944: 
                   17945: # ------------------------------------------------------------- Get environment
                   17946: 
                   17947:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17948:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17949:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17950: 	undef(%userenv);
                   17951:     }
                   17952:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17953: 	$form->{'interface'}=$userenv{'interface'};
                   17954:     }
                   17955:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17956: 
                   17957: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17958:     foreach my $option ('interface','localpath','localres') {
                   17959:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17960:     }
                   17961: # --------------------------------------------------------- Write first profile
                   17962: 
                   17963:     {
1.1350    raeburn  17964:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17965: 	my %initial_env = 
                   17966: 	    ("user.name"          => $username,
                   17967: 	     "user.domain"        => $domain,
                   17968: 	     "user.home"          => $authhost,
                   17969: 	     "browser.type"       => $clientbrowser,
                   17970: 	     "browser.version"    => $clientversion,
                   17971: 	     "browser.mathml"     => $clientmathml,
                   17972: 	     "browser.unicode"    => $clientunicode,
                   17973: 	     "browser.os"         => $clientos,
1.1137    raeburn  17974:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17975:              "browser.info"       => $clientinfo,
1.1194    raeburn  17976:              "browser.osversion"  => $clientosversion,
1.462     albertel 17977: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17978: 	     "request.course.fn"  => '',
                   17979: 	     "request.course.uri" => '',
                   17980: 	     "request.course.sec" => '',
                   17981: 	     "request.role"       => 'cm',
                   17982: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17983: 	     "request.host"       => $ip,);
1.462     albertel 17984: 
                   17985:         if ($form->{'localpath'}) {
                   17986: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17987: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17988:         }
                   17989: 	
                   17990: 	if ($form->{'interface'}) {
                   17991: 	    $form->{'interface'}=~s/\W//gs;
                   17992: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17993: 	    $env{'browser.interface'}=$form->{'interface'};
                   17994: 	}
                   17995: 
1.1157    raeburn  17996:         if ($form->{'iptoken'}) {
                   17997:             my $lonhost = $r->dir_config('lonHostID');
                   17998:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17999:             $env{'user.noloadbalance'} = $lonhost;
                   18000:         }
                   18001: 
1.1268    raeburn  18002:         if ($form->{'noloadbalance'}) {
                   18003:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18004:             my $hosthere = $form->{'noloadbalance'};
                   18005:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18006:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18007:                 $env{'user.noloadbalance'} = $hosthere;
                   18008:             }
                   18009:         }
                   18010: 
1.1016    raeburn  18011:         unless ($domain eq 'public') {
1.1273    raeburn  18012:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18013:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18014: 
1.1414    raeburn  18015:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18016:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18017:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18018:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18019:             }
1.980     raeburn  18020: 
1.1311    raeburn  18021:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18022:                 $userenv{'canrequest.'.$crstype} =
                   18023:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18024:                                                       'reload','requestcourses',
                   18025:                                                       \%userenv,\%domdef,\%is_adv);
                   18026:             }
1.724     raeburn  18027: 
1.1418    raeburn  18028:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18029:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18030:                 if ($userenv{'authoreditors'}) {
                   18031:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18032:                 } elsif ($domdef{'editors'} ne '') {
                   18033:                     $userenv{'editors'} = $domdef{'editors'};
                   18034:                 } else {
                   18035:                     $userenv{'editors'} = 'edit,xml';
                   18036:                 }
                   18037:             }
                   18038: 
1.1273    raeburn  18039:             $userenv{'canrequest.author'} =
                   18040:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18041:                                                   'reload','requestauthor',
1.980     raeburn  18042:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18043:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18044:                                                  $domain,$username);
                   18045:             my $reqstatus = $reqauthor{'author_status'};
                   18046:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18047:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18048:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18049:                                                       $reqauthor{'author'}{'timestamp'};
                   18050:                 }
1.1092    raeburn  18051:             }
1.1287    raeburn  18052:             my ($types,$typename) = &course_types();
                   18053:             if (ref($types) eq 'ARRAY') {
                   18054:                 my @options = ('approval','validate','autolimit');
                   18055:                 my $optregex = join('|',@options);
                   18056:                 my (%willtrust,%trustchecked);
                   18057:                 foreach my $type (@{$types}) {
                   18058:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18059:                     if ($dom_str ne '') {
                   18060:                         my $updatedstr = '';
                   18061:                         my @possdomains = split(',',$dom_str);
                   18062:                         foreach my $entry (@possdomains) {
                   18063:                             my ($extdom,$extopt) = split(':',$entry);
                   18064:                             unless ($trustchecked{$extdom}) {
                   18065:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18066:                                 $trustchecked{$extdom} = 1;
                   18067:                             }
                   18068:                             if ($willtrust{$extdom}) {
                   18069:                                 $updatedstr .= $entry.',';
                   18070:                             }
                   18071:                         }
                   18072:                         $updatedstr =~ s/,$//;
                   18073:                         if ($updatedstr) {
                   18074:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18075:                         } else {
                   18076:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18077:                         }
                   18078:                     }
                   18079:                 }
                   18080:             }
1.1092    raeburn  18081:         }
1.462     albertel 18082: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18083: 
1.462     albertel 18084: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18085: 		 &GDBM_WRCREAT(),0640)) {
                   18086: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18087: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18088: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18089:             if (ref($firstaccenv) eq 'HASH') {
                   18090:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18091:             }
                   18092:             if (ref($timerintenv) eq 'HASH') {
                   18093:                 &_add_to_env(\%disk_env,$timerintenv);
                   18094:             }
1.1414    raeburn  18095:             if (ref($coauthorenv) eq 'HASH') {
                   18096:                 if (keys(%{$coauthorenv})) {
                   18097:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18098:                 }
                   18099:             }
1.463     albertel 18100: 	    if (ref($args->{'extra_env'})) {
                   18101: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18102: 	    }
1.462     albertel 18103: 	    untie(%disk_env);
                   18104: 	} else {
1.705     tempelho 18105: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18106: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18107: 	    return 'error: '.$!;
                   18108: 	}
                   18109:     }
                   18110:     $env{'request.role'}='cm';
                   18111:     $env{'request.role.adv'}=$env{'user.adv'};
                   18112:     $env{'browser.type'}=$clientbrowser;
                   18113: 
                   18114:     return $cookie;
                   18115: 
                   18116: }
                   18117: 
                   18118: sub _add_to_env {
                   18119:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18120:     if (ref($env_data) eq 'HASH') {
                   18121:         while (my ($key,$value) = each(%$env_data)) {
                   18122: 	    $idf->{$prefix.$key} = $value;
                   18123: 	    $env{$prefix.$key}   = $value;
                   18124:         }
1.462     albertel 18125:     }
                   18126: }
                   18127: 
1.685     tempelho 18128: # --- Get the symbolic name of a problem and the url
                   18129: sub get_symb {
                   18130:     my ($request,$silent) = @_;
1.726     raeburn  18131:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18132:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18133:     if ($symb eq '') {
                   18134:         if (!$silent) {
1.1071    raeburn  18135:             if (ref($request)) { 
                   18136:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18137:             }
1.685     tempelho 18138:             return ();
                   18139:         }
                   18140:     }
                   18141:     &Apache::lonenc::check_decrypt(\$symb);
                   18142:     return ($symb);
                   18143: }
                   18144: 
                   18145: # --------------------------------------------------------------Get annotation
                   18146: 
                   18147: sub get_annotation {
                   18148:     my ($symb,$enc) = @_;
                   18149: 
                   18150:     my $key = $symb;
                   18151:     if (!$enc) {
                   18152:         $key =
                   18153:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18154:     }
                   18155:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18156:     return $annotation{$key};
                   18157: }
                   18158: 
                   18159: sub clean_symb {
1.731     raeburn  18160:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18161: 
                   18162:     &Apache::lonenc::check_decrypt(\$symb);
                   18163:     my $enc = $env{'request.enc'};
1.731     raeburn  18164:     if ($delete_enc) {
1.730     raeburn  18165:         delete($env{'request.enc'});
                   18166:     }
1.685     tempelho 18167: 
                   18168:     return ($symb,$enc);
                   18169: }
1.462     albertel 18170: 
1.1181    raeburn  18171: ############################################################
                   18172: ############################################################
                   18173: 
                   18174: =pod
                   18175: 
                   18176: =head1 Routines for building display used to search for courses
                   18177: 
                   18178: 
                   18179: =over 4
                   18180: 
                   18181: =item * &build_filters()
                   18182: 
                   18183: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18184: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18185: and quotacheck.pl
                   18186: 
1.1181    raeburn  18187: 
                   18188: Inputs:
                   18189: 
                   18190: filterlist - anonymous array of fields to include as potential filters 
                   18191: 
                   18192: crstype - course type
                   18193: 
                   18194: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18195:               to pop-open a course selector (will contain "extra element"). 
                   18196: 
                   18197: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18198: 
                   18199: filter - anonymous hash of criteria and their values
                   18200: 
                   18201: action - form action
                   18202: 
                   18203: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18204: 
1.1182    raeburn  18205: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18206: 
                   18207: cloneruname - username of owner of new course who wants to clone
                   18208: 
                   18209: clonerudom - domain of owner of new course who wants to clone
                   18210: 
                   18211: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18212: 
                   18213: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18214: 
                   18215: codedom - domain
                   18216: 
                   18217: formname - value of form element named "form". 
                   18218: 
                   18219: fixeddom - domain, if fixed.
                   18220: 
                   18221: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18222: 
                   18223: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18224: 
                   18225: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18226: 
                   18227: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18228: 
                   18229: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18230: 
                   18231: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18232: 
                   18233: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18234: 
1.1182    raeburn  18235: 
1.1181    raeburn  18236: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18237: 
1.1182    raeburn  18238: 
1.1181    raeburn  18239: Side Effects: None
                   18240: 
                   18241: =cut
                   18242: 
                   18243: # ---------------------------------------------- search for courses based on last activity etc.
                   18244: 
                   18245: sub build_filters {
                   18246:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18247:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18248:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18249:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18250:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18251:     my ($list,$jscript);
1.1181    raeburn  18252:     my $onchange = 'javascript:updateFilters(this)';
                   18253:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18254:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18255:         $typeselectform,$instcodetitle);
                   18256:     if ($formname eq '') {
                   18257:         $formname = $caller;
                   18258:     }
                   18259:     foreach my $item (@{$filterlist}) {
                   18260:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18261:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18262:             if ($item eq 'domainfilter') {
                   18263:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18264:             } elsif ($item eq 'coursefilter') {
                   18265:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18266:             } elsif ($item eq 'ownerfilter') {
                   18267:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18268:             } elsif ($item eq 'ownerdomfilter') {
                   18269:                 $filter->{'ownerdomfilter'} =
                   18270:                     &LONCAPA::clean_domain($filter->{$item});
                   18271:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18272:                                                        'ownerdomfilter',1);
                   18273:             } elsif ($item eq 'personfilter') {
                   18274:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18275:             } elsif ($item eq 'persondomfilter') {
                   18276:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18277:                                                         'persondomfilter',1);
                   18278:             } else {
                   18279:                 $filter->{$item} =~ s/\W//g;
                   18280:             }
                   18281:             if (!$filter->{$item}) {
                   18282:                 $filter->{$item} = '';
                   18283:             }
                   18284:         }
                   18285:         if ($item eq 'domainfilter') {
                   18286:             my $allow_blank = 1;
                   18287:             if ($formname eq 'portform') {
                   18288:                 $allow_blank=0;
                   18289:             } elsif ($formname eq 'studentform') {
                   18290:                 $allow_blank=0;
                   18291:             }
                   18292:             if ($fixeddom) {
                   18293:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18294:                                     ' value="'.$codedom.'" />'.
                   18295:                                     &Apache::lonnet::domain($codedom,'description');
                   18296:             } else {
                   18297:                 $domainselectform = &select_dom_form($filter->{$item},
                   18298:                                                      'domainfilter',
                   18299:                                                       $allow_blank,'',$onchange);
                   18300:             }
                   18301:         } else {
                   18302:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18303:         }
                   18304:     }
                   18305: 
                   18306:     # last course activity filter and selection
                   18307:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18308: 
                   18309:     # course created filter and selection
                   18310:     if (exists($filter->{'createdfilter'})) {
                   18311:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18312:     }
                   18313: 
1.1239    raeburn  18314:     my $prefix = $crstype;
                   18315:     if ($crstype eq 'Placement') {
                   18316:         $prefix = 'Placement Test'
                   18317:     }
1.1181    raeburn  18318:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18319:                 'cac' => "$prefix Activity",
                   18320:                 'ccr' => "$prefix Created",
                   18321:                 'cde' => "$prefix Title",
                   18322:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18323:                 'ins' => 'Institutional Code',
                   18324:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18325:                 'cow' => "$prefix Owner/Co-owner",
                   18326:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18327:                 'cog' => 'Type',
                   18328:              );
                   18329: 
                   18330:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18331:         my $typeval = 'Course';
                   18332:         if ($crstype eq 'Community') {
                   18333:             $typeval = 'Community';
1.1239    raeburn  18334:         } elsif ($crstype eq 'Placement') {
                   18335:             $typeval = 'Placement';
1.1181    raeburn  18336:         }
                   18337:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18338:     } else {
                   18339:         $typeselectform =  '<select name="type" size="1"';
                   18340:         if ($onchange) {
                   18341:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18342:         }
                   18343:         $typeselectform .= '>'."\n";
1.1237    raeburn  18344:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18345:             my $shown;
                   18346:             if ($posstype eq 'Placement') {
                   18347:                 $shown = &mt('Placement Test');
                   18348:             } else {
                   18349:                 $shown = &mt($posstype);
                   18350:             }
1.1181    raeburn  18351:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18352:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18353:         }
                   18354:         $typeselectform.="</select>";
                   18355:     }
                   18356: 
                   18357:     my ($cloneableonlyform,$cloneabletitle);
                   18358:     if (exists($filter->{'cloneableonly'})) {
                   18359:         my $cloneableon = '';
                   18360:         my $cloneableoff = ' checked="checked"';
                   18361:         if ($filter->{'cloneableonly'}) {
                   18362:             $cloneableon = $cloneableoff;
                   18363:             $cloneableoff = '';
                   18364:         }
                   18365:         $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>';
                   18366:         if ($formname eq 'ccrs') {
1.1187    bisitz   18367:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18368:         } else {
                   18369:             $cloneabletitle = &mt('Cloneable by you');
                   18370:         }
                   18371:     }
                   18372:     my $officialjs;
                   18373:     if ($crstype eq 'Course') {
                   18374:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18375: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18376: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18377:             if ($codedom) { 
1.1181    raeburn  18378:                 $officialjs = 1;
                   18379:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18380:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18381:                                                                   $officialjs,$codetitlesref);
                   18382:                 if ($jscript) {
1.1182    raeburn  18383:                     $jscript = '<script type="text/javascript">'."\n".
                   18384:                                '// <![CDATA['."\n".
                   18385:                                $jscript."\n".
                   18386:                                '// ]]>'."\n".
                   18387:                                '</script>'."\n";
1.1181    raeburn  18388:                 }
                   18389:             }
                   18390:             if ($instcodeform eq '') {
                   18391:                 $instcodeform =
                   18392:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18393:                     $list->{'instcodefilter'}.'" />';
                   18394:                 $instcodetitle = $lt{'ins'};
                   18395:             } else {
                   18396:                 $instcodetitle = $lt{'inc'};
                   18397:             }
                   18398:             if ($fixeddom) {
                   18399:                 $instcodetitle .= '<br />('.$codedom.')';
                   18400:             }
                   18401:         }
                   18402:     }
                   18403:     my $output = qq|
                   18404: <form method="post" name="filterpicker" action="$action">
                   18405: <input type="hidden" name="form" value="$formname" />
                   18406: |;
                   18407:     if ($formname eq 'modifycourse') {
                   18408:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18409:                    '<input type="hidden" name="prevphase" value="'.
                   18410:                    $prevphase.'" />'."\n";
1.1198    musolffc 18411:     } elsif ($formname eq 'quotacheck') {
                   18412:         $output .= qq|
                   18413: <input type="hidden" name="sortby" value="" />
                   18414: <input type="hidden" name="sortorder" value="" />
                   18415: |;
                   18416:     } else {
1.1181    raeburn  18417:         my $name_input;
                   18418:         if ($cnameelement ne '') {
                   18419:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18420:                           $cnameelement.'" />';
                   18421:         }
                   18422:         $output .= qq|
1.1182    raeburn  18423: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18424: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18425: $name_input
                   18426: $roleelement
                   18427: $multelement
                   18428: $typeelement
                   18429: |;
                   18430:         if ($formname eq 'portform') {
                   18431:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18432:         }
                   18433:     }
                   18434:     if ($fixeddom) {
                   18435:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18436:     }
                   18437:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18438:     if ($sincefilterform) {
                   18439:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18440:                   .$sincefilterform
                   18441:                   .&Apache::lonhtmlcommon::row_closure();
                   18442:     }
                   18443:     if ($createdfilterform) {
                   18444:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18445:                   .$createdfilterform
                   18446:                   .&Apache::lonhtmlcommon::row_closure();
                   18447:     }
                   18448:     if ($domainselectform) {
                   18449:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18450:                   .$domainselectform
                   18451:                   .&Apache::lonhtmlcommon::row_closure();
                   18452:     }
                   18453:     if ($typeselectform) {
                   18454:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18455:             $output .= $typeselectform;
                   18456:         } else {
                   18457:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18458:                       .$typeselectform
                   18459:                       .&Apache::lonhtmlcommon::row_closure();
                   18460:         }
                   18461:     }
                   18462:     if ($instcodeform) {
                   18463:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18464:                   .$instcodeform
                   18465:                   .&Apache::lonhtmlcommon::row_closure();
                   18466:     }
                   18467:     if (exists($filter->{'ownerfilter'})) {
                   18468:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18469:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18470:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18471:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18472:                    $ownerdomselectform.'</td></tr></table>'.
                   18473:                    &Apache::lonhtmlcommon::row_closure();
                   18474:     }
                   18475:     if (exists($filter->{'personfilter'})) {
                   18476:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18477:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18478:                    '<input type="text" name="personfilter" size="20" value="'.
                   18479:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18480:                    $persondomselectform.'</td></tr></table>'.
                   18481:                    &Apache::lonhtmlcommon::row_closure();
                   18482:     }
                   18483:     if (exists($filter->{'coursefilter'})) {
                   18484:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18485:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18486:                   .$list->{'coursefilter'}.'" />'
                   18487:                   .&Apache::lonhtmlcommon::row_closure();
                   18488:     }
                   18489:     if ($cloneableonlyform) {
                   18490:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18491:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18492:     }
                   18493:     if (exists($filter->{'descriptfilter'})) {
                   18494:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18495:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18496:                   .$list->{'descriptfilter'}.'" />'
                   18497:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18498:     }
                   18499:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18500:                '<input type="hidden" name="updater" value="" />'."\n".
                   18501:                '<input type="submit" name="gosearch" value="'.
                   18502:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18503:     return $jscript.$clonewarning.$output;
                   18504: }
                   18505: 
                   18506: =pod 
                   18507: 
                   18508: =item * &timebased_select_form()
                   18509: 
1.1182    raeburn  18510: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18511: filter e.g., Course Activity, Course Created, when searching for courses
                   18512: or communities
                   18513: 
                   18514: Inputs:
                   18515: 
                   18516: item - name of form element (sincefilter or createdfilter)
                   18517: 
                   18518: filter - anonymous hash of criteria and their values
                   18519: 
                   18520: Returns: HTML for a select box contained a blank, then six time selections,
                   18521:          with value set in incoming form variables currently selected. 
                   18522: 
                   18523: Side Effects: None
                   18524: 
                   18525: =cut
                   18526: 
                   18527: sub timebased_select_form {
                   18528:     my ($item,$filter) = @_;
                   18529:     if (ref($filter) eq 'HASH') {
                   18530:         $filter->{$item} =~ s/[^\d-]//g;
                   18531:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18532:         return &select_form(
                   18533:                             $filter->{$item},
                   18534:                             $item,
                   18535:                             {      '-1' => '',
                   18536:                                 '86400' => &mt('today'),
                   18537:                                '604800' => &mt('last week'),
                   18538:                               '2592000' => &mt('last month'),
                   18539:                               '7776000' => &mt('last three months'),
                   18540:                              '15552000' => &mt('last six months'),
                   18541:                              '31104000' => &mt('last year'),
                   18542:                     'select_form_order' =>
                   18543:                            ['-1','86400','604800','2592000','7776000',
                   18544:                             '15552000','31104000']});
                   18545:     }
                   18546: }
                   18547: 
                   18548: =pod
                   18549: 
                   18550: =item * &js_changer()
                   18551: 
                   18552: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18553: when course type or domain is changed, and also to hide 'Searching ...' on
                   18554: page load completion for page showing search result.
1.1181    raeburn  18555: 
                   18556: Inputs: None
                   18557: 
1.1183    raeburn  18558: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18559: 
                   18560: Side Effects: None
                   18561: 
                   18562: =cut
                   18563: 
                   18564: sub js_changer {
                   18565:     return <<ENDJS;
                   18566: <script type="text/javascript">
                   18567: // <![CDATA[
                   18568: function updateFilters(caller) {
                   18569:     if (typeof(caller) != "undefined") {
                   18570:         document.filterpicker.updater.value = caller.name;
                   18571:     }
                   18572:     document.filterpicker.submit();
                   18573: }
1.1183    raeburn  18574: 
                   18575: function hideSearching() {
                   18576:     if (document.getElementById('searching')) {
                   18577:         document.getElementById('searching').style.display = 'none';
                   18578:     }
                   18579:     return;
                   18580: }
                   18581: 
1.1181    raeburn  18582: // ]]>
                   18583: </script>
                   18584: 
                   18585: ENDJS
                   18586: }
                   18587: 
                   18588: =pod
                   18589: 
1.1182    raeburn  18590: =item * &search_courses()
                   18591: 
                   18592: Process selected filters form course search form and pass to lonnet::courseiddump
                   18593: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18594: 
                   18595: Inputs:
                   18596: 
                   18597: dom - domain being searched 
                   18598: 
                   18599: type - course type ('Course' or 'Community' or '.' if any).
                   18600: 
                   18601: filter - anonymous hash of criteria and their values
                   18602: 
                   18603: numtitles - for institutional codes - number of categories
                   18604: 
                   18605: cloneruname - optional username of new course owner
                   18606: 
                   18607: clonerudom - optional domain of new course owner
                   18608: 
1.1221    raeburn  18609: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18610:             (used when DC is using course creation form)
                   18611: 
                   18612: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18613: 
1.1221    raeburn  18614: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18615:            (and so can clone automatically)
                   18616: 
                   18617: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18618: 
                   18619: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18620:               courses to clone 
1.1182    raeburn  18621: 
                   18622: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18623: 
                   18624: 
                   18625: Side Effects: None
                   18626: 
                   18627: =cut
                   18628: 
                   18629: 
                   18630: sub search_courses {
1.1221    raeburn  18631:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18632:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18633:     my (%courses,%showcourses,$cloner);
                   18634:     if (($filter->{'ownerfilter'} ne '') ||
                   18635:         ($filter->{'ownerdomfilter'} ne '')) {
                   18636:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18637:                                        $filter->{'ownerdomfilter'};
                   18638:     }
                   18639:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18640:         if (!$filter->{$item}) {
                   18641:             $filter->{$item}='.';
                   18642:         }
                   18643:     }
                   18644:     my $now = time;
                   18645:     my $timefilter =
                   18646:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18647:     my ($createdbefore,$createdafter);
                   18648:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18649:         $createdbefore = $now;
                   18650:         $createdafter = $now-$filter->{'createdfilter'};
                   18651:     }
                   18652:     my ($instcodefilter,$regexpok);
                   18653:     if ($numtitles) {
                   18654:         if ($env{'form.official'} eq 'on') {
                   18655:             $instcodefilter =
                   18656:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18657:             $regexpok = 1;
                   18658:         } elsif ($env{'form.official'} eq 'off') {
                   18659:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18660:             unless ($instcodefilter eq '') {
                   18661:                 $regexpok = -1;
                   18662:             }
                   18663:         }
                   18664:     } else {
                   18665:         $instcodefilter = $filter->{'instcodefilter'};
                   18666:     }
                   18667:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18668:     if ($type eq '') { $type = '.'; }
                   18669: 
                   18670:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18671:         $cloner = $cloneruname.':'.$clonerudom;
                   18672:     }
                   18673:     %courses = &Apache::lonnet::courseiddump($dom,
                   18674:                                              $filter->{'descriptfilter'},
                   18675:                                              $timefilter,
                   18676:                                              $instcodefilter,
                   18677:                                              $filter->{'combownerfilter'},
                   18678:                                              $filter->{'coursefilter'},
                   18679:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18680:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18681:                                              $filter->{'cloneableonly'},
                   18682:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18683:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18684:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18685:         my $ccrole;
                   18686:         if ($type eq 'Community') {
                   18687:             $ccrole = 'co';
                   18688:         } else {
                   18689:             $ccrole = 'cc';
                   18690:         }
                   18691:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18692:                                                      $filter->{'persondomfilter'},
                   18693:                                                      'userroles',undef,
                   18694:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18695:                                                      $dom);
                   18696:         foreach my $role (keys(%rolehash)) {
                   18697:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18698:             my $cid = $cdom.'_'.$cnum;
                   18699:             if (exists($courses{$cid})) {
                   18700:                 if (ref($courses{$cid}) eq 'HASH') {
                   18701:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18702:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18703:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18704:                         }
                   18705:                     } else {
                   18706:                         $courses{$cid}{roles} = [$courserole];
                   18707:                     }
                   18708:                     $showcourses{$cid} = $courses{$cid};
                   18709:                 }
                   18710:             }
                   18711:         }
                   18712:         %courses = %showcourses;
                   18713:     }
                   18714:     return %courses;
                   18715: }
                   18716: 
                   18717: =pod
                   18718: 
1.1181    raeburn  18719: =back
                   18720: 
1.1207    raeburn  18721: =head1 Routines for version requirements for current course.
                   18722: 
                   18723: =over 4
                   18724: 
                   18725: =item * &check_release_required()
                   18726: 
                   18727: Compares required LON-CAPA version with version on server, and
                   18728: if required version is newer looks for a server with the required version.
                   18729: 
                   18730: Looks first at servers in user's owen domain; if none suitable, looks at
                   18731: servers in course's domain are permitted to host sessions for user's domain.
                   18732: 
                   18733: Inputs:
                   18734: 
                   18735: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18736: 
                   18737: $courseid - Course ID of current course
                   18738: 
                   18739: $rolecode - User's current role in course (for switchserver query string).
                   18740: 
                   18741: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18742: 
                   18743: 
                   18744: Returns:
                   18745: 
                   18746: $switchserver - query string tp append to /adm/switchserver call (if 
                   18747:                 current server's LON-CAPA version is too old. 
                   18748: 
                   18749: $warning - Message is displayed if no suitable server could be found.
                   18750: 
                   18751: =cut
                   18752: 
                   18753: sub check_release_required {
                   18754:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18755:     my ($switchserver,$warning);
                   18756:     if ($required ne '') {
                   18757:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18758:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18759:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18760:             my $otherserver;
                   18761:             if (($major eq '' && $minor eq '') ||
                   18762:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18763:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18764:                 my $switchlcrev =
                   18765:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18766:                                                            $userdomserver);
                   18767:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18768:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18769:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18770:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18771:                     if ($cdom ne $env{'user.domain'}) {
                   18772:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18773:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18774:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18775:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18776:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18777:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18778:                         my $canhost =
                   18779:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18780:                                                               $coursedomserver,
                   18781:                                                               $remoterev,
                   18782:                                                               $udomdefaults{'remotesessions'},
                   18783:                                                               $defdomdefaults{'hostedsessions'});
                   18784: 
                   18785:                         if ($canhost) {
                   18786:                             $otherserver = $coursedomserver;
                   18787:                         } else {
                   18788:                             $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.");
                   18789:                         }
                   18790:                     } else {
                   18791:                         $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).");
                   18792:                     }
                   18793:                 } else {
                   18794:                     $otherserver = $userdomserver;
                   18795:                 }
                   18796:             }
                   18797:             if ($otherserver ne '') {
                   18798:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18799:             }
                   18800:         }
                   18801:     }
                   18802:     return ($switchserver,$warning);
                   18803: }
                   18804: 
                   18805: =pod
                   18806: 
                   18807: =item * &check_release_result()
                   18808: 
                   18809: Inputs:
                   18810: 
                   18811: $switchwarning - Warning message if no suitable server found to host session.
                   18812: 
                   18813: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18814:                 and current role.
                   18815: 
                   18816: Returns: HTML to display with information about requirement to switch server.
                   18817:          Either displaying warning with link to Roles/Courses screen or
                   18818:          display link to switchserver.
                   18819: 
1.1181    raeburn  18820: =cut
                   18821: 
1.1207    raeburn  18822: sub check_release_result {
                   18823:     my ($switchwarning,$switchserver) = @_;
                   18824:     my $output = &start_page('Selected course unavailable on this server').
                   18825:                  '<p class="LC_warning">';
                   18826:     if ($switchwarning) {
                   18827:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18828:         if (&show_course()) {
                   18829:             $output .= &mt('Display courses');
                   18830:         } else {
                   18831:             $output .= &mt('Display roles');
                   18832:         }
                   18833:         $output .= '</a>';
                   18834:     } elsif ($switchserver) {
                   18835:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18836:                    '<br />'.
                   18837:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18838:                    &mt('Switch Server').
                   18839:                    '</a>';
                   18840:     }
                   18841:     $output .= '</p>'.&end_page();
                   18842:     return $output;
                   18843: }
                   18844: 
                   18845: =pod
                   18846: 
                   18847: =item * &needs_coursereinit()
                   18848: 
                   18849: Determine if course contents stored for user's session needs to be
                   18850: refreshed, because content has changed since "Big Hash" last tied.
                   18851: 
                   18852: Check for change is made if time last checked is more than 10 minutes ago
                   18853: (by default).
                   18854: 
                   18855: Inputs:
                   18856: 
                   18857: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18858: 
                   18859: $interval (optional) - Time which may elapse (in s) between last check for content
                   18860:                        change in current course. (default: 600 s).  
                   18861: 
                   18862: Returns: an array; first element is:
                   18863: 
                   18864: =over 4
                   18865: 
                   18866: 'switch' - if content updates mean user's session
                   18867:            needs to be switched to a server running a newer LON-CAPA version
                   18868:  
                   18869: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18870:            on current server hosting user's session                
                   18871: 
                   18872: ''       - if no action required.
                   18873: 
                   18874: =back
                   18875: 
                   18876: If first item element is 'switch':
                   18877: 
                   18878: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18879: 
                   18880: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18881:                               and current role. 
                   18882: 
                   18883: otherwise: no other elements returned.
                   18884: 
                   18885: =back
                   18886: 
                   18887: =cut
                   18888: 
                   18889: sub needs_coursereinit {
                   18890:     my ($loncaparev,$interval) = @_;
                   18891:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18892:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18893:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18894:     my $now = time;
                   18895:     if ($interval eq '') {
                   18896:         $interval = 600;
                   18897:     }
                   18898:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18899:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18900:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18901:         if ($blocked) {
                   18902:             return ();
                   18903:         }
1.1391    raeburn  18904:         my $update;
                   18905:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18906:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18907:         if ($lastmainchange > $env{'request.course.tied'}) {
                   18908:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18909:             if ($needswitch) {
                   18910:                 return ('switch',$switchwarning,$switchserver);
                   18911:             }
                   18912:             $update = 'main';
                   18913:         }
                   18914:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18915:             if ($update) {
                   18916:                 $update = 'both';
                   18917:             } else {
                   18918:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18919:                 if ($needswitch) {
                   18920:                     return ('switch',$switchwarning,$switchserver);
                   18921:                 } else {
                   18922:                     $update = 'supp';
1.1207    raeburn  18923:                 }
                   18924:             }
1.1391    raeburn  18925:             return ($update);
                   18926:         }
                   18927:     }
                   18928:     return ();
                   18929: }
                   18930: 
                   18931: sub switch_for_update {
                   18932:     my ($loncaparev,$cdom,$cnum) = @_;
                   18933:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18934:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18935:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18936:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18937:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18938:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18939:             my ($switchserver,$switchwarning) =
                   18940:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18941:                                         $curr_reqd_hash{'internal.releaserequired'});
                   18942:             if ($switchwarning ne '' || $switchserver ne '') {
                   18943:                 return ('switch',$switchwarning,$switchserver);
                   18944:             }
1.1207    raeburn  18945:         }
                   18946:     }
                   18947:     return ();
                   18948: }
1.1181    raeburn  18949: 
1.1083    raeburn  18950: sub update_content_constraints {
1.1395    raeburn  18951:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  18952:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18953:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18954:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18955:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18956:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18957:         if ($item eq 'resourcetag') {
                   18958:             if ($name eq 'responsetype') {
                   18959:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18960:             }
1.1307    raeburn  18961:         } elsif ($item eq 'course') {
                   18962:             if ($name eq 'courserestype') {
                   18963:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18964:             }
1.1083    raeburn  18965:         }
                   18966:     }
                   18967:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18968:     if (defined($navmap)) {
1.1307    raeburn  18969:         my (%allresponses,%allcrsrestypes);
                   18970:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18971:             if ($res->is_tool()) {
                   18972:                 if ($allcrsrestypes{'exttool'}) {
                   18973:                     $allcrsrestypes{'exttool'} ++;
                   18974:                 } else {
                   18975:                     $allcrsrestypes{'exttool'} = 1;
                   18976:                 }
                   18977:                 next;
                   18978:             }
1.1083    raeburn  18979:             my %responses = $res->responseTypes();
                   18980:             foreach my $key (keys(%responses)) {
                   18981:                 next unless(exists($checkresponsetypes{$key}));
                   18982:                 $allresponses{$key} += $responses{$key};
                   18983:             }
                   18984:         }
                   18985:         foreach my $key (keys(%allresponses)) {
                   18986:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18987:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18988:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18989:             }
                   18990:         }
1.1307    raeburn  18991:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18992:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18993:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18994:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18995:             }
                   18996:         }
1.1083    raeburn  18997:         undef($navmap);
                   18998:     }
1.1391    raeburn  18999:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19000:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19001:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19002:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19003:         }
                   19004:     }
1.1083    raeburn  19005:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19006:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19007:     }
                   19008:     return;
                   19009: }
                   19010: 
1.1110    raeburn  19011: sub allmaps_incourse {
                   19012:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19013:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19014:         $cid = $env{'request.course.id'};
                   19015:         $cdom = $env{'course.'.$cid.'.domain'};
                   19016:         $cnum = $env{'course.'.$cid.'.num'};
                   19017:         $chome = $env{'course.'.$cid.'.home'};
                   19018:     }
                   19019:     my %allmaps = ();
                   19020:     my $lastchange =
                   19021:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19022:     if ($lastchange > $env{'request.course.tied'}) {
                   19023:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19024:         unless ($ferr) {
1.1395    raeburn  19025:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19026:         }
                   19027:     }
                   19028:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19029:     if (defined($navmap)) {
                   19030:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19031:             $allmaps{$res->src()} = 1;
                   19032:         }
                   19033:     }
                   19034:     return \%allmaps;
                   19035: }
                   19036: 
1.1083    raeburn  19037: sub parse_supplemental_title {
                   19038:     my ($title) = @_;
                   19039: 
                   19040:     my ($foldertitle,$renametitle);
                   19041:     if ($title =~ /&amp;&amp;&amp;/) {
                   19042:         $title = &HTML::Entites::decode($title);
                   19043:     }
                   19044:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19045:         $renametitle=$4;
                   19046:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19047:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19048:         my $name =  &plainname($uname,$udom);
                   19049:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19050:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19051:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19052:         if ($foldertitle ne '') {
1.1401    raeburn  19053:             $title .= ': <br />'.$foldertitle;
                   19054:         }
1.1083    raeburn  19055:     }
                   19056:     if (wantarray) {
                   19057:         return ($title,$foldertitle,$renametitle);
                   19058:     }
                   19059:     return $title;
                   19060: }
                   19061: 
1.1395    raeburn  19062: sub get_supplemental {
                   19063:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19064:     my $hashid=$cnum.':'.$cdom;
                   19065:     my ($supplemental,$cached,$set_httprefs);
                   19066:     unless ($ignorecache) {
                   19067:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19068:     }
                   19069:     unless (defined($cached)) {
                   19070:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19071:         unless ($chome eq 'no_host') {
                   19072:             my @order = @LONCAPA::map::order;
                   19073:             my @resources = @LONCAPA::map::resources;
                   19074:             my @resparms = @LONCAPA::map::resparms;
                   19075:             my @zombies = @LONCAPA::map::zombies;
                   19076:             my ($errors,%ids,%hidden);
                   19077:             $errors =
                   19078:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19079:                                       $errors,$possdel,\%ids,\%hidden);
                   19080:             @LONCAPA::map::order = @order;
                   19081:             @LONCAPA::map::resources = @resources;
                   19082:             @LONCAPA::map::resparms = @resparms;
                   19083:             @LONCAPA::map::zombies = @zombies;
                   19084:             $set_httprefs = 1;
                   19085:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19086:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19087:             }
                   19088:             $supplemental = {
                   19089:                                ids => \%ids,
                   19090:                                hidden => \%hidden,
                   19091:                             };
                   19092:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19093:         }
                   19094:     }
                   19095:     return ($supplemental,$set_httprefs);
                   19096: }
                   19097: 
1.1143    raeburn  19098: sub recurse_supplemental {
1.1391    raeburn  19099:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19100:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19101:         my $mapnum;
                   19102:         if ($suppmap eq 'supplemental.sequence') {
                   19103:             $mapnum = 0;
                   19104:         } else {
                   19105:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19106:         }
1.1143    raeburn  19107:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19108:         if ($fatal) {
                   19109:             $errors ++;
                   19110:         } else {
1.1389    raeburn  19111:             my @order = @LONCAPA::map::order;
                   19112:             if (@order > 0) {
                   19113:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19114:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19115:                 foreach my $idx (@order) {
                   19116:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19117:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19118:                         my $id = $mapnum.':'.$idx;
                   19119:                         push(@{$suppids->{$src}},$id);
                   19120:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19121:                             $hiddensupp->{$id} = 1;
                   19122:                         }
1.1146    raeburn  19123:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19124:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19125:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19126:                         } else {
1.1391    raeburn  19127:                             my $allowed;
                   19128:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19129:                                 $allowed = 1;
                   19130:                             } elsif ($possdel) {
                   19131:                                 foreach my $item (@{$suppids->{$src}}) {
                   19132:                                     next if ($item eq $id);
                   19133:                                     unless ($hiddensupp->{$item}) {
                   19134:                                        $allowed = 1;
                   19135:                                        last;
                   19136:                                     }
                   19137:                                 }
                   19138:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19139:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19140:                                 }
                   19141:                             }
                   19142:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19143:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19144:                             }
1.1143    raeburn  19145:                         }
                   19146:                     }
                   19147:                 }
                   19148:             }
                   19149:         }
                   19150:     }
1.1391    raeburn  19151:     return $errors;
                   19152: }
                   19153: 
                   19154: sub set_supp_httprefs {
                   19155:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19156:     if (ref($supplemental) eq 'HASH') {
                   19157:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19158:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19159:                 next if ($src =~ /\.sequence$/);
                   19160:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19161:                     my $allowed;
                   19162:                     if ($env{'request.role.adv'}) {
                   19163:                         $allowed = 1;
                   19164:                     } else {
                   19165:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19166:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19167:                                 $allowed = 1;
                   19168:                                 last;
                   19169:                             }
                   19170:                         }
                   19171:                     }
                   19172:                     if (exists($env{'httpref.'.$src})) {
                   19173:                         if ($possdel) {
                   19174:                             unless ($allowed) {
                   19175:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19176:                             }
                   19177:                         }
                   19178:                     } elsif ($allowed) {
                   19179:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19180:                     }
                   19181:                 }
                   19182:             }
                   19183:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19184:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19185:             }
                   19186:         }
                   19187:     }
                   19188: }
                   19189: 
                   19190: sub get_supp_parameter {
                   19191:     my ($resparm,$name)=@_;
                   19192:     return if ($resparm eq '');
                   19193:     my $value=undef;
                   19194:     my $ptype=undef;
                   19195:     foreach (split('&&&',$resparm)) {
                   19196:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19197:         if ($thisname eq $name) {
                   19198:             $value=$thisvalue;
                   19199:             $ptype=$thistype;
                   19200:         }
                   19201:     }
                   19202:     return $value;
1.1143    raeburn  19203: }
                   19204: 
1.1101    raeburn  19205: sub symb_to_docspath {
1.1267    raeburn  19206:     my ($symb,$navmapref) = @_;
                   19207:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19208:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19209:     if ($resurl=~/\.(sequence|page)$/) {
                   19210:         $mapurl=$resurl;
                   19211:     } elsif ($resurl eq 'adm/navmaps') {
                   19212:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19213:     }
                   19214:     my $mapresobj;
1.1267    raeburn  19215:     unless (ref($$navmapref)) {
                   19216:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19217:     }
                   19218:     if (ref($$navmapref)) {
                   19219:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19220:     }
                   19221:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19222:     my $type=$2;
                   19223:     my $path;
                   19224:     if (ref($mapresobj)) {
                   19225:         my $pcslist = $mapresobj->map_hierarchy();
                   19226:         if ($pcslist ne '') {
                   19227:             foreach my $pc (split(/,/,$pcslist)) {
                   19228:                 next if ($pc <= 1);
1.1267    raeburn  19229:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19230:                 if (ref($res)) {
                   19231:                     my $thisurl = $res->src();
                   19232:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19233:                     my $thistitle = $res->title();
                   19234:                     $path .= '&'.
                   19235:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19236:                              &escape($thistitle).
1.1101    raeburn  19237:                              ':'.$res->randompick().
                   19238:                              ':'.$res->randomout().
                   19239:                              ':'.$res->encrypted().
                   19240:                              ':'.$res->randomorder().
                   19241:                              ':'.$res->is_page();
                   19242:                 }
                   19243:             }
                   19244:         }
                   19245:         $path =~ s/^\&//;
                   19246:         my $maptitle = $mapresobj->title();
                   19247:         if ($mapurl eq 'default') {
1.1129    raeburn  19248:             $maptitle = 'Main Content';
1.1101    raeburn  19249:         }
                   19250:         $path .= (($path ne '')? '&' : '').
                   19251:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19252:                  &escape($maptitle).
1.1101    raeburn  19253:                  ':'.$mapresobj->randompick().
                   19254:                  ':'.$mapresobj->randomout().
                   19255:                  ':'.$mapresobj->encrypted().
                   19256:                  ':'.$mapresobj->randomorder().
                   19257:                  ':'.$mapresobj->is_page();
                   19258:     } else {
                   19259:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19260:         my $ispage = (($type eq 'page')? 1 : '');
                   19261:         if ($mapurl eq 'default') {
1.1129    raeburn  19262:             $maptitle = 'Main Content';
1.1101    raeburn  19263:         }
                   19264:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19265:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19266:     }
                   19267:     unless ($mapurl eq 'default') {
                   19268:         $path = 'default&'.
1.1146    raeburn  19269:                 &escape('Main Content').
1.1101    raeburn  19270:                 ':::::&'.$path;
                   19271:     }
                   19272:     return $path;
                   19273: }
                   19274: 
1.1393    raeburn  19275: sub validate_folderpath {
                   19276:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19277:     if ($env{'form.folderpath'} ne '') {
                   19278:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19279:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19280:         for (my $i=0; $i<@items; $i++) {
                   19281:             my $odd = $i%2;
                   19282:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19283:                 $badpath = 1;
1.1394    raeburn  19284:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19285:                 my $idx = $i-1;
1.1394    raeburn  19286:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19287:                     my $esc_name = $1;
                   19288:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19289:                         $supppath .= '&'.$esc_name;
                   19290:                         $changed = 1;
                   19291:                     } else {
                   19292:                         $supppath .= '&'.$items[$i];
                   19293:                     }
                   19294:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19295:                     $changed = 1;
1.1393    raeburn  19296:                     my $is_hidden;
                   19297:                     unless ($got_supp) {
1.1395    raeburn  19298:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19299:                         if (ref($supplemental) eq 'HASH') {
                   19300:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19301:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19302:                             }
                   19303:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19304:                                 %suppids = %{$supplemental->{'ids'}};
                   19305:                             }
                   19306:                         }
                   19307:                         $got_supp = 1;
                   19308:                     }
                   19309:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19310:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19311:                         if ($supphidden{$mapid}) {
                   19312:                             $is_hidden = 1;
                   19313:                         }
                   19314:                     }
1.1394    raeburn  19315:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19316:                 } else {
                   19317:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19318:                 }
                   19319:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19320:                 $badpath = 1;
1.1394    raeburn  19321:             } elsif ($supplementalflag) {
1.1393    raeburn  19322:                 $supppath .= '&'.$items[$i];
                   19323:             }
                   19324:             last if ($badpath);
                   19325:         }
                   19326:         if ($badpath) {
                   19327:             delete($env{'form.folderpath'});
1.1394    raeburn  19328:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19329:             $supppath =~ s/^\&//;
                   19330:             $env{'form.folderpath'} = $supppath;
                   19331:         }
                   19332:     }
                   19333:     return;
                   19334: }
                   19335: 
1.1094    raeburn  19336: sub captcha_display {
1.1327    raeburn  19337:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19338:     my ($output,$error);
1.1234    raeburn  19339:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19340:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19341:     if ($captcha eq 'original') {
1.1094    raeburn  19342:         $output = &create_captcha();
                   19343:         unless ($output) {
1.1172    raeburn  19344:             $error = 'captcha';
1.1094    raeburn  19345:         }
                   19346:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19347:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19348:         unless ($output) {
1.1172    raeburn  19349:             $error = 'recaptcha';
1.1094    raeburn  19350:         }
                   19351:     }
1.1234    raeburn  19352:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19353: }
                   19354: 
                   19355: sub captcha_response {
1.1327    raeburn  19356:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19357:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19358:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19359:     if ($captcha eq 'original') {
1.1094    raeburn  19360:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19361:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19362:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19363:     } else {
                   19364:         $captcha_chk = 1;
                   19365:     }
                   19366:     return ($captcha_chk,$captcha_error);
                   19367: }
                   19368: 
                   19369: sub get_captcha_config {
1.1327    raeburn  19370:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19371:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19372:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19373:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19374:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19375:     if ($context eq 'usercreation') {
                   19376:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19377:         if (ref($domconfig{$context}) eq 'HASH') {
                   19378:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19379:             if (ref($hashtocheck) eq 'HASH') {
                   19380:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19381:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19382:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19383:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19384:                     }
                   19385:                     if ($privkey && $pubkey) {
                   19386:                         $captcha = 'recaptcha';
1.1234    raeburn  19387:                         $version = $hashtocheck->{'recaptchaversion'};
                   19388:                         if ($version ne '2') {
                   19389:                             $version = 1;
                   19390:                         }
1.1095    raeburn  19391:                     } else {
                   19392:                         $captcha = 'original';
                   19393:                     }
                   19394:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19395:                     $captcha = 'original';
                   19396:                 }
1.1094    raeburn  19397:             }
1.1095    raeburn  19398:         } else {
                   19399:             $captcha = 'captcha';
                   19400:         }
                   19401:     } elsif ($context eq 'login') {
                   19402:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19403:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19404:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19405:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19406:             if ($privkey && $pubkey) {
                   19407:                 $captcha = 'recaptcha';
1.1234    raeburn  19408:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19409:                 if ($version ne '2') {
                   19410:                     $version = 1; 
                   19411:                 }
1.1095    raeburn  19412:             } else {
                   19413:                 $captcha = 'original';
1.1094    raeburn  19414:             }
1.1095    raeburn  19415:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19416:             $captcha = 'original';
1.1094    raeburn  19417:         }
1.1327    raeburn  19418:     } elsif ($context eq 'passwords') {
                   19419:         if ($dom_in_effect) {
                   19420:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19421:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19422:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19423:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19424:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19425:                 }
                   19426:                 if ($privkey && $pubkey) {
                   19427:                     $captcha = 'recaptcha';
                   19428:                     $version = $passwdconf{'recaptchaversion'};
                   19429:                     if ($version ne '2') {
                   19430:                         $version = 1;
                   19431:                     }
                   19432:                 } else {
                   19433:                     $captcha = 'original';
                   19434:                 }
                   19435:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19436:                 $captcha = 'original';
                   19437:             }
                   19438:         }
                   19439:     } 
1.1234    raeburn  19440:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19441: }
                   19442: 
                   19443: sub create_captcha {
                   19444:     my %captcha_params = &captcha_settings();
                   19445:     my ($output,$maxtries,$tries) = ('',10,0);
                   19446:     while ($tries < $maxtries) {
                   19447:         $tries ++;
                   19448:         my $captcha = Authen::Captcha->new (
                   19449:                                            output_folder => $captcha_params{'output_dir'},
                   19450:                                            data_folder   => $captcha_params{'db_dir'},
                   19451:                                           );
                   19452:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19453: 
                   19454:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19455:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19456:                       '<span class="LC_nobreak">'.
1.1094    raeburn  19457:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19458:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  19459:                       '</span><br />'.
1.1176    raeburn  19460:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19461:             last;
                   19462:         }
                   19463:     }
1.1323    raeburn  19464:     if ($output eq '') {
                   19465:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19466:     }
1.1094    raeburn  19467:     return $output;
                   19468: }
                   19469: 
                   19470: sub captcha_settings {
                   19471:     my %captcha_params = (
                   19472:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19473:                            www_output_dir => "/captchaspool",
                   19474:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19475:                            numchars       => '5',
                   19476:                          );
                   19477:     return %captcha_params;
                   19478: }
                   19479: 
                   19480: sub check_captcha {
                   19481:     my ($captcha_chk,$captcha_error);
                   19482:     my $code = $env{'form.code'};
                   19483:     my $md5sum = $env{'form.crypt'};
                   19484:     my %captcha_params = &captcha_settings();
                   19485:     my $captcha = Authen::Captcha->new(
                   19486:                       output_folder => $captcha_params{'output_dir'},
                   19487:                       data_folder   => $captcha_params{'db_dir'},
                   19488:                   );
1.1109    raeburn  19489:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19490:     my %captcha_hash = (
                   19491:                         0       => 'Code not checked (file error)',
                   19492:                        -1      => 'Failed: code expired',
                   19493:                        -2      => 'Failed: invalid code (not in database)',
                   19494:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19495:     );
                   19496:     if ($captcha_chk != 1) {
                   19497:         $captcha_error = $captcha_hash{$captcha_chk}
                   19498:     }
                   19499:     return ($captcha_chk,$captcha_error);
                   19500: }
                   19501: 
                   19502: sub create_recaptcha {
1.1234    raeburn  19503:     my ($pubkey,$version) = @_;
                   19504:     if ($version >= 2) {
1.1367    raeburn  19505:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19506:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19507:     } else {
                   19508:         my $use_ssl;
                   19509:         if ($ENV{'SERVER_PORT'} == 443) {
                   19510:             $use_ssl = 1;
                   19511:         }
                   19512:         my $captcha = Captcha::reCAPTCHA->new;
                   19513:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19514:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19515:                &mt('If the text is hard to read, [_1] will replace them.',
                   19516:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19517:                '<br /><br />';
                   19518:     }
1.1094    raeburn  19519: }
                   19520: 
                   19521: sub check_recaptcha {
1.1234    raeburn  19522:     my ($privkey,$version) = @_;
1.1094    raeburn  19523:     my $captcha_chk;
1.1350    raeburn  19524:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19525:     if ($version >= 2) {
                   19526:         my %info = (
                   19527:                      secret   => $privkey, 
                   19528:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19529:                      remoteip => $ip,
1.1234    raeburn  19530:                    );
1.1280    raeburn  19531:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19532:         $request->content(join('&',map {
                   19533:                          my $name = escape($_);
                   19534:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19535:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19536:                          : &escape($info{$_}) );
                   19537:         } keys(%info)));
                   19538:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19539:         if ($response->is_success)  {
                   19540:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19541:             if (ref($data) eq 'HASH') {
                   19542:                 if ($data->{'success'}) {
                   19543:                     $captcha_chk = 1;
                   19544:                 }
                   19545:             }
                   19546:         }
                   19547:     } else {
                   19548:         my $captcha = Captcha::reCAPTCHA->new;
                   19549:         my $captcha_result =
                   19550:             $captcha->check_answer(
                   19551:                                     $privkey,
1.1350    raeburn  19552:                                     $ip,
1.1234    raeburn  19553:                                     $env{'form.recaptcha_challenge_field'},
                   19554:                                     $env{'form.recaptcha_response_field'},
                   19555:                                   );
                   19556:         if ($captcha_result->{is_valid}) {
                   19557:             $captcha_chk = 1;
                   19558:         }
1.1094    raeburn  19559:     }
                   19560:     return $captcha_chk;
                   19561: }
                   19562: 
1.1174    raeburn  19563: sub emailusername_info {
1.1244    raeburn  19564:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19565:     my %titles = &Apache::lonlocal::texthash (
                   19566:                      lastname      => 'Last Name',
                   19567:                      firstname     => 'First Name',
                   19568:                      institution   => 'School/college/university',
                   19569:                      location      => "School's city, state/province, country",
                   19570:                      web           => "School's web address",
                   19571:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19572:                      id            => 'Student/Employee ID',
1.1174    raeburn  19573:                  );
                   19574:     return (\@fields,\%titles);
                   19575: }
                   19576: 
1.1161    raeburn  19577: sub cleanup_html {
                   19578:     my ($incoming) = @_;
                   19579:     my $outgoing;
                   19580:     if ($incoming ne '') {
                   19581:         $outgoing = $incoming;
                   19582:         $outgoing =~ s/;/&#059;/g;
                   19583:         $outgoing =~ s/\#/&#035;/g;
                   19584:         $outgoing =~ s/\&/&#038;/g;
                   19585:         $outgoing =~ s/</&#060;/g;
                   19586:         $outgoing =~ s/>/&#062;/g;
                   19587:         $outgoing =~ s/\(/&#040/g;
                   19588:         $outgoing =~ s/\)/&#041;/g;
                   19589:         $outgoing =~ s/"/&#034;/g;
                   19590:         $outgoing =~ s/'/&#039;/g;
                   19591:         $outgoing =~ s/\$/&#036;/g;
                   19592:         $outgoing =~ s{/}{&#047;}g;
                   19593:         $outgoing =~ s/=/&#061;/g;
                   19594:         $outgoing =~ s/\\/&#092;/g
                   19595:     }
                   19596:     return $outgoing;
                   19597: }
                   19598: 
1.1190    musolffc 19599: # Checks for critical messages and returns a redirect url if one exists.
                   19600: # $interval indicates how often to check for messages.
1.1282    raeburn  19601: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19602: sub critical_redirect {
1.1282    raeburn  19603:     my ($interval,$context) = @_;
1.1356    raeburn  19604:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19605:         return ();
                   19606:     }
1.1190    musolffc 19607:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19608:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19609:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19610:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19611:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19612:             if ($blocked) {
                   19613:                 my $checkrole = "cm./$cdom/$cnum";
                   19614:                 if ($env{'request.course.sec'} ne '') {
                   19615:                     $checkrole .= "/$env{'request.course.sec'}";
                   19616:                 }
                   19617:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19618:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19619:                     return;
                   19620:                 }
                   19621:             }
                   19622:         }
1.1190    musolffc 19623:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19624:                                         $env{'user.name'});
                   19625:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19626:         my $redirecturl;
1.1190    musolffc 19627:         if ($what[0]) {
1.1356    raeburn  19628: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19629: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19630: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19631:                 return (1, $url);
1.1190    musolffc 19632:             }
1.1191    raeburn  19633:         }
                   19634:     } 
                   19635:     return ();
1.1190    musolffc 19636: }
                   19637: 
1.1174    raeburn  19638: # Use:
                   19639: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19640: #
                   19641: ##################################################
                   19642: #          password associated functions         #
                   19643: ##################################################
                   19644: sub des_keys {
                   19645:     # Make a new key for DES encryption.
                   19646:     # Each key has two parts which are returned separately.
                   19647:     # Please note:  Each key must be passed through the &hex function
                   19648:     # before it is output to the web browser.  The hex versions cannot
                   19649:     # be used to decrypt.
                   19650:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19651:                 '8','9','a','b','c','d','e','f');
                   19652:     my $lkey='';
                   19653:     for (0..7) {
                   19654:         $lkey.=$hexstr[rand(15)];
                   19655:     }
                   19656:     my $ukey='';
                   19657:     for (0..7) {
                   19658:         $ukey.=$hexstr[rand(15)];
                   19659:     }
                   19660:     return ($lkey,$ukey);
                   19661: }
                   19662: 
                   19663: sub des_decrypt {
                   19664:     my ($key,$cyphertext) = @_;
                   19665:     my $keybin=pack("H16",$key);
                   19666:     my $cypher;
                   19667:     if ($Crypt::DES::VERSION>=2.03) {
                   19668:         $cypher=new Crypt::DES $keybin;
                   19669:     } else {
                   19670:         $cypher=new DES $keybin;
                   19671:     }
1.1233    raeburn  19672:     my $plaintext='';
                   19673:     my $cypherlength = length($cyphertext);
                   19674:     my $numchunks = int($cypherlength/32);
                   19675:     for (my $j=0; $j<$numchunks; $j++) {
                   19676:         my $start = $j*32;
                   19677:         my $cypherblock = substr($cyphertext,$start,32);
                   19678:         my $chunk =
                   19679:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19680:         $chunk .=
                   19681:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19682:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19683:         $plaintext .= $chunk;
                   19684:     }
1.1174    raeburn  19685:     return $plaintext;
                   19686: }
                   19687: 
1.1344    raeburn  19688: sub get_requested_shorturls {
1.1309    raeburn  19689:     my ($cdom,$cnum,$navmap) = @_;
                   19690:     return unless (ref($navmap));
1.1344    raeburn  19691:     my ($numnew,$errors);
1.1309    raeburn  19692:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19693:     if (@toshorten) {
                   19694:         my (%maps,%resources,%titles);
                   19695:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19696:                                                                'shorturls',$cdom,$cnum);
                   19697:         if (keys(%resources)) {
1.1344    raeburn  19698:             my %tocreate;
1.1309    raeburn  19699:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19700:                 my $symb = $resources{$item};
                   19701:                 if ($symb) {
                   19702:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19703:                 }
                   19704:             }
1.1344    raeburn  19705:             if (keys(%tocreate)) {
                   19706:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19707:                                                       \%tocreate);
                   19708:             }
1.1309    raeburn  19709:         }
1.1344    raeburn  19710:     }
                   19711:     return ($numnew,$errors);
                   19712: }
                   19713: 
                   19714: sub make_short_symbs {
                   19715:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19716:     my ($numnew,@errors);
                   19717:     if (ref($tocreateref) eq 'HASH') {
                   19718:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19719:         if (keys(%tocreate)) {
                   19720:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19721:             my $su = Short::URL->new(no_vowels => 1);
                   19722:             my $init = '';
                   19723:             my (%newunique,%addcourse,%courseonly,%failed);
                   19724:             # get lock on tiny db
                   19725:             my $now = time;
1.1344    raeburn  19726:             if ($lockuser eq '') {
                   19727:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19728:             }
1.1309    raeburn  19729:             my $lockhash = {
1.1344    raeburn  19730:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19731:                             };
                   19732:             my $tries = 0;
                   19733:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19734:             my ($code,$error);
                   19735:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19736:                 $tries ++;
                   19737:                 sleep 1;
1.1319    raeburn  19738:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19739:             }
                   19740:             if ($gotlock eq 'ok') {
                   19741:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19742:                                        \%addcourse,\%courseonly,\%failed);
                   19743:                 if (keys(%failed)) {
                   19744:                     my $numfailed = scalar(keys(%failed));
                   19745:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19746:                 }
                   19747:                 if (keys(%newunique)) {
                   19748:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19749:                     if ($putres eq 'ok') {
                   19750:                         $numnew = scalar(keys(%newunique));
                   19751:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19752:                         unless ($newputres eq 'ok') {
                   19753:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19754:                         }
                   19755:                     } else {
                   19756:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19757:                     }
                   19758:                 }
                   19759:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19760:                 unless ($dellockres eq 'ok') {
                   19761:                     push(@errors,&mt('error: could not release lockfile'));
                   19762:                 }
                   19763:             } else {
                   19764:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19765:             }
                   19766:             if (keys(%courseonly)) {
                   19767:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19768:                 if ($result ne 'ok') {
                   19769:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19770:                 }
                   19771:             }
                   19772:         }
                   19773:     }
                   19774:     return ($numnew,\@errors);
                   19775: }
                   19776: 
                   19777: sub shorten_symbs {
                   19778:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19779:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19780:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19781:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19782:     my (%possibles,%collisions);
                   19783:     foreach my $key (keys(%{$tocreate})) {
                   19784:         my $num = String::CRC32::crc32($key);
                   19785:         my $tiny = $su->encode($num,$init);
                   19786:         if ($tiny) {
                   19787:             $possibles{$tiny} = $key;
                   19788:         }
                   19789:     }
                   19790:     if (!$init) {
                   19791:         $init = 1;
                   19792:     } else {
                   19793:         $init ++;
                   19794:     }
                   19795:     if (keys(%possibles)) {
                   19796:         my @posstiny = keys(%possibles);
                   19797:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19798:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19799:         if (keys(%currtiny)) {
                   19800:             foreach my $key (keys(%currtiny)) {
                   19801:                 next if ($currtiny{$key} eq '');
                   19802:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19803:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19804:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19805:                         $courseonly->{$tsymb} = $key;
                   19806:                     }
                   19807:                 } else {
                   19808:                     $collisions{$possibles{$key}} = 1;
                   19809:                 }
                   19810:                 delete($possibles{$key});
                   19811:             }
                   19812:         }
                   19813:         foreach my $key (keys(%possibles)) {
                   19814:             $newunique->{$key} = $possibles{$key};
                   19815:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19816:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19817:                 $addcourse->{$tsymb} = $key;
                   19818:             }
                   19819:         }
                   19820:     }
                   19821:     if (keys(%collisions)) {
                   19822:         if ($init <5) {
                   19823:             if (!$init) {
                   19824:                 $init = 1;
                   19825:             } else {
                   19826:                 $init ++;
                   19827:             }
                   19828:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19829:                                    $newunique,$addcourse,$courseonly,$failed);
                   19830:         } else {
                   19831:             foreach my $key (keys(%collisions)) {
                   19832:                 $failed->{$key} = 1;
                   19833:             }
                   19834:         }
                   19835:     }
                   19836:     return $init;
                   19837: }
                   19838: 
1.1328    raeburn  19839: sub is_nonframeable {
1.1329    raeburn  19840:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19841:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19842:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19843: 
                   19844:     $remprotocol = lc($remprotocol);
                   19845:     $remhost = lc($remhost);
                   19846:     my $remport = 80;
                   19847:     if ($remprotocol eq 'https') {
                   19848:         $remport = 443;
                   19849:     }
1.1330    raeburn  19850:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19851:     if ($cached) {
                   19852:         unless ($nocache) {
                   19853:             if ($result) {
                   19854:                 return 1;
                   19855:             } else {
                   19856:                 return 0;
                   19857:             }
                   19858:         }
                   19859:     }
1.1328    raeburn  19860:     my $uselink;
                   19861:     my $request = new HTTP::Request('HEAD',$url);
                   19862:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19863:     if ($response->is_success()) {
                   19864:         my $secpolicy = lc($response->header('content-security-policy'));
                   19865:         my $xframeop = lc($response->header('x-frame-options'));
                   19866:         $secpolicy =~ s/^\s+|\s+$//g;
                   19867:         $xframeop =~ s/^\s+|\s+$//g;
                   19868:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19869:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19870:             my ($origin,$protocol,$port);
                   19871:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19872:                 $port = $ENV{'SERVER_PORT'};
                   19873:             } else {
                   19874:                 $port = 80;
                   19875:             }
                   19876:             if ($absolute eq '') {
                   19877:                 $protocol = 'http:';
                   19878:                 if ($port == 443) {
                   19879:                     $protocol = 'https:';
                   19880:                 }
                   19881:                 $origin = $protocol.'//'.lc($hostname);
                   19882:             } else {
                   19883:                 $origin = lc($absolute);
                   19884:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19885:             }
                   19886:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19887:                 my $framepolicy = $1;
                   19888:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19889:                 my @policies = split(/\s+/,$framepolicy);
                   19890:                 if (@policies) {
                   19891:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19892:                         $uselink = 1;
                   19893:                     } else {
                   19894:                         $uselink = 1;
                   19895:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19896:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19897:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19898:                             undef($uselink);
                   19899:                         }
                   19900:                         if ($uselink) {
                   19901:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19902:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19903:                                     undef($uselink);
                   19904:                                 }
                   19905:                             }
                   19906:                         }
                   19907:                         if ($uselink) {
                   19908:                             my @possok;
                   19909:                             if ($ip ne '') {
                   19910:                                 push(@possok,$ip);
                   19911:                             }
                   19912:                             my $hoststr = '';
                   19913:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19914:                                 if ($hoststr eq '') {
                   19915:                                     $hoststr = $part;
                   19916:                                 } else {
                   19917:                                     $hoststr = "$part.$hoststr";
                   19918:                                 }
                   19919:                                 if ($hoststr eq $hostname) {
                   19920:                                     push(@possok,$hostname);
                   19921:                                 } else {
                   19922:                                     push(@possok,"*.$hoststr");
                   19923:                                 }
                   19924:                             }
                   19925:                             if (@possok) {
                   19926:                                 foreach my $poss (@possok) {
                   19927:                                     last if (!$uselink);
                   19928:                                     foreach my $policy (@policies) {
                   19929:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19930:                                             undef($uselink);
                   19931:                                             last;
                   19932:                                         }
                   19933:                                     }
                   19934:                                 }
                   19935:                             }
                   19936:                         }
                   19937:                     }
                   19938:                 }
                   19939:             } elsif ($xframeop ne '') {
                   19940:                 $uselink = 1;
                   19941:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19942:                 if (@policies) {
                   19943:                     unless (grep(/^deny$/,@policies)) {
                   19944:                         if ($origin ne '') {
                   19945:                             if (grep(/^sameorigin$/,@policies)) {
                   19946:                                 if ($remotehost eq $origin) {
                   19947:                                     undef($uselink);
                   19948:                                 }
                   19949:                             }
                   19950:                             if ($uselink) {
                   19951:                                 foreach my $policy (@policies) {
                   19952:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19953:                                         my $allowfrom = $1;
                   19954:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19955:                                             undef($uselink);
                   19956:                                             last;
                   19957:                                         }
                   19958:                                     }
                   19959:                                 }
                   19960:                             }
                   19961:                         }
                   19962:                     }
                   19963:                 }
                   19964:             }
                   19965:         }
                   19966:     }
1.1329    raeburn  19967:     if ($nocache) {
                   19968:         if ($cached) {
                   19969:             my $devalidate;
                   19970:             if ($uselink && !$result) {
                   19971:                 $devalidate = 1;
                   19972:             } elsif (!$uselink && $result) {
                   19973:                 $devalidate = 1;
                   19974:             }
                   19975:             if ($devalidate) {
                   19976:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19977:             }
                   19978:         }
                   19979:     } else {
                   19980:         if ($uselink) {
                   19981:             $result = 1;
                   19982:         } else {
                   19983:             $result = 0;
                   19984:         }
                   19985:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19986:     }
1.1328    raeburn  19987:     return $uselink;
                   19988: }
                   19989: 
1.1359    raeburn  19990: sub page_menu {
                   19991:     my ($menucolls,$menunum) = @_;
                   19992:     my %menu;
                   19993:     foreach my $item (split(/;/,$menucolls)) {
                   19994:         my ($num,$value) = split(/\%/,$item);
                   19995:         if ($num eq $menunum) {
                   19996:             my @entries = split(/\&/,$value);
                   19997:             foreach my $entry (@entries) {
                   19998:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19999:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20000:                     $menu{$name} = $fields;
                   20001:                 } else {
                   20002:                     my @shown;
                   20003:                     if ($fields =~ /,/) {
                   20004:                         @shown = split(/,/,$fields);
                   20005:                     } else {
                   20006:                         @shown = ($fields);
                   20007:                     }
                   20008:                     if (@shown) {
                   20009:                         foreach my $field (@shown) {
                   20010:                             next if ($field eq '');
                   20011:                             $menu{$field} = 1;
                   20012:                         }
                   20013:                     }
                   20014:                 }
                   20015:             }
                   20016:         }
                   20017:     }
                   20018:     return %menu;
                   20019: }
                   20020: 
1.112     bowersj2 20021: 1;
                   20022: __END__;
1.41      ng       20023: 

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