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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1409  ! raeburn     4: # $Id: loncommon.pm,v 1.1408 2023/06/20 14:03:52 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.1337    raeburn   440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
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.102     www       461:         var title = 'Student_Browser';
1.74      www       462:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    463:         options += ',width=700,height=600';
                    464:         stdeditbrowser = open(url,title,options,'1');
                    465:         stdeditbrowser.focus();
                    466:     }
1.824     bisitz    467: // ]]>
1.74      www       468: </script>
                    469: ENDSTDBRW
                    470: }
1.42      matthew   471: 
1.1003    www       472: sub resourcebrowser_javascript {
                    473:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       474:    return (<<'ENDRESBRW');
1.1003    www       475: <script type="text/javascript" language="Javascript">
                    476: // <![CDATA[
                    477:     var reseditbrowser;
1.1004    www       478:     function openresbrowser(formname,reslink) {
1.1005    www       479:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       480:         var title = 'Resource_Browser';
                    481:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       482:         options += ',width=700,height=500';
1.1004    www       483:         reseditbrowser = open(url,title,options,'1');
                    484:         reseditbrowser.focus();
1.1003    www       485:     }
                    486: // ]]>
                    487: </script>
1.1004    www       488: ENDRESBRW
1.1003    www       489: }
                    490: 
1.74      www       491: sub selectstudent_link {
1.1337    raeburn   492:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       493:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    494:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    495:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  496:    if ($env{'request.course.id'}) {  
1.302     albertel  497:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    498: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    499: 					'/'.$env{'request.course.sec'})) {
1.111     www       500: 	   return '';
                    501:        }
1.999     www       502:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   503:        if ($courseadv eq 'only') {
                    504:            $callargs .= ",'',1,'$courseadv'";
                    505:        } elsif ($courseadv eq 'none') {
                    506:            $callargs .= ",'','','$courseadv'";
                    507:        } elsif ($courseadv eq 'condition') {
                    508:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   509:        }
                    510:        return '<span class="LC_nobreak">'.
                    511:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    512:               &mt('Select User').'</a></span>';
1.74      www       513:    }
1.258     albertel  514:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       515:        $callargs .= ",'',1"; 
1.793     raeburn   516:        return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    518:               &mt('Select User').'</a></span>';
1.111     www       519:    }
                    520:    return '';
1.91      www       521: }
                    522: 
1.1004    www       523: sub selectresource_link {
                    524:    my ($form,$reslink,$arg)=@_;
                    525:    
                    526:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    527:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    528:    unless ($env{'request.course.id'}) { return $arg; }
                    529:    return '<span class="LC_nobreak">'.
                    530:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    531:               $arg.'</a></span>';
                    532: }
                    533: 
                    534: 
                    535: 
1.653     raeburn   536: sub authorbrowser_javascript {
                    537:     return <<"ENDAUTHORBRW";
1.776     bisitz    538: <script type="text/javascript" language="JavaScript">
1.824     bisitz    539: // <![CDATA[
1.653     raeburn   540: var stdeditbrowser;
                    541: 
                    542: function openauthorbrowser(formname,udom) {
                    543:     var url = '/adm/pickauthor?';
                    544:     url += 'form='+formname+'&roledom='+udom;
                    545:     var title = 'Author_Browser';
                    546:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    547:     options += ',width=700,height=600';
                    548:     stdeditbrowser = open(url,title,options,'1');
                    549:     stdeditbrowser.focus();
                    550: }
                    551: 
1.824     bisitz    552: // ]]>
1.653     raeburn   553: </script>
                    554: ENDAUTHORBRW
                    555: }
                    556: 
1.91      www       557: sub coursebrowser_javascript {
1.1116    raeburn   558:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   559:         $credits_element,$instcode) = @_;
1.932     raeburn   560:     my $wintitle = 'Course_Browser';
1.931     raeburn   561:     if ($crstype eq 'Community') {
1.932     raeburn   562:         $wintitle = 'Community_Browser';
1.909     raeburn   563:     }
1.876     raeburn   564:     my $id_functions = &javascript_index_functions();
                    565:     my $output = '
1.776     bisitz    566: <script type="text/javascript" language="JavaScript">
1.824     bisitz    567: // <![CDATA[
1.468     raeburn   568:     var stdeditbrowser;'."\n";
1.876     raeburn   569: 
                    570:     $output .= <<"ENDSTDBRW";
1.909     raeburn   571:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       572:         var url = '/adm/pickcourse?';
1.895     raeburn   573:         var formid = getFormIdByName(formname);
1.876     raeburn   574:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  575:         if (domainfilter != null) {
                    576:            if (domainfilter != '') {
                    577:                url += 'domainfilter='+domainfilter+'&';
                    578: 	   }
                    579:         }
1.91      www       580:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  581: 	                            '&cdomelement='+udom+
                    582:                                     '&cnameelement='+desc;
1.468     raeburn   583:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   584:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   585:                 url += '&roleelement='+extra_element;
                    586:                 if (domainfilter == null || domainfilter == '') {
                    587:                     url += '&domainfilter='+extra_element;
                    588:                 }
1.234     raeburn   589:             }
1.468     raeburn   590:             else {
                    591:                 if (formname == 'portform') {
                    592:                     url += '&setroles='+extra_element;
1.800     raeburn   593:                 } else {
                    594:                     if (formname == 'rules') {
                    595:                         url += '&fixeddom='+extra_element; 
                    596:                     }
1.468     raeburn   597:                 }
                    598:             }     
1.230     raeburn   599:         }
1.909     raeburn   600:         if (type != null && type != '') {
                    601:             url += '&type='+type;
                    602:         }
                    603:         if (type_elem != null && type_elem != '') {
                    604:             url += '&typeelement='+type_elem;
                    605:         }
1.872     raeburn   606:         if (formname == 'ccrs') {
                    607:             var ownername = document.forms[formid].ccuname.value;
                    608:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   609:             url += '&cloner='+ownername+':'+ownerdom;
                    610:             if (type == 'Course') {
                    611:                 url += '&crscode='+document.forms[formid].crscode.value;
                    612:             }
1.1221    raeburn   613:         }
                    614:         if (formname == 'requestcrs') {
                    615:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   616:         }
1.293     raeburn   617:         if (multflag !=null && multflag != '') {
                    618:             url += '&multiple='+multflag;
                    619:         }
1.909     raeburn   620:         var title = '$wintitle';
1.91      www       621:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    622:         options += ',width=700,height=600';
                    623:         stdeditbrowser = open(url,title,options,'1');
                    624:         stdeditbrowser.focus();
                    625:     }
1.876     raeburn   626: $id_functions
                    627: ENDSTDBRW
1.1116    raeburn   628:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    629:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    630:                                       $credits_element);
1.876     raeburn   631:     }
                    632:     $output .= '
                    633: // ]]>
                    634: </script>';
                    635:     return $output;
                    636: }
                    637: 
                    638: sub javascript_index_functions {
                    639:     return <<"ENDJS";
                    640: 
                    641: function getFormIdByName(formname) {
                    642:     for (var i=0;i<document.forms.length;i++) {
                    643:         if (document.forms[i].name == formname) {
                    644:             return i;
                    645:         }
                    646:     }
                    647:     return -1;
                    648: }
                    649: 
                    650: function getIndexByName(formid,item) {
                    651:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    652:         if (document.forms[formid].elements[i].name == item) {
                    653:             return i;
                    654:         }
                    655:     }
                    656:     return -1;
                    657: }
1.468     raeburn   658: 
1.876     raeburn   659: function getDomainFromSelectbox(formname,udom) {
                    660:     var userdom;
                    661:     var formid = getFormIdByName(formname);
                    662:     if (formid > -1) {
                    663:         var domid = getIndexByName(formid,udom);
                    664:         if (domid > -1) {
                    665:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    666:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    667:             }
                    668:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    669:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   670:             }
                    671:         }
                    672:     }
1.876     raeburn   673:     return userdom;
                    674: }
                    675: 
                    676: ENDJS
1.468     raeburn   677: 
1.876     raeburn   678: }
                    679: 
1.1017    raeburn   680: sub javascript_array_indexof {
1.1018    raeburn   681:     return <<ENDJS;
1.1017    raeburn   682: <script type="text/javascript" language="JavaScript">
                    683: // <![CDATA[
                    684: 
                    685: if (!Array.prototype.indexOf) {
                    686:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    687:         "use strict";
                    688:         if (this === void 0 || this === null) {
                    689:             throw new TypeError();
                    690:         }
                    691:         var t = Object(this);
                    692:         var len = t.length >>> 0;
                    693:         if (len === 0) {
                    694:             return -1;
                    695:         }
                    696:         var n = 0;
                    697:         if (arguments.length > 0) {
                    698:             n = Number(arguments[1]);
1.1088    foxr      699:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   700:                 n = 0;
                    701:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    702:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    703:             }
                    704:         }
                    705:         if (n >= len) {
                    706:             return -1;
                    707:         }
                    708:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    709:         for (; k < len; k++) {
                    710:             if (k in t && t[k] === searchElement) {
                    711:                 return k;
                    712:             }
                    713:         }
                    714:         return -1;
                    715:     }
                    716: }
                    717: 
                    718: // ]]>
                    719: </script>
                    720: 
                    721: ENDJS
                    722: 
                    723: }
                    724: 
1.876     raeburn   725: sub userbrowser_javascript {
                    726:     my $id_functions = &javascript_index_functions();
                    727:     return <<"ENDUSERBRW";
                    728: 
1.888     raeburn   729: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   730:     var url = '/adm/pickuser?';
                    731:     var userdom = getDomainFromSelectbox(formname,udom);
                    732:     if (userdom != null) {
                    733:        if (userdom != '') {
                    734:            url += 'srchdom='+userdom+'&';
                    735:        }
                    736:     }
                    737:     url += 'form=' + formname + '&unameelement='+uname+
                    738:                                 '&udomelement='+udom+
                    739:                                 '&ulastelement='+ulast+
                    740:                                 '&ufirstelement='+ufirst+
                    741:                                 '&uemailelement='+uemail+
1.881     raeburn   742:                                 '&hideudomelement='+hideudom+
                    743:                                 '&coursedom='+crsdom;
1.888     raeburn   744:     if ((caller != null) && (caller != undefined)) {
                    745:         url += '&caller='+caller;
                    746:     }
1.876     raeburn   747:     var title = 'User_Browser';
                    748:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    749:     options += ',width=700,height=600';
                    750:     var stdeditbrowser = open(url,title,options,'1');
                    751:     stdeditbrowser.focus();
                    752: }
                    753: 
1.888     raeburn   754: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   755:     var formid = getFormIdByName(formname);
                    756:     if (formid > -1) {
1.888     raeburn   757:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   758:         var domid = getIndexByName(formid,udom);
                    759:         var hidedomid = getIndexByName(formid,origdom);
                    760:         if (hidedomid > -1) {
                    761:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   762:             var unameval = document.forms[formid].elements[unameid].value;
                    763:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    764:                 if (domid > -1) {
                    765:                     var slct = document.forms[formid].elements[domid];
                    766:                     if (slct.type == 'select-one') {
                    767:                         var i;
                    768:                         for (i=0;i<slct.length;i++) {
                    769:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    770:                         }
                    771:                     }
                    772:                     if (slct.type == 'hidden') {
                    773:                         slct.value = fixeddom;
1.876     raeburn   774:                     }
                    775:                 }
1.468     raeburn   776:             }
                    777:         }
                    778:     }
1.876     raeburn   779:     return;
                    780: }
                    781: 
                    782: $id_functions
                    783: ENDUSERBRW
1.468     raeburn   784: }
                    785: 
                    786: sub setsec_javascript {
1.1116    raeburn   787:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   788:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    789:         $communityrolestr);
                    790:     if ($role_element ne '') {
                    791:         my @allroles = ('st','ta','ep','in','ad');
                    792:         foreach my $crstype ('Course','Community') {
                    793:             if ($crstype eq 'Community') {
                    794:                 foreach my $role (@allroles) {
                    795:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    796:                 }
                    797:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    798:             } else {
                    799:                 foreach my $role (@allroles) {
                    800:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    801:                 }
                    802:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    803:             }
                    804:         }
                    805:         $rolestr = '"'.join('","',@allroles).'"';
                    806:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    807:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    808:     }
1.468     raeburn   809:     my $setsections = qq|
                    810: function setSect(sectionlist) {
1.629     raeburn   811:     var sectionsArray = new Array();
                    812:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    813:         sectionsArray = sectionlist.split(",");
                    814:     }
1.468     raeburn   815:     var numSections = sectionsArray.length;
                    816:     document.$formname.$sec_element.length = 0;
                    817:     if (numSections == 0) {
                    818:         document.$formname.$sec_element.multiple=false;
                    819:         document.$formname.$sec_element.size=1;
                    820:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    821:     } else {
                    822:         if (numSections == 1) {
                    823:             document.$formname.$sec_element.multiple=false;
                    824:             document.$formname.$sec_element.size=1;
                    825:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    826:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    827:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    828:         } else {
                    829:             for (var i=0; i<numSections; i++) {
                    830:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    831:             }
                    832:             document.$formname.$sec_element.multiple=true
                    833:             if (numSections < 3) {
                    834:                 document.$formname.$sec_element.size=numSections;
                    835:             } else {
                    836:                 document.$formname.$sec_element.size=3;
                    837:             }
                    838:             document.$formname.$sec_element.options[0].selected = false
                    839:         }
                    840:     }
1.91      www       841: }
1.905     raeburn   842: 
                    843: function setRole(crstype) {
1.468     raeburn   844: |;
1.905     raeburn   845:     if ($role_element eq '') {
                    846:         $setsections .= '    return;
                    847: }
                    848: ';
                    849:     } else {
                    850:         $setsections .= qq|
                    851:     var elementLength = document.$formname.$role_element.length;
                    852:     var allroles = Array($rolestr);
                    853:     var courserolenames = Array($courserolestr);
                    854:     var communityrolenames = Array($communityrolestr);
                    855:     if (elementLength != undefined) {
                    856:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    857:             if (crstype == 'Course') {
                    858:                 return;
                    859:             } else {
                    860:                 allroles[5] = 'co';
                    861:                 for (var i=0; i<6; i++) {
                    862:                     document.$formname.$role_element.options[i].value = allroles[i];
                    863:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    864:                 }
                    865:             }
                    866:         } else {
                    867:             if (crstype == 'Community') {
                    868:                 return;
                    869:             } else {
                    870:                 allroles[5] = 'cc';
                    871:                 for (var i=0; i<6; i++) {
                    872:                     document.$formname.$role_element.options[i].value = allroles[i];
                    873:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    874:                 }
                    875:             }
                    876:         }
                    877:     }
                    878:     return;
                    879: }
                    880: |;
                    881:     }
1.1116    raeburn   882:     if ($credits_element) {
                    883:         $setsections .= qq|
                    884: function setCredits(defaultcredits) {
                    885:     document.$formname.$credits_element.value = defaultcredits;
                    886:     return;
                    887: }
                    888: |;
                    889:     }
1.468     raeburn   890:     return $setsections;
                    891: }
                    892: 
1.91      www       893: sub selectcourse_link {
1.909     raeburn   894:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    895:        $typeelement) = @_;
                    896:    my $type = $selecttype;
1.871     raeburn   897:    my $linktext = &mt('Select Course');
                    898:    if ($selecttype eq 'Community') {
1.909     raeburn   899:        $linktext = &mt('Select Community');
1.1239    raeburn   900:    } elsif ($selecttype eq 'Placement') {
                    901:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   902:    } elsif ($selecttype eq 'Course/Community') {
                    903:        $linktext = &mt('Select Course/Community');
1.909     raeburn   904:        $type = '';
1.1019    raeburn   905:    } elsif ($selecttype eq 'Select') {
                    906:        $linktext = &mt('Select');
                    907:        $type = '';
1.871     raeburn   908:    }
1.787     bisitz    909:    return '<span class="LC_nobreak">'
                    910:          ."<a href='"
                    911:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    912:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   913:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   914:          ."'>".$linktext.'</a>'
1.787     bisitz    915:          .'</span>';
1.74      www       916: }
1.42      matthew   917: 
1.653     raeburn   918: sub selectauthor_link {
                    919:    my ($form,$udom)=@_;
                    920:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    921:           &mt('Select Author').'</a>';
                    922: }
                    923: 
1.876     raeburn   924: sub selectuser_link {
1.881     raeburn   925:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   926:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   927:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   928:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   929:            ');">'.$linktext.'</a>';
1.876     raeburn   930: }
                    931: 
1.273     raeburn   932: sub check_uncheck_jscript {
                    933:     my $jscript = <<"ENDSCRT";
                    934: function checkAll(field) {
                    935:     if (field.length > 0) {
                    936:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   937:             if (!field[i].disabled) { 
                    938:                 field[i].checked = true;
                    939:             }
1.273     raeburn   940:         }
                    941:     } else {
1.1093    raeburn   942:         if (!field.disabled) { 
                    943:             field.checked = true;
                    944:         }
1.273     raeburn   945:     }
                    946: }
                    947:  
                    948: function uncheckAll(field) {
                    949:     if (field.length > 0) {
                    950:         for (i = 0; i < field.length; i++) {
                    951:             field[i].checked = false ;
1.543     albertel  952:         }
                    953:     } else {
1.273     raeburn   954:         field.checked = false ;
                    955:     }
                    956: }
                    957: ENDSCRT
                    958:     return $jscript;
                    959: }
                    960: 
1.656     www       961: sub select_timezone {
1.1387    raeburn   962:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    963:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   964:    if ($includeempty) {
                    965:        $output .= '<option value=""';
                    966:        if (($selected eq '') || ($selected eq 'local')) {
                    967:            $output .= ' selected="selected" ';
                    968:        }
                    969:        $output .= '> </option>';
                    970:    }
1.657     raeburn   971:    my @timezones = DateTime::TimeZone->all_names;
                    972:    foreach my $tzone (@timezones) {
                    973:        $output.= '<option value="'.$tzone.'"';
                    974:        if ($tzone eq $selected) {
                    975:            $output.=' selected="selected"';
                    976:        }
                    977:        $output.=">$tzone</option>\n";
1.656     www       978:    }
                    979:    $output.="</select>";
                    980:    return $output;
                    981: }
1.273     raeburn   982: 
1.687     raeburn   983: sub select_datelocale {
1.1256    raeburn   984:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    985:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   986:     if ($includeempty) {
                    987:         $output .= '<option value=""';
                    988:         if ($selected eq '') {
                    989:             $output .= ' selected="selected" ';
                    990:         }
                    991:         $output .= '> </option>';
                    992:     }
1.1241    raeburn   993:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   994:     my (@possibles,%locale_names);
1.1241    raeburn   995:     my @locales = DateTime::Locale->ids();
                    996:     foreach my $id (@locales) {
                    997:         if ($id ne '') {
                    998:             my ($en_terr,$native_terr);
                    999:             my $loc = DateTime::Locale->load($id);
                   1000:             if (ref($loc)) {
                   1001:                 $en_terr = $loc->name();
                   1002:                 $native_terr = $loc->native_name();
1.687     raeburn  1003:                 if (grep(/^en$/,@languages) || !@languages) {
                   1004:                     if ($en_terr ne '') {
                   1005:                         $locale_names{$id} = '('.$en_terr.')';
                   1006:                     } elsif ($native_terr ne '') {
                   1007:                         $locale_names{$id} = $native_terr;
                   1008:                     }
                   1009:                 } else {
                   1010:                     if ($native_terr ne '') {
                   1011:                         $locale_names{$id} = $native_terr.' ';
                   1012:                     } elsif ($en_terr ne '') {
                   1013:                         $locale_names{$id} = '('.$en_terr.')';
                   1014:                     }
                   1015:                 }
1.1220    raeburn  1016:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1017:                 push(@possibles,$id);
                   1018:             } 
1.687     raeburn  1019:         }
                   1020:     }
                   1021:     foreach my $item (sort(@possibles)) {
                   1022:         $output.= '<option value="'.$item.'"';
                   1023:         if ($item eq $selected) {
                   1024:             $output.=' selected="selected"';
                   1025:         }
                   1026:         $output.=">$item";
                   1027:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1028:             $output.='  '.$locale_names{$item};
1.687     raeburn  1029:         }
                   1030:         $output.="</option>\n";
                   1031:     }
                   1032:     $output.="</select>";
                   1033:     return $output;
                   1034: }
                   1035: 
1.792     raeburn  1036: sub select_language {
1.1256    raeburn  1037:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1038:     my %langchoices;
                   1039:     if ($includeempty) {
1.1117    raeburn  1040:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1041:     }
                   1042:     foreach my $id (&languageids()) {
                   1043:         my $code = &supportedlanguagecode($id);
                   1044:         if ($code) {
                   1045:             $langchoices{$code} = &plainlanguagedescription($id);
                   1046:         }
                   1047:     }
1.1117    raeburn  1048:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1049:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1050: }
                   1051: 
1.42      matthew  1052: =pod
1.36      matthew  1053: 
1.1088    foxr     1054: 
                   1055: =item * &list_languages()
                   1056: 
                   1057: Returns an array reference that is suitable for use in language prompters.
                   1058: Each array element is itself a two element array.  The first element
                   1059: is the language code.  The second element a descsriptiuon of the 
                   1060: language itself.  This is suitable for use in e.g.
                   1061: &Apache::edit::select_arg (once dereferenced that is).
                   1062: 
                   1063: =cut 
                   1064: 
                   1065: sub list_languages {
                   1066:     my @lang_choices;
                   1067: 
                   1068:     foreach my $id (&languageids()) {
                   1069: 	my $code = &supportedlanguagecode($id);
                   1070: 	if ($code) {
                   1071: 	    my $selector    = $supported_codes{$id};
                   1072: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1073: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1074: 	}
                   1075:     }
                   1076:     return \@lang_choices;
                   1077: }
                   1078: 
                   1079: =pod
                   1080: 
1.648     raeburn  1081: =item * &linked_select_forms(...)
1.36      matthew  1082: 
                   1083: linked_select_forms returns a string containing a <script></script> block
                   1084: and html for two <select> menus.  The select menus will be linked in that
                   1085: changing the value of the first menu will result in new values being placed
                   1086: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1087: order unless a defined order is provided.
1.36      matthew  1088: 
                   1089: linked_select_forms takes the following ordered inputs:
                   1090: 
                   1091: =over 4
                   1092: 
1.112     bowersj2 1093: =item * $formname, the name of the <form> tag
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstdefault, the default value for the first menu
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1102: 
1.112     bowersj2 1103: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1104: 
1.609     raeburn  1105: =item * $menuorder, the order of values in the first menu
                   1106: 
1.1115    raeburn  1107: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1108:         event for the first <select> tag
                   1109: 
                   1110: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1111:         event for the second <select> tag
                   1112: 
1.1245    raeburn  1113: =item * $suffix, to differentiate separate uses of select2data javascript
                   1114:         objects in a page.
                   1115: 
1.41      ng       1116: =back 
                   1117: 
1.36      matthew  1118: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1119: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1120: values for the first select menu.  The text that coincides with the 
1.41      ng       1121: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1122: and text for the second menu are given in the hash pointed to by 
                   1123: $menu{$choice1}->{'select2'}.  
                   1124: 
1.112     bowersj2 1125:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1126:                        default => "B3",
                   1127:                        select2 => { 
                   1128:                            B1 => "Choice B1",
                   1129:                            B2 => "Choice B2",
                   1130:                            B3 => "Choice B3",
                   1131:                            B4 => "Choice B4"
1.609     raeburn  1132:                            },
                   1133:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1134:                    },
                   1135:                A2 => { text =>"Choice A2" ,
                   1136:                        default => "C2",
                   1137:                        select2 => { 
                   1138:                            C1 => "Choice C1",
                   1139:                            C2 => "Choice C2",
                   1140:                            C3 => "Choice C3"
1.609     raeburn  1141:                            },
                   1142:                        order => ['C2','C1','C3'],
1.112     bowersj2 1143:                    },
                   1144:                A3 => { text =>"Choice A3" ,
                   1145:                        default => "D6",
                   1146:                        select2 => { 
                   1147:                            D1 => "Choice D1",
                   1148:                            D2 => "Choice D2",
                   1149:                            D3 => "Choice D3",
                   1150:                            D4 => "Choice D4",
                   1151:                            D5 => "Choice D5",
                   1152:                            D6 => "Choice D6",
                   1153:                            D7 => "Choice D7"
1.609     raeburn  1154:                            },
                   1155:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1156:                    }
                   1157:                );
1.36      matthew  1158: 
                   1159: =cut
                   1160: 
                   1161: sub linked_select_forms {
                   1162:     my ($formname,
                   1163:         $middletext,
                   1164:         $firstdefault,
                   1165:         $firstselectname,
                   1166:         $secondselectname, 
1.609     raeburn  1167:         $hashref,
                   1168:         $menuorder,
1.1115    raeburn  1169:         $onchangefirst,
1.1245    raeburn  1170:         $onchangesecond,
                   1171:         $suffix
1.36      matthew  1172:         ) = @_;
                   1173:     my $second = "document.$formname.$secondselectname";
                   1174:     my $first = "document.$formname.$firstselectname";
                   1175:     # output the javascript to do the changing
                   1176:     my $result = '';
1.776     bisitz   1177:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1178:     $result.="// <![CDATA[\n";
1.1245    raeburn  1179:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1180:     $" = '","';
                   1181:     my $debug = '';
                   1182:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1183:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1184:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1185:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1186:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1187:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1188:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1189:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1190:         }
1.36      matthew  1191:         $result.="\"@s2values\");\n";
1.1245    raeburn  1192:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1193:         my @s2texts;
                   1194:         foreach my $value (@s2values) {
1.1263    raeburn  1195:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1196:         }
                   1197:         $result.="\"@s2texts\");\n";
                   1198:     }
                   1199:     $"=' ';
                   1200:     $result.= <<"END";
                   1201: 
1.1245    raeburn  1202: function select1${suffix}_changed() {
1.36      matthew  1203:     // Determine new choice
1.1245    raeburn  1204:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1205:     // update select2
1.1245    raeburn  1206:     var values     = select2data${suffix}[newvalue].values;
                   1207:     var texts      = select2data${suffix}[newvalue].texts;
                   1208:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1209:     var i;
                   1210:     // out with the old
1.1245    raeburn  1211:     $second.options.length = 0;
                   1212:     // in with the new
1.36      matthew  1213:     for (i=0;i<values.length; i++) {
                   1214:         $second.options[i] = new Option(values[i]);
1.143     matthew  1215:         $second.options[i].value = values[i];
1.36      matthew  1216:         $second.options[i].text = texts[i];
                   1217:         if (values[i] == select2def) {
                   1218:             $second.options[i].selected = true;
                   1219:         }
                   1220:     }
                   1221: }
1.824     bisitz   1222: // ]]>
1.36      matthew  1223: </script>
                   1224: END
                   1225:     # output the initial values for the selection lists
1.1245    raeburn  1226:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1227:     my @order = sort(keys(%{$hashref}));
                   1228:     if (ref($menuorder) eq 'ARRAY') {
                   1229:         @order = @{$menuorder};
                   1230:     }
                   1231:     foreach my $value (@order) {
1.36      matthew  1232:         $result.="    <option value=\"$value\" ";
1.253     albertel 1233:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1234:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1235:     }
                   1236:     $result .= "</select>\n";
1.1400    raeburn  1237:     my %select2;
                   1238:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
                   1239:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
                   1240:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1241:         }
                   1242:     }
1.36      matthew  1243:     $result .= $middletext;
1.1115    raeburn  1244:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1245:     if ($onchangesecond) {
                   1246:         $result .= ' onchange="'.$onchangesecond.'"';
                   1247:     }
                   1248:     $result .= ">\n";
1.36      matthew  1249:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1250:     
                   1251:     my @secondorder = sort(keys(%select2));
                   1252:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1253:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1254:     }
                   1255:     foreach my $value (@secondorder) {
1.36      matthew  1256:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1257:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1258:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1259:     }
                   1260:     $result .= "</select>\n";
                   1261:     #    return $debug;
                   1262:     return $result;
                   1263: }   #  end of sub linked_select_forms {
                   1264: 
1.45      matthew  1265: =pod
1.44      bowersj2 1266: 
1.1381    raeburn  1267: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1268: 
1.112     bowersj2 1269: Returns a string corresponding to an HTML link to the given help
                   1270: $topic, where $topic corresponds to the name of a .tex file in
                   1271: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1272: spaces. 
                   1273: 
                   1274: $text will optionally be linked to the same topic, allowing you to
                   1275: link text in addition to the graphic. If you do not want to link
                   1276: text, but wish to specify one of the later parameters, pass an
                   1277: empty string. 
                   1278: 
                   1279: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1280: the link will not open a new window. If false, the link will open
                   1281: a new window using Javascript. (Default is false.) 
                   1282: 
                   1283: $width and $height are optional numerical parameters that will
                   1284: override the width and height of the popped up window, which may
1.973     raeburn  1285: be useful for certain help topics with big pictures included.
                   1286: 
                   1287: $imgid is the id of the img tag used for the help icon. This may be
                   1288: used in a javascript call to switch the image src.  See 
                   1289: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1290: 
1.1381    raeburn  1291: $links_target will optionally be set to a target (_top, _parent or _self).
                   1292: 
1.44      bowersj2 1293: =cut
                   1294: 
                   1295: sub help_open_topic {
1.1381    raeburn  1296:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1297:     $text = "" if (not defined $text);
1.44      bowersj2 1298:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1299:     $width = 500 if (not defined $width);
1.44      bowersj2 1300:     $height = 400 if (not defined $height);
                   1301:     my $filename = $topic;
                   1302:     $filename =~ s/ /_/g;
                   1303: 
1.48      bowersj2 1304:     my $template = "";
                   1305:     my $link;
1.572     banghart 1306:     
1.159     www      1307:     $topic=~s/\W/\_/g;
1.44      bowersj2 1308: 
1.572     banghart 1309:     if (!$stayOnPage) {
1.1033    www      1310: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1311:     } elsif ($stayOnPage eq 'popup') {
                   1312:         $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 1313:     } else {
1.48      bowersj2 1314: 	$link = "/adm/help/${filename}.hlp";
                   1315:     }
                   1316: 
                   1317:     # Add the text
1.1314    raeburn  1318:     my $target = ' target="_top"';
1.1381    raeburn  1319:     if ($links_target) {
                   1320:         $target = ' target="'.$links_target.'"';
                   1321:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1322:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1323:         $target = '';
1.1378    raeburn  1324:     }
1.1380    raeburn  1325:     if ($text ne "") {
1.763     bisitz   1326: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1327:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1328:                   .$text.'</a>';
1.48      bowersj2 1329:     }
                   1330: 
1.763     bisitz   1331:     # (Always) Add the graphic
1.179     matthew  1332:     my $title = &mt('Online Help');
1.667     raeburn  1333:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1334:     if ($imgid ne '') {
                   1335:         $imgid = ' id="'.$imgid.'"';
                   1336:     }
1.1314    raeburn  1337:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1338:               .'<img src="'.$helpicon.'" border="0"'
                   1339:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1340:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1341:               .' /></a>';
                   1342:     if ($text ne "") {	
                   1343:         $template.='</span>';
                   1344:     }
1.44      bowersj2 1345:     return $template;
                   1346: 
1.106     bowersj2 1347: }
                   1348: 
                   1349: # This is a quicky function for Latex cheatsheet editing, since it 
                   1350: # appears in at least four places
                   1351: sub helpLatexCheatsheet {
1.1037    www      1352:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1353:     my $out;
1.106     bowersj2 1354:     my $addOther = '';
1.732     raeburn  1355:     if ($topic) {
1.1037    www      1356: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1357:     }
                   1358:     $out = '<span>' # Start cheatsheet
                   1359: 	  .$addOther
                   1360:           .'<span>'
1.1037    www      1361: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1362: 	  .'</span> <span>'
1.1037    www      1363: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1364: 	  .'</span>';
1.732     raeburn  1365:     unless ($not_author) {
1.1186    kruse    1366:         $out .= '<span>'
                   1367:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1368:                .'</span> <span>'
                   1369:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1370: 	       .'</span>';
1.732     raeburn  1371:     }
1.763     bisitz   1372:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1373:     return $out;
1.172     www      1374: }
                   1375: 
1.430     albertel 1376: sub general_help {
                   1377:     my $helptopic='Student_Intro';
                   1378:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1379: 	$helptopic='Authoring_Intro';
1.907     raeburn  1380:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1381: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1382:     } elsif ($env{'request.role'}=~/^dc/) {
                   1383:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1384:     }
                   1385:     return $helptopic;
                   1386: }
                   1387: 
                   1388: sub update_help_link {
                   1389:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1390:     my $origurl = $ENV{'REQUEST_URI'};
                   1391:     $origurl=~s|^/~|/priv/|;
                   1392:     my $timestamp = time;
                   1393:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1394:         $$datum = &escape($$datum);
                   1395:     }
                   1396: 
                   1397:     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";
                   1398:     my $output .= <<"ENDOUTPUT";
                   1399: <script type="text/javascript">
1.824     bisitz   1400: // <![CDATA[
1.430     albertel 1401: banner_link = '$banner_link';
1.824     bisitz   1402: // ]]>
1.430     albertel 1403: </script>
                   1404: ENDOUTPUT
                   1405:     return $output;
                   1406: }
                   1407: 
                   1408: # now just updates the help link and generates a blue icon
1.193     raeburn  1409: sub help_open_menu {
1.1381    raeburn  1410:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1411: 	= @_;    
1.949     droeschl 1412:     $stayOnPage = 1;
1.430     albertel 1413:     my $output;
                   1414:     if ($component_help) {
                   1415: 	if (!$text) {
                   1416: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1417: 				       $width,$height,'',$links_target);
1.430     albertel 1418: 	} else {
                   1419: 	    my $help_text;
                   1420: 	    $help_text=&unescape($topic);
                   1421: 	    $output='<table><tr><td>'.
                   1422: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1423: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1424: 	}
                   1425:     }
                   1426:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1427:     return $output.$banner_link;
                   1428: }
                   1429: 
                   1430: sub top_nav_help {
1.1369    raeburn  1431:     my ($text,$linkattr) = @_;
1.436     albertel 1432:     $text = &mt($text);
1.949     droeschl 1433:     my $stay_on_page = 1;
                   1434: 
1.1168    raeburn  1435:     my ($link,$banner_link);
                   1436:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1437:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1438: 	                         : "javascript:helpMenu('open')";
                   1439:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1440:     }
1.201     raeburn  1441:     my $title = &mt('Get help');
1.1168    raeburn  1442:     if ($link) {
                   1443:         return <<"END";
1.436     albertel 1444: $banner_link
1.1369    raeburn  1445: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1446: END
1.1168    raeburn  1447:     } else {
                   1448:         return '&nbsp;'.$text.'&nbsp;';
                   1449:     }
1.436     albertel 1450: }
                   1451: 
                   1452: sub help_menu_js {
1.1154    raeburn  1453:     my ($httphost) = @_;
1.949     droeschl 1454:     my $stayOnPage = 1;
1.436     albertel 1455:     my $width = 620;
                   1456:     my $height = 600;
1.430     albertel 1457:     my $helptopic=&general_help();
1.1154    raeburn  1458:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1459:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1460:     my $start_page =
                   1461:         &Apache::loncommon::start_page('Help Menu', undef,
                   1462: 				       {'frameset'    => 1,
                   1463: 					'js_ready'    => 1,
1.1154    raeburn  1464:                                         'use_absolute' => $httphost,
1.331     albertel 1465: 					'add_entries' => {
1.1168    raeburn  1466: 					    'border' => '0', 
1.579     raeburn  1467: 					    'rows'   => "110,*",},});
1.331     albertel 1468:     my $end_page =
                   1469:         &Apache::loncommon::end_page({'frameset' => 1,
                   1470: 				      'js_ready' => 1,});
                   1471: 
1.436     albertel 1472:     my $template .= <<"ENDTEMPLATE";
                   1473: <script type="text/javascript">
1.877     bisitz   1474: // <![CDATA[
1.253     albertel 1475: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1476: var banner_link = '';
1.243     raeburn  1477: function helpMenu(target) {
                   1478:     var caller = this;
                   1479:     if (target == 'open') {
                   1480:         var newWindow = null;
                   1481:         try {
1.262     albertel 1482:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1483:         }
                   1484:         catch(error) {
                   1485:             writeHelp(caller);
                   1486:             return;
                   1487:         }
                   1488:         if (newWindow) {
                   1489:             caller = newWindow;
                   1490:         }
1.193     raeburn  1491:     }
1.243     raeburn  1492:     writeHelp(caller);
                   1493:     return;
                   1494: }
                   1495: function writeHelp(caller) {
1.1168    raeburn  1496:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1497:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1498:     caller.document.close();
                   1499:     caller.focus();
1.193     raeburn  1500: }
1.877     bisitz   1501: // END LON-CAPA Internal -->
1.253     albertel 1502: // ]]>
1.436     albertel 1503: </script>
1.193     raeburn  1504: ENDTEMPLATE
                   1505:     return $template;
                   1506: }
                   1507: 
1.172     www      1508: sub help_open_bug {
                   1509:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1510:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1511:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1512:     $text = "" if (not defined $text);
                   1513: 	$stayOnPage=1;
1.184     albertel 1514:     $width = 600 if (not defined $width);
                   1515:     $height = 600 if (not defined $height);
1.172     www      1516: 
                   1517:     $topic=~s/\W+/\+/g;
                   1518:     my $link='';
                   1519:     my $template='';
1.379     albertel 1520:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1521: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1522:     if (!$stayOnPage)
                   1523:     {
                   1524: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1525:     }
                   1526:     else
                   1527:     {
                   1528: 	$link = $url;
                   1529:     }
1.1314    raeburn  1530: 
1.1382    raeburn  1531:     my $target = '_top';
                   1532:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1533:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1534:         $target = '_blank';
1.1378    raeburn  1535:     }
1.1382    raeburn  1536: 
1.172     www      1537:     # Add the text
                   1538:     if ($text ne "")
                   1539:     {
                   1540: 	$template .= 
                   1541:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1542:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1543:     }
                   1544: 
                   1545:     # Add the graphic
1.179     matthew  1546:     my $title = &mt('Report a Bug');
1.215     albertel 1547:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1548:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1549:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1550: ENDTEMPLATE
                   1551:     if ($text ne '') { $template.='</td></tr></table>' };
                   1552:     return $template;
                   1553: 
                   1554: }
                   1555: 
                   1556: sub help_open_faq {
                   1557:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1558:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1559:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1560:     $text = "" if (not defined $text);
                   1561: 	$stayOnPage=1;
                   1562:     $width = 350 if (not defined $width);
                   1563:     $height = 400 if (not defined $height);
                   1564: 
                   1565:     $topic=~s/\W+/\+/g;
                   1566:     my $link='';
                   1567:     my $template='';
                   1568:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1569:     if (!$stayOnPage)
                   1570:     {
                   1571: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1572:     }
                   1573:     else
                   1574:     {
                   1575: 	$link = $url;
                   1576:     }
                   1577: 
                   1578:     # Add the text
                   1579:     if ($text ne "")
                   1580:     {
                   1581: 	$template .= 
1.173     www      1582:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1583:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1584:     }
                   1585: 
                   1586:     # Add the graphic
1.179     matthew  1587:     my $title = &mt('View the FAQ');
1.215     albertel 1588:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1589:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1590:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1591: ENDTEMPLATE
                   1592:     if ($text ne '') { $template.='</td></tr></table>' };
                   1593:     return $template;
                   1594: 
1.44      bowersj2 1595: }
1.37      matthew  1596: 
1.180     matthew  1597: ###############################################################
                   1598: ###############################################################
                   1599: 
1.45      matthew  1600: =pod
                   1601: 
1.648     raeburn  1602: =item * &change_content_javascript():
1.256     matthew  1603: 
                   1604: This and the next function allow you to create small sections of an
                   1605: otherwise static HTML page that you can update on the fly with
                   1606: Javascript, even in Netscape 4.
                   1607: 
                   1608: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1609: must be written to the HTML page once. It will prove the Javascript
                   1610: function "change(name, content)". Calling the change function with the
                   1611: name of the section 
                   1612: you want to update, matching the name passed to C<changable_area>, and
                   1613: the new content you want to put in there, will put the content into
                   1614: that area.
                   1615: 
                   1616: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1617: to contain room for the original contents. You need to "make space"
                   1618: for whatever changes you wish to make, and be B<sure> to check your
                   1619: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1620: it's adequate for updating a one-line status display, but little more.
                   1621: This script will set the space to 100% width, so you only need to
                   1622: worry about height in Netscape 4.
                   1623: 
                   1624: Modern browsers are much less limiting, and if you can commit to the
                   1625: user not using Netscape 4, this feature may be used freely with
                   1626: pretty much any HTML.
                   1627: 
                   1628: =cut
                   1629: 
                   1630: sub change_content_javascript {
                   1631:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1632:     if ($env{'browser.type'} eq 'netscape' &&
                   1633: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1634: 	return (<<NETSCAPE4);
                   1635: 	function change(name, content) {
                   1636: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1637: 	    doc.open();
                   1638: 	    doc.write(content);
                   1639: 	    doc.close();
                   1640: 	}
                   1641: NETSCAPE4
                   1642:     } else {
                   1643: 	# Otherwise, we need to use semi-standards-compliant code
                   1644: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1645: 	# is really scary, and every useful browser supports it
                   1646: 	return (<<DOMBASED);
                   1647: 	function change(name, content) {
                   1648: 	    element = document.getElementById(name);
                   1649: 	    element.innerHTML = content;
                   1650: 	}
                   1651: DOMBASED
                   1652:     }
                   1653: }
                   1654: 
                   1655: =pod
                   1656: 
1.648     raeburn  1657: =item * &changable_area($name,$origContent):
1.256     matthew  1658: 
                   1659: This provides a "changable area" that can be modified on the fly via
                   1660: the Javascript code provided in C<change_content_javascript>. $name is
                   1661: the name you will use to reference the area later; do not repeat the
                   1662: same name on a given HTML page more then once. $origContent is what
                   1663: the area will originally contain, which can be left blank.
                   1664: 
                   1665: =cut
                   1666: 
                   1667: sub changable_area {
                   1668:     my ($name, $origContent) = @_;
                   1669: 
1.258     albertel 1670:     if ($env{'browser.type'} eq 'netscape' &&
                   1671: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1672: 	# If this is netscape 4, we need to use the Layer tag
                   1673: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1674:     } else {
                   1675: 	return "<span id='$name'>$origContent</span>";
                   1676:     }
                   1677: }
                   1678: 
                   1679: =pod
                   1680: 
1.648     raeburn  1681: =item * &viewport_geometry_js 
1.590     raeburn  1682: 
                   1683: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1684: 
                   1685: =cut
                   1686: 
                   1687: 
                   1688: sub viewport_geometry_js { 
                   1689:     return <<"GEOMETRY";
                   1690: var Geometry = {};
                   1691: function init_geometry() {
                   1692:     if (Geometry.init) { return };
                   1693:     Geometry.init=1;
                   1694:     if (window.innerHeight) {
                   1695:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1696:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1697:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1698:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1699:     }
                   1700:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1701:         Geometry.getViewportHeight =
                   1702:             function() { return document.documentElement.clientHeight; };
                   1703:         Geometry.getViewportWidth =
                   1704:             function() { return document.documentElement.clientWidth; };
                   1705: 
                   1706:         Geometry.getHorizontalScroll =
                   1707:             function() { return document.documentElement.scrollLeft; };
                   1708:         Geometry.getVerticalScroll =
                   1709:             function() { return document.documentElement.scrollTop; };
                   1710:     }
                   1711:     else if (document.body.clientHeight) {
                   1712:         Geometry.getViewportHeight =
                   1713:             function() { return document.body.clientHeight; };
                   1714:         Geometry.getViewportWidth =
                   1715:             function() { return document.body.clientWidth; };
                   1716:         Geometry.getHorizontalScroll =
                   1717:             function() { return document.body.scrollLeft; };
                   1718:         Geometry.getVerticalScroll =
                   1719:             function() { return document.body.scrollTop; };
                   1720:     }
                   1721: }
                   1722: 
                   1723: GEOMETRY
                   1724: }
                   1725: 
                   1726: =pod
                   1727: 
1.648     raeburn  1728: =item * &viewport_size_js()
1.590     raeburn  1729: 
                   1730: 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. 
                   1731: 
                   1732: =cut
                   1733: 
                   1734: sub viewport_size_js {
                   1735:     my $geometry = &viewport_geometry_js();
                   1736:     return <<"DIMS";
                   1737: 
                   1738: $geometry
                   1739: 
                   1740: function getViewportDims(width,height) {
                   1741:     init_geometry();
                   1742:     width.value = Geometry.getViewportWidth();
                   1743:     height.value = Geometry.getViewportHeight();
                   1744:     return;
                   1745: }
                   1746: 
                   1747: DIMS
                   1748: }
                   1749: 
                   1750: =pod
                   1751: 
1.648     raeburn  1752: =item * &resize_textarea_js()
1.565     albertel 1753: 
                   1754: emits the needed javascript to resize a textarea to be as big as possible
                   1755: 
                   1756: creates a function resize_textrea that takes two IDs first should be
                   1757: the id of the element to resize, second should be the id of a div that
                   1758: surrounds everything that comes after the textarea, this routine needs
                   1759: to be attached to the <body> for the onload and onresize events.
                   1760: 
1.648     raeburn  1761: =back
1.565     albertel 1762: 
                   1763: =cut
                   1764: 
                   1765: sub resize_textarea_js {
1.590     raeburn  1766:     my $geometry = &viewport_geometry_js();
1.565     albertel 1767:     return <<"RESIZE";
                   1768:     <script type="text/javascript">
1.824     bisitz   1769: // <![CDATA[
1.590     raeburn  1770: $geometry
1.565     albertel 1771: 
1.588     albertel 1772: function getX(element) {
                   1773:     var x = 0;
                   1774:     while (element) {
                   1775: 	x += element.offsetLeft;
                   1776: 	element = element.offsetParent;
                   1777:     }
                   1778:     return x;
                   1779: }
                   1780: function getY(element) {
                   1781:     var y = 0;
                   1782:     while (element) {
                   1783: 	y += element.offsetTop;
                   1784: 	element = element.offsetParent;
                   1785:     }
                   1786:     return y;
                   1787: }
                   1788: 
                   1789: 
1.565     albertel 1790: function resize_textarea(textarea_id,bottom_id) {
                   1791:     init_geometry();
                   1792:     var textarea        = document.getElementById(textarea_id);
                   1793:     //alert(textarea);
                   1794: 
1.588     albertel 1795:     var textarea_top    = getY(textarea);
1.565     albertel 1796:     var textarea_height = textarea.offsetHeight;
                   1797:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1798:     var bottom_top      = getY(bottom);
1.565     albertel 1799:     var bottom_height   = bottom.offsetHeight;
                   1800:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1801:     var fudge           = 23;
1.565     albertel 1802:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1803:     if (new_height < 300) {
                   1804: 	new_height = 300;
                   1805:     }
                   1806:     textarea.style.height=new_height+'px';
                   1807: }
1.824     bisitz   1808: // ]]>
1.565     albertel 1809: </script>
                   1810: RESIZE
                   1811: 
                   1812: }
                   1813: 
1.1205    golterma 1814: sub colorfuleditor_js {
1.1248    raeburn  1815:     my $browse_or_search;
                   1816:     my $respath;
                   1817:     my ($cnum,$cdom) = &crsauthor_url();
                   1818:     if ($cnum) {
                   1819:         $respath = "/res/$cdom/$cnum/";
                   1820:         my %js_lt = &Apache::lonlocal::texthash(
                   1821:             sunm => 'Sub-directory name',
                   1822:             save => 'Save page to make this permanent',
                   1823:         );
                   1824:         &js_escape(\%js_lt);
1.1400    raeburn  1825:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1826:         $browse_or_search = <<"END";
                   1827: 
1.1400    raeburn  1828:     $showfile_js
                   1829: 
1.1248    raeburn  1830:     function toggleChooser(form,element,titleid,only,search) {
                   1831:         var disp = 'none';
                   1832:         if (document.getElementById('chooser_'+element)) {
                   1833:             var curr = document.getElementById('chooser_'+element).style.display;
                   1834:             if (curr == 'none') {
                   1835:                 disp='inline';
                   1836:                 if (form.elements['chooser_'+element].length) {
                   1837:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1838:                         form.elements['chooser_'+element][i].checked = false;
                   1839:                     }
                   1840:                 }
                   1841:                 toggleResImport(form,element);
                   1842:             }
                   1843:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1844:             var dirsel = '';
                   1845:             var filesel = '';
                   1846:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1847:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1848:                 if (currcrsres == 'none') {
                   1849:                     dirsel = 'coursepath_'+element;
                   1850:                     var filesel = 'coursefile_'+element;
                   1851:                     var include;
                   1852:                     if (document.getElementById('crsres_include_'+element)) {
                   1853:                         include = document.getElementById('crsres_include_'+element).value;
                   1854:                     }
1.1402    raeburn  1855:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1856:                 }
                   1857:             }
                   1858:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1859:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1860:                 if (currcrsupload == 'none') {
                   1861:                     dirsel = 'crsauthorpath_'+element;
                   1862:                     filesel = '';
1.1402    raeburn  1863:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1864:                 }
                   1865:             }
1.1248    raeburn  1866:         }
                   1867:     }
                   1868: 
1.1400    raeburn  1869:     function toggleCrsFile(form,element) {
1.1248    raeburn  1870:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1871:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1872:             if (curr == 'none') {
1.1400    raeburn  1873:                 if (document.getElementById('coursepath_'+element)) {
                   1874:                     var numdirs;
                   1875:                     if (document.getElementById('coursepath_'+element).length) {
                   1876:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1877:                     }
1.1402    raeburn  1878:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1879:                         (document.getElementById('nocrsres_'+element))) {
                   1880:                         if (numdirs) {
                   1881:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1882:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1883:                         } else {
                   1884:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1885:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1886:                         }
                   1887:                     }
1.1248    raeburn  1888:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1889:                     if (numdirs > 1) {
1.1400    raeburn  1890:                         var selelem = form.elements['coursefile_'+element];
                   1891:                         var i, len = selelem.options.length -1;
                   1892:                         if (len >=0) {
                   1893:                             for (i = len; i >= 0; i--) {
                   1894:                                 selelem.remove(i);
                   1895:                             }
                   1896:                             selelem.options[0] = new Option('','');
                   1897:                         }
1.1248    raeburn  1898:                     }
                   1899:                 }
1.1400    raeburn  1900:             }
1.1248    raeburn  1901:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1902:         }
                   1903:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1904:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1905:             if (document.getElementById('uploadcrsres_'+element)) {
                   1906:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1907:             }
                   1908:         }
                   1909:         return;
                   1910:     }
                   1911: 
1.1400    raeburn  1912:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1913:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1914:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1915:         }
                   1916:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1917:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1918:             if (curr == 'none') {
1.1400    raeburn  1919:                 form.elements['newsubdir_'+element][0].checked = true;
                   1920:                 toggleNewsubdir(form,element);
                   1921:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1922:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1923:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1924:                 }
                   1925:             }
                   1926:         }
                   1927:         return;
                   1928:     }
                   1929: 
                   1930:     function toggleResImport(form,element) {
                   1931:         var choices = new Array('crsres','upload');
                   1932:         for (var i=0; i<choices.length; i++) {
                   1933:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1934:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1935:             }
                   1936:         }
                   1937:     }
                   1938: 
                   1939:     function toggleNewsubdir(form,element) {
                   1940:         var newsub = form.elements['newsubdir_'+element];
                   1941:         if (newsub) {
                   1942:             if (newsub.length) {
                   1943:                 for (var j=0; j<newsub.length; j++) {
                   1944:                     if (newsub[j].checked) {
                   1945:                         if (document.getElementById('newsubdirname_'+element)) {
                   1946:                             if (newsub[j].value == '1') {
                   1947:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1948:                                 if (document.getElementById('newsubdir_'+element)) {
                   1949:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1950:                                 }
                   1951:                             } else {
                   1952:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1953:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1954:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1955:                             }
                   1956:                         }
                   1957:                         break; 
                   1958:                     }
                   1959:                 }
                   1960:             }
                   1961:         }
                   1962:     }
                   1963: 
                   1964:     function updateCrsFile(form,element) {
                   1965:         var directory = form.elements['coursepath_'+element];
                   1966:         var filename = form.elements['coursefile_'+element];
                   1967:         var path = directory.options[directory.selectedIndex].value;
                   1968:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1969:         if (file != '') {
                   1970:             form.elements[element].value = '$respath';
                   1971:             if (path == '/') {
                   1972:                 form.elements[element].value += file;
                   1973:             } else {
                   1974:                 form.elements[element].value += path+'/'+file;
                   1975:             }
                   1976:             unClean();
                   1977:             if (document.getElementById('previewimg_'+element)) {
                   1978:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1979:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1980:             }
                   1981:             if (document.getElementById('showimg_'+element)) {
                   1982:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1983:             }
1.1248    raeburn  1984:         }
                   1985:         toggleChooser(form,element);
                   1986:         return;
                   1987:     }
                   1988: 
                   1989:     function uploadDone(suffix,name) {
                   1990:         if (name) {
                   1991: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1992:             unClean();
                   1993:             toggleChooser(document.forms["lonhomework"],suffix);
                   1994:         }
                   1995:     }
                   1996: 
                   1997: \$(document).ready(function(){
                   1998: 
                   1999:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2000:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2001:             var buttonId = this.id;
                   2002:             var suffix = buttonId.toString();
                   2003:             suffix = suffix.replace(/^crsupload_/,'');
                   2004:             event.preventDefault();
                   2005:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2006:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2007:             \$(this.form).submit();
                   2008:             document.lonhomework.target = '';
                   2009:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2010:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2011:             }
                   2012:             return false;
                   2013:         }
                   2014:     });
                   2015: });
                   2016: END
                   2017:     }
1.1205    golterma 2018:     return <<"COLORFULEDIT"
                   2019: <script type="text/javascript">
                   2020: // <![CDATA[>
                   2021:     function fold_box(curDepth, lastresource){
                   2022: 
                   2023:     // we need a list because there can be several blocks you need to fold in one tag
                   2024:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2025:     // but there is only one folding button per tag
                   2026:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2027: 
                   2028:         if(block.item(0).style.display == 'none'){
                   2029: 
                   2030:             foldbutton.value = '@{[&mt("Hide")]}';
                   2031:             for (i = 0; i < block.length; i++){
                   2032:                 block.item(i).style.display = '';
                   2033:             }
                   2034:         }else{
                   2035: 
                   2036:             foldbutton.value = '@{[&mt("Show")]}';
                   2037:             for (i = 0; i < block.length; i++){
                   2038:                 // block.item(i).style.visibility = 'collapse';
                   2039:                 block.item(i).style.display = 'none';
                   2040:             }
                   2041:         };
                   2042:         saveState(lastresource);
                   2043:     }
                   2044: 
                   2045:     function saveState (lastresource) {
                   2046: 
                   2047:         var tag_list = getTagList();
                   2048:         if(tag_list != null){
                   2049:             var timestamp = new Date().getTime();
                   2050:             var key = lastresource;
                   2051: 
                   2052:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2053:             // starting with timestamp
                   2054:             var value = timestamp+';';
                   2055: 
                   2056:             // building the list of key-value pairs
                   2057:             for(var i = 0; i < tag_list.length; i++){
                   2058:                 value += tag_list[i]+',';
                   2059:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2060:             }
                   2061: 
                   2062:             // only iterate whole storage if nothing to override
                   2063:             if(localStorage.getItem(key) == null){        
                   2064: 
                   2065:                 // prevent storage from growing large
                   2066:                 if(localStorage.length > 50){
                   2067:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2068:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2069:                     var oldest_key;
                   2070:                     
                   2071:                     for(var i = 1; i < localStorage.length; i++){
                   2072:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2073:                             oldest_key = localStorage.key(i);
                   2074:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2075:                         }
                   2076:                     }
                   2077:                     localStorage.removeItem(oldest_key);
                   2078:                 }
                   2079:             }
                   2080:             localStorage.setItem(key,value);
                   2081:         }
                   2082:     }
                   2083: 
                   2084:     // restore folding status of blocks (on page load)
                   2085:     function restoreState (lastresource) {
                   2086:         if(localStorage.getItem(lastresource) != null){
                   2087:             var key = lastresource;
                   2088:             var value = localStorage.getItem(key);
                   2089:             var regex_delTimestamp = /^\d+;/;
                   2090: 
                   2091:             value.replace(regex_delTimestamp, '');
                   2092: 
                   2093:             var valueArr = value.split(';');
                   2094:             var pairs;
                   2095:             var elements;
                   2096:             for (var i = 0; i < valueArr.length; i++){
                   2097:                 pairs = valueArr[i].split(',');
                   2098:                 elements = document.getElementsByName(pairs[0]);
                   2099: 
                   2100:                 for (var j = 0; j < elements.length; j++){  
                   2101:                     elements[j].style.display = pairs[1];
                   2102:                     if (pairs[1] == "none"){
                   2103:                         var regex_id = /([_\\d]+)\$/;
                   2104:                         regex_id.exec(pairs[0]);
                   2105:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2106:                     }
                   2107:                 }
                   2108:             }
                   2109:         }
                   2110:     }
                   2111: 
                   2112:     function getTagList () {
                   2113:         
                   2114:         var stringToSearch = document.lonhomework.innerHTML;
                   2115: 
                   2116:         var ret = new Array();
                   2117:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2118:         var tag_list = stringToSearch.match(regex_findBlock);
                   2119: 
                   2120:         if(tag_list != null){
                   2121:             for(var i = 0; i < tag_list.length; i++){            
                   2122:                 ret.push(tag_list[i].replace(/"/, ''));
                   2123:             }
                   2124:         }
                   2125:         return ret;
                   2126:     }
                   2127: 
                   2128:     function saveScrollPosition (resource) {
                   2129:         var tag_list = getTagList();
                   2130: 
                   2131:         // we dont always want to jump to the first block
                   2132:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2133:         if(\$(window).scrollTop() > 170){
                   2134:             if(tag_list != null){
                   2135:                 var result;
                   2136:                 for(var i = 0; i < tag_list.length; i++){
                   2137:                     if(isElementInViewport(tag_list[i])){
                   2138:                         result += tag_list[i]+';';
                   2139:                     }
                   2140:                 }
                   2141:                 sessionStorage.setItem('anchor_'+resource, result);
                   2142:             }
                   2143:         } else {
                   2144:             // we dont need to save zero, just delete the item to leave everything tidy
                   2145:             sessionStorage.removeItem('anchor_'+resource);
                   2146:         }
                   2147:     }
                   2148: 
                   2149:     function restoreScrollPosition(resource){
                   2150: 
                   2151:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2152:         if(elem != null){
                   2153:             var tag_list = elem.split(';');
                   2154:             var elem_list;
                   2155: 
                   2156:             for(var i = 0; i < tag_list.length; i++){
                   2157:                 elem_list = document.getElementsByName(tag_list[i]);
                   2158:                 
                   2159:                 if(elem_list.length > 0){
                   2160:                     elem = elem_list[0];
                   2161:                     break;
                   2162:                 }
                   2163:             }
                   2164:             elem.scrollIntoView();
                   2165:         }
                   2166:     }
                   2167: 
                   2168:     function isElementInViewport(el) {
                   2169: 
                   2170:         // change to last element instead of first
                   2171:         var elem = document.getElementsByName(el);
                   2172:         var rect = elem[0].getBoundingClientRect();
                   2173: 
                   2174:         return (
                   2175:             rect.top >= 0 &&
                   2176:             rect.left >= 0 &&
                   2177:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2178:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2179:         );
                   2180:     }
                   2181:     
                   2182:     function autosize(depth){
                   2183:         var cmInst = window['cm'+depth];
                   2184:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2185: 
                   2186:         // is fixed size, switching to dynamic
                   2187:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2188:             cmInst.setSize("","auto");
                   2189:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2190:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2191: 
                   2192:         // is dynamic size, switching to fixed
                   2193:         } else {
                   2194:             cmInst.setSize("","300px");
                   2195:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2196:             sessionStorage.removeItem("autosized_"+depth);
                   2197:         }
                   2198:     }
                   2199: 
1.1248    raeburn  2200: $browse_or_search
1.1205    golterma 2201: 
                   2202: // ]]>
                   2203: </script>
                   2204: COLORFULEDIT
                   2205: }
                   2206: 
                   2207: sub xmleditor_js {
                   2208:     return <<XMLEDIT
                   2209: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2210: <script type="text/javascript">
                   2211: // <![CDATA[>
                   2212: 
                   2213:     function saveScrollPosition (resource) {
                   2214: 
                   2215:         var scrollPos = \$(window).scrollTop();
                   2216:         sessionStorage.setItem(resource,scrollPos);
                   2217:     }
                   2218: 
                   2219:     function restoreScrollPosition(resource){
                   2220: 
                   2221:         var scrollPos = sessionStorage.getItem(resource);
                   2222:         \$(window).scrollTop(scrollPos);
                   2223:     }
                   2224: 
                   2225:     // unless internet explorer
                   2226:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2227: 
                   2228:         \$(document).ready(function() {
                   2229:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2230:         });
                   2231:     }
                   2232: 
                   2233:     // inserts text at cursor position into codemirror (xml editor only)
                   2234:     function insertText(text){
                   2235:         cm.focus();
                   2236:         var curPos = cm.getCursor();
                   2237:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2238:     }
                   2239: // ]]>
                   2240: </script>
                   2241: XMLEDIT
                   2242: }
                   2243: 
                   2244: sub insert_folding_button {
                   2245:     my $curDepth = $Apache::lonxml::curdepth;
                   2246:     my $lastresource = $env{'request.ambiguous'};
                   2247: 
                   2248:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2249:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2250: }
                   2251: 
1.1248    raeburn  2252: sub crsauthor_url {
                   2253:     my ($url) = @_;
                   2254:     if ($url eq '') {
                   2255:         $url = $ENV{'REQUEST_URI'};
                   2256:     }
                   2257:     my ($cnum,$cdom);
                   2258:     if ($env{'request.course.id'}) {
                   2259:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2260:         if ($audom ne '' && $auname ne '') {
                   2261:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2262:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2263:                 $cnum = $auname;
                   2264:                 $cdom = $audom;
                   2265:             }
                   2266:         }
                   2267:     }
                   2268:     return ($cnum,$cdom);
                   2269: }
                   2270: 
                   2271: sub import_crsauthor_form {
1.1400    raeburn  2272:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2273:     return (0) unless ($env{'request.course.id'});
                   2274:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2275:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2276:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2277:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2278:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2279:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2280: 
1.1248    raeburn  2281:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2282:         $is_home = 1;
                   2283:     }
1.1400    raeburn  2284:     $toppath = "/priv/$cdom/$cnum";
                   2285:     my $nonemptydir = 1;
                   2286:     my $js_only;
                   2287:     if ($only) {
                   2288:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2289:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2290:     }
                   2291:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2292:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2293:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2294:     my %lt = &Apache::lonlocal::texthash (
                   2295:         fnam => 'Filename',
                   2296:         dire => 'Directory',
1.1400    raeburn  2297:         se   => 'Select',
1.1248    raeburn  2298:     );
1.1402    raeburn  2299:     $output = $lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2300:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2301:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2302:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2303:     if ($files{'/'}) {
                   2304:         $output .= '<option value="/">/</option>'."\n";
                   2305:     }
1.1400    raeburn  2306:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2307:         next if ($key eq '/');
1.1400    raeburn  2308:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2309:     }
                   2310:     $output .= '</select><br />'."\n".
1.1402    raeburn  2311:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2312:                '<option value="" selected="selected"></option>'."\n".
1.1402    raeburn  2313:                '</select>'."\n".
                   2314:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2315:     return ($numdirs,$output);
                   2316: }
                   2317: 
                   2318: sub show_crsfiles_js {
                   2319:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2320:     my $se = &js_escape(&mt('Select'));
                   2321:     my $exclude;
                   2322:     if (ref($excluderef) eq 'HASH') {
                   2323:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2324:     }
                   2325:     my $js = <<"END";
                   2326: 
                   2327: 
1.1402    raeburn  2328:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2329:         var relpath = '';
                   2330:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2331:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2332:             if (currdir == '') {
                   2333:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2334:                     selelem = form.elements[filesel];
                   2335:                     var j, numfiles = selelem.options.length -1;
                   2336:                     if (numfiles >=0) {
                   2337:                         for (j = numfiles; j >= 0; j--) {
                   2338:                             selelem.remove(j);
                   2339:                         }
                   2340:                     }
                   2341:                     if (selelem.options.length == 0) {
                   2342:                         selelem.options[selelem.options.length] = new Option('','');
                   2343:                         selelem.selectedIndex = 0;
1.1248    raeburn  2344:                     }
                   2345:                 }
1.1400    raeburn  2346:                 return;
                   2347:             } else {
                   2348:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2349:             }
                   2350:         }
1.1400    raeburn  2351:         var http = new XMLHttpRequest();
                   2352:         var url = "/adm/courseauthor";
                   2353:         var crsrole = "$env{'request.role'}";
                   2354:         var exclude = '';
                   2355:         if (exc) {
                   2356:             exclude = '$exclude';
                   2357:         }
1.1402    raeburn  2358:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2359:         http.open("POST", url, true);
                   2360:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2361:         http.onreadystatechange = function() {
                   2362:             if (http.readyState == 4 && http.status == 200) {
                   2363:                 var data = JSON.parse(http.responseText);
                   2364:                 var selelem;
                   2365:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2366:                     if (Array.isArray(data.dirs)) {
                   2367:                         selelem = form.elements[dirsel];
                   2368:                         var i, numdirs = selelem.options.length -1;
                   2369:                         if (numdirs >=0) {
                   2370:                             for (i = numdirs; i >= 0; i--) {
                   2371:                                 selelem.remove(i);
                   2372:                             }
                   2373:                         }
                   2374:                         var len = data.dirs.length;
                   2375:                         if (len) {
1.1402    raeburn  2376:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2377:                             var j;
                   2378:                             for (j = 0; j < len; j++) {
                   2379:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2380:                             }
                   2381:                             selelem.selectedIndex = 0;
                   2382:                         }
                   2383:                         if (!setfile) {
                   2384:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2385:                                 selelem = form.elements[filesel];
                   2386:                                 var j, numfiles = selelem.options.length -1;
                   2387:                                 if (numfiles >=0) {
                   2388:                                     for (j = numfiles; j >= 0; j--) {
                   2389:                                         selelem.remove(j);
                   2390:                                     }
                   2391:                                 }
                   2392:                                 if (selelem.options.length == 0) {
                   2393:                                     selelem.options[selelem.options.length] = new Option('','');
                   2394:                                     selelem.selectedIndex = 0;
                   2395:                                 }
                   2396:                             }
                   2397:                         }
                   2398:                     }
                   2399:                 }
                   2400:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2401:                     selelem = form.elements[filesel];
                   2402:                     var i, numfiles = selelem.options.length -1;
                   2403:                     if (numfiles >=0) {
                   2404:                         for (i = numfiles; i >= 0; i--) {
                   2405:                             selelem.remove(i);
                   2406:                         }
                   2407:                     }
                   2408:                     var x;
                   2409:                     for (x in data.files) {
                   2410:                         if (Array.isArray(data.files[x])) {
                   2411:                             if (data.files[x].length > 1) {
                   2412:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2413:                             }
                   2414:                             var len = data.files[x].length;
                   2415:                             if (len) {
                   2416:                                 var k;
                   2417:                                 for (k = 0; k < len; k++) {
                   2418:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2419:                                 }
                   2420:                                 selelem.selectedIndex = 0;
                   2421:                             }
                   2422:                         }
                   2423:                     }
                   2424:                     if (selelem.options.length == 0) {
                   2425:                         selelem.options[selelem.options.length] = new Option('','');
                   2426:                         selelem.selectedIndex = 0;
                   2427:                     }
1.1248    raeburn  2428:                 }
                   2429:             }
                   2430:         }
1.1400    raeburn  2431:         http.send(params);
1.1248    raeburn  2432:     }
1.1400    raeburn  2433: END
1.1248    raeburn  2434: }
                   2435: 
1.565     albertel 2436: =pod
                   2437: 
1.256     matthew  2438: =head1 Excel and CSV file utility routines
                   2439: 
                   2440: =cut
                   2441: 
                   2442: ###############################################################
                   2443: ###############################################################
                   2444: 
                   2445: =pod
                   2446: 
1.1162    raeburn  2447: =over 4
                   2448: 
1.648     raeburn  2449: =item * &csv_translate($text) 
1.37      matthew  2450: 
1.185     www      2451: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2452: format.
                   2453: 
                   2454: =cut
                   2455: 
1.180     matthew  2456: ###############################################################
                   2457: ###############################################################
1.37      matthew  2458: sub csv_translate {
                   2459:     my $text = shift;
                   2460:     $text =~ s/\"/\"\"/g;
1.209     albertel 2461:     $text =~ s/\n/ /g;
1.37      matthew  2462:     return $text;
                   2463: }
1.180     matthew  2464: 
                   2465: ###############################################################
                   2466: ###############################################################
                   2467: 
                   2468: =pod
                   2469: 
1.648     raeburn  2470: =item * &define_excel_formats()
1.180     matthew  2471: 
                   2472: Define some commonly used Excel cell formats.
                   2473: 
                   2474: Currently supported formats:
                   2475: 
                   2476: =over 4
                   2477: 
                   2478: =item header
                   2479: 
                   2480: =item bold
                   2481: 
                   2482: =item h1
                   2483: 
                   2484: =item h2
                   2485: 
                   2486: =item h3
                   2487: 
1.256     matthew  2488: =item h4
                   2489: 
                   2490: =item i
                   2491: 
1.180     matthew  2492: =item date
                   2493: 
                   2494: =back
                   2495: 
                   2496: Inputs: $workbook
                   2497: 
                   2498: Returns: $format, a hash reference.
                   2499: 
1.1057    foxr     2500: 
1.180     matthew  2501: =cut
                   2502: 
                   2503: ###############################################################
                   2504: ###############################################################
                   2505: sub define_excel_formats {
                   2506:     my ($workbook) = @_;
                   2507:     my $format;
                   2508:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2509:                                                 bottom    => 1,
                   2510:                                                 align     => 'center');
                   2511:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2512:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2513:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2514:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2515:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2516:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2517:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2518:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2519:     return $format;
                   2520: }
                   2521: 
                   2522: ###############################################################
                   2523: ###############################################################
1.113     bowersj2 2524: 
                   2525: =pod
                   2526: 
1.648     raeburn  2527: =item * &create_workbook()
1.255     matthew  2528: 
                   2529: Create an Excel worksheet.  If it fails, output message on the
                   2530: request object and return undefs.
                   2531: 
                   2532: Inputs: Apache request object
                   2533: 
                   2534: Returns (undef) on failure, 
                   2535:     Excel worksheet object, scalar with filename, and formats 
                   2536:     from &Apache::loncommon::define_excel_formats on success
                   2537: 
                   2538: =cut
                   2539: 
                   2540: ###############################################################
                   2541: ###############################################################
                   2542: sub create_workbook {
                   2543:     my ($r) = @_;
                   2544:         #
                   2545:     # Create the excel spreadsheet
                   2546:     my $filename = '/prtspool/'.
1.258     albertel 2547:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2548:         time.'_'.rand(1000000000).'.xls';
                   2549:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2550:     if (! defined($workbook)) {
                   2551:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2552:         $r->print(
                   2553:             '<p class="LC_error">'
                   2554:            .&mt('Problems occurred in creating the new Excel file.')
                   2555:            .' '.&mt('This error has been logged.')
                   2556:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2557:            .'</p>'
                   2558:         );
1.255     matthew  2559:         return (undef);
                   2560:     }
                   2561:     #
1.1014    foxr     2562:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2563:     #
                   2564:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2565:     return ($workbook,$filename,$format);
                   2566: }
                   2567: 
                   2568: ###############################################################
                   2569: ###############################################################
                   2570: 
                   2571: =pod
                   2572: 
1.648     raeburn  2573: =item * &create_text_file()
1.113     bowersj2 2574: 
1.542     raeburn  2575: Create a file to write to and eventually make available to the user.
1.256     matthew  2576: If file creation fails, outputs an error message on the request object and 
                   2577: return undefs.
1.113     bowersj2 2578: 
1.256     matthew  2579: Inputs: Apache request object, and file suffix
1.113     bowersj2 2580: 
1.256     matthew  2581: Returns (undef) on failure, 
                   2582:     Filehandle and filename on success.
1.113     bowersj2 2583: 
                   2584: =cut
                   2585: 
1.256     matthew  2586: ###############################################################
                   2587: ###############################################################
                   2588: sub create_text_file {
                   2589:     my ($r,$suffix) = @_;
                   2590:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2591:     my $fh;
                   2592:     my $filename = '/prtspool/'.
1.258     albertel 2593:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2594:         time.'_'.rand(1000000000).'.'.$suffix;
                   2595:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2596:     if (! defined($fh)) {
                   2597:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2598:         $r->print(
                   2599:             '<p class="LC_error">'
                   2600:            .&mt('Problems occurred in creating the output file.')
                   2601:            .' '.&mt('This error has been logged.')
                   2602:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2603:            .'</p>'
                   2604:         );
1.113     bowersj2 2605:     }
1.256     matthew  2606:     return ($fh,$filename)
1.113     bowersj2 2607: }
                   2608: 
                   2609: 
1.256     matthew  2610: =pod 
1.113     bowersj2 2611: 
                   2612: =back
                   2613: 
                   2614: =cut
1.37      matthew  2615: 
                   2616: ###############################################################
1.33      matthew  2617: ##        Home server <option> list generating code          ##
                   2618: ###############################################################
1.35      matthew  2619: 
1.169     www      2620: # ------------------------------------------
                   2621: 
                   2622: sub domain_select {
1.1289    raeburn  2623:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2624:     my @possdoms;
                   2625:     if (ref($incdoms) eq 'ARRAY') {
                   2626:         @possdoms = @{$incdoms};
                   2627:     } else {
                   2628:         @possdoms = &Apache::lonnet::all_domains();
                   2629:     }
                   2630: 
1.169     www      2631:     my %domains=map { 
1.514     albertel 2632: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2633:     } @possdoms;
                   2634: 
                   2635:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2636:         foreach my $dom (@{$excdoms}) {
                   2637:             delete($domains{$dom});
                   2638:         }
                   2639:     }
                   2640: 
1.169     www      2641:     if ($multiple) {
                   2642: 	$domains{''}=&mt('Any domain');
1.550     albertel 2643: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2644: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2645:     } else {
1.550     albertel 2646: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2647: 	return &select_form($name,$value,\%domains);
1.169     www      2648:     }
                   2649: }
                   2650: 
1.282     albertel 2651: #-------------------------------------------
                   2652: 
                   2653: =pod
                   2654: 
1.519     raeburn  2655: =head1 Routines for form select boxes
                   2656: 
                   2657: =over 4
                   2658: 
1.648     raeburn  2659: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2660: 
                   2661: Returns a string containing a <select> element int multiple mode
                   2662: 
                   2663: 
                   2664: Args:
                   2665:   $name - name of the <select> element
1.506     raeburn  2666:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2667:   $size - number of rows long the select element is
1.283     albertel 2668:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2669:           (shown text should already have been &mt())
1.506     raeburn  2670:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2671: 
1.282     albertel 2672: =cut
                   2673: 
                   2674: #-------------------------------------------
1.169     www      2675: sub multiple_select_form {
1.284     albertel 2676:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2677:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2678:     my $output='';
1.191     matthew  2679:     if (! defined($size)) {
                   2680:         $size = 4;
1.283     albertel 2681:         if (scalar(keys(%$hash))<4) {
                   2682:             $size = scalar(keys(%$hash));
1.191     matthew  2683:         }
                   2684:     }
1.734     bisitz   2685:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2686:     my @order;
1.506     raeburn  2687:     if (ref($order) eq 'ARRAY')  {
                   2688:         @order = @{$order};
                   2689:     } else {
                   2690:         @order = sort(keys(%$hash));
1.501     banghart 2691:     }
                   2692:     if (exists($$hash{'select_form_order'})) {
                   2693:         @order = @{$$hash{'select_form_order'}};
                   2694:     }
                   2695:         
1.284     albertel 2696:     foreach my $key (@order) {
1.356     albertel 2697:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2698:         $output.='selected="selected" ' if ($selected{$key});
                   2699:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2700:     }
                   2701:     $output.="</select>\n";
                   2702:     return $output;
                   2703: }
                   2704: 
1.88      www      2705: #-------------------------------------------
                   2706: 
                   2707: =pod
                   2708: 
1.1254    raeburn  2709: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2710: 
                   2711: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2712: allow a user to select options from a ref to a hash containing:
                   2713: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2714: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2715: An optional arg -- $readonly -- if true will cause the select form
                   2716: to be disabled, e.g., for the case where an instructor has a section-
                   2717: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2718: 
1.88      www      2719: See lonrights.pm for an example invocation and use.
                   2720: 
                   2721: =cut
                   2722: 
                   2723: #-------------------------------------------
                   2724: sub select_form {
1.1228    raeburn  2725:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2726:     return unless (ref($hashref) eq 'HASH');
                   2727:     if ($onchange) {
                   2728:         $onchange = ' onchange="'.$onchange.'"';
                   2729:     }
1.1228    raeburn  2730:     my $disabled;
                   2731:     if ($readonly) {
                   2732:         $disabled = ' disabled="disabled"';
                   2733:     }
                   2734:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2735:     my @keys;
1.970     raeburn  2736:     if (exists($hashref->{'select_form_order'})) {
                   2737: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2738:     } else {
1.970     raeburn  2739: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2740:     }
1.356     albertel 2741:     foreach my $key (@keys) {
                   2742:         $selectform.=
                   2743: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2744:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2745:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2746:     }
                   2747:     $selectform.="</select>";
                   2748:     return $selectform;
                   2749: }
                   2750: 
1.475     www      2751: # For display filters
                   2752: 
                   2753: sub display_filter {
1.1074    raeburn  2754:     my ($context) = @_;
1.475     www      2755:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2756:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2757:     my $phraseinput = 'hidden';
                   2758:     my $includeinput = 'hidden';
                   2759:     my ($checked,$includetypestext);
                   2760:     if ($env{'form.displayfilter'} eq 'containing') {
                   2761:         $phraseinput = 'text'; 
                   2762:         if ($context eq 'parmslog') {
                   2763:             $includeinput = 'checkbox';
                   2764:             if ($env{'form.includetypes'}) {
                   2765:                 $checked = ' checked="checked"';
                   2766:             }
                   2767:             $includetypestext = &mt('Include parameter types');
                   2768:         }
                   2769:     } else {
                   2770:         $includetypestext = '&nbsp;';
                   2771:     }
                   2772:     my ($additional,$secondid,$thirdid);
                   2773:     if ($context eq 'parmslog') {
                   2774:         $additional = 
                   2775:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2776:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2777:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2778:             '</label>';
                   2779:         $secondid = 'includetypes';
                   2780:         $thirdid = 'includetypestext';
                   2781:     }
                   2782:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2783:                                                     '$secondid','$thirdid')";
                   2784:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2785: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2786: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2787: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2788:            &mt('Filter: [_1]',
1.477     www      2789: 	   &select_form($env{'form.displayfilter'},
                   2790: 			'displayfilter',
1.970     raeburn  2791: 			{'currentfolder' => 'Current folder/page',
1.477     www      2792: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2793: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2794: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2795:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2796:                          '" />'.$additional;
                   2797: }
                   2798: 
                   2799: sub display_filter_js {
                   2800:     my $includetext = &mt('Include parameter types');
                   2801:     return <<"ENDJS";
                   2802:   
                   2803: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2804:     var firstType = 'hidden';
                   2805:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2806:         firstType = 'text';
                   2807:     }
                   2808:     firstObject = document.getElementById(firstid);
                   2809:     if (typeof(firstObject) == 'object') {
                   2810:         if (firstObject.type != firstType) {
                   2811:             changeInputType(firstObject,firstType);
                   2812:         }
                   2813:     }
                   2814:     if (context == 'parmslog') {
                   2815:         var secondType = 'hidden';
                   2816:         if (firstType == 'text') {
                   2817:             secondType = 'checkbox';
                   2818:         }
                   2819:         secondObject = document.getElementById(secondid);  
                   2820:         if (typeof(secondObject) == 'object') {
                   2821:             if (secondObject.type != secondType) {
                   2822:                 changeInputType(secondObject,secondType);
                   2823:             }
                   2824:         }
                   2825:         var textItem = document.getElementById(thirdid);
                   2826:         var currtext = textItem.innerHTML;
                   2827:         var newtext;
                   2828:         if (firstType == 'text') {
                   2829:             newtext = '$includetext';
                   2830:         } else {
                   2831:             newtext = '&nbsp;';
                   2832:         }
                   2833:         if (currtext != newtext) {
                   2834:             textItem.innerHTML = newtext;
                   2835:         }
                   2836:     }
                   2837:     return;
                   2838: }
                   2839: 
                   2840: function changeInputType(oldObject,newType) {
                   2841:     var newObject = document.createElement('input');
                   2842:     newObject.type = newType;
                   2843:     if (oldObject.size) {
                   2844:         newObject.size = oldObject.size;
                   2845:     }
                   2846:     if (oldObject.value) {
                   2847:         newObject.value = oldObject.value;
                   2848:     }
                   2849:     if (oldObject.name) {
                   2850:         newObject.name = oldObject.name;
                   2851:     }
                   2852:     if (oldObject.id) {
                   2853:         newObject.id = oldObject.id;
                   2854:     }
                   2855:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2856:     return;
                   2857: }
                   2858: 
                   2859: ENDJS
1.475     www      2860: }
                   2861: 
1.167     www      2862: sub gradeleveldescription {
                   2863:     my $gradelevel=shift;
                   2864:     my %gradelevels=(0 => 'Not specified',
                   2865: 		     1 => 'Grade 1',
                   2866: 		     2 => 'Grade 2',
                   2867: 		     3 => 'Grade 3',
                   2868: 		     4 => 'Grade 4',
                   2869: 		     5 => 'Grade 5',
                   2870: 		     6 => 'Grade 6',
                   2871: 		     7 => 'Grade 7',
                   2872: 		     8 => 'Grade 8',
                   2873: 		     9 => 'Grade 9',
                   2874: 		     10 => 'Grade 10',
                   2875: 		     11 => 'Grade 11',
                   2876: 		     12 => 'Grade 12',
                   2877: 		     13 => 'Grade 13',
                   2878: 		     14 => '100 Level',
                   2879: 		     15 => '200 Level',
                   2880: 		     16 => '300 Level',
                   2881: 		     17 => '400 Level',
                   2882: 		     18 => 'Graduate Level');
                   2883:     return &mt($gradelevels{$gradelevel});
                   2884: }
                   2885: 
1.163     www      2886: sub select_level_form {
                   2887:     my ($deflevel,$name)=@_;
                   2888:     unless ($deflevel) { $deflevel=0; }
1.167     www      2889:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2890:     for (my $i=0; $i<=18; $i++) {
                   2891:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2892:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2893:                 ">".&gradeleveldescription($i)."</option>\n";
                   2894:     }
                   2895:     $selectform.="</select>";
                   2896:     return $selectform;
1.163     www      2897: }
1.167     www      2898: 
1.35      matthew  2899: #-------------------------------------------
                   2900: 
1.45      matthew  2901: =pod
                   2902: 
1.1256    raeburn  2903: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2904: 
                   2905: Returns a string containing a <select name='$name' size='1'> form to 
                   2906: allow a user to select the domain to preform an operation in.  
                   2907: See loncreateuser.pm for an example invocation and use.
                   2908: 
1.90      www      2909: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2910: selected");
                   2911: 
1.743     raeburn  2912: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2913: 
1.910     raeburn  2914: 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.
                   2915: 
1.1121    raeburn  2916: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2917: 
                   2918: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2919: 
1.1256    raeburn  2920: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2921: 
1.35      matthew  2922: =cut
                   2923: 
                   2924: #-------------------------------------------
1.34      matthew  2925: sub select_dom_form {
1.1256    raeburn  2926:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2927:     if ($onchange) {
1.874     raeburn  2928:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2929:     }
1.1256    raeburn  2930:     if ($disabled) {
                   2931:         $disabled = ' disabled="disabled"';
                   2932:     }
1.1121    raeburn  2933:     my (@domains,%exclude);
1.910     raeburn  2934:     if (ref($incdoms) eq 'ARRAY') {
                   2935:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2936:     } else {
                   2937:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2938:     }
1.90      www      2939:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2940:     if (ref($excdoms) eq 'ARRAY') {
                   2941:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2942:     }
1.1256    raeburn  2943:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2944:     foreach my $dom (@domains) {
1.1121    raeburn  2945:         next if ($exclude{$dom});
1.356     albertel 2946:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2947:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2948:         if ($showdomdesc) {
                   2949:             if ($dom ne '') {
                   2950:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2951:                 if ($domdesc ne '') {
                   2952:                     $selectdomain .= ' ('.$domdesc.')';
                   2953:                 }
                   2954:             } 
                   2955:         }
                   2956:         $selectdomain .= "</option>\n";
1.34      matthew  2957:     }
                   2958:     $selectdomain.="</select>";
                   2959:     return $selectdomain;
                   2960: }
                   2961: 
1.35      matthew  2962: #-------------------------------------------
                   2963: 
1.45      matthew  2964: =pod
                   2965: 
1.648     raeburn  2966: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2967: 
1.586     raeburn  2968: input: 4 arguments (two required, two optional) - 
                   2969:     $domain - domain of new user
                   2970:     $name - name of form element
                   2971:     $default - Value of 'default' causes a default item to be first 
                   2972:                             option, and selected by default. 
                   2973:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2974:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2975: output: returns 2 items: 
1.586     raeburn  2976: (a) form element which contains either:
                   2977:    (i) <select name="$name">
                   2978:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2979:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2980:        </select>
                   2981:        form item if there are multiple library servers in $domain, or
                   2982:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2983:        if there is only one library server in $domain.
                   2984: 
                   2985: (b) number of library servers found.
                   2986: 
                   2987: See loncreateuser.pm for example of use.
1.35      matthew  2988: 
                   2989: =cut
                   2990: 
                   2991: #-------------------------------------------
1.586     raeburn  2992: sub home_server_form_item {
                   2993:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2994:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2995:     my $result;
                   2996:     my $numlib = keys(%servers);
                   2997:     if ($numlib > 1) {
                   2998:         $result .= '<select name="'.$name.'" />'."\n";
                   2999:         if ($default) {
1.804     bisitz   3000:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3001:                        '</option>'."\n";
                   3002:         }
                   3003:         foreach my $hostid (sort(keys(%servers))) {
                   3004:             $result.= '<option value="'.$hostid.'">'.
                   3005: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3006:         }
                   3007:         $result .= '</select>'."\n";
                   3008:     } elsif ($numlib == 1) {
                   3009:         my $hostid;
                   3010:         foreach my $item (keys(%servers)) {
                   3011:             $hostid = $item;
                   3012:         }
                   3013:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3014:                    $hostid.'" />';
                   3015:                    if (!$hide) {
                   3016:                        $result .= $hostid.' '.$servers{$hostid};
                   3017:                    }
                   3018:                    $result .= "\n";
                   3019:     } elsif ($default) {
                   3020:         $result .= '<input type="hidden" name="'.$name.
                   3021:                    '" value="default" />';
                   3022:                    if (!$hide) {
                   3023:                        $result .= &mt('default');
                   3024:                    }
                   3025:                    $result .= "\n";
1.33      matthew  3026:     }
1.586     raeburn  3027:     return ($result,$numlib);
1.33      matthew  3028: }
1.112     bowersj2 3029: 
                   3030: =pod
                   3031: 
1.534     albertel 3032: =back 
                   3033: 
1.112     bowersj2 3034: =cut
1.87      matthew  3035: 
                   3036: ###############################################################
1.112     bowersj2 3037: ##                  Decoding User Agent                      ##
1.87      matthew  3038: ###############################################################
                   3039: 
                   3040: =pod
                   3041: 
1.112     bowersj2 3042: =head1 Decoding the User Agent
                   3043: 
                   3044: =over 4
                   3045: 
                   3046: =item * &decode_user_agent()
1.87      matthew  3047: 
                   3048: Inputs: $r
                   3049: 
                   3050: Outputs:
                   3051: 
                   3052: =over 4
                   3053: 
1.112     bowersj2 3054: =item * $httpbrowser
1.87      matthew  3055: 
1.112     bowersj2 3056: =item * $clientbrowser
1.87      matthew  3057: 
1.112     bowersj2 3058: =item * $clientversion
1.87      matthew  3059: 
1.112     bowersj2 3060: =item * $clientmathml
1.87      matthew  3061: 
1.112     bowersj2 3062: =item * $clientunicode
1.87      matthew  3063: 
1.112     bowersj2 3064: =item * $clientos
1.87      matthew  3065: 
1.1137    raeburn  3066: =item * $clientmobile
                   3067: 
1.1141    raeburn  3068: =item * $clientinfo
                   3069: 
1.1194    raeburn  3070: =item * $clientosversion
                   3071: 
1.87      matthew  3072: =back
                   3073: 
1.157     matthew  3074: =back 
                   3075: 
1.87      matthew  3076: =cut
                   3077: 
                   3078: ###############################################################
                   3079: ###############################################################
                   3080: sub decode_user_agent {
1.247     albertel 3081:     my ($r)=@_;
1.87      matthew  3082:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3083:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3084:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3085:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3086:     my $clientbrowser='unknown';
                   3087:     my $clientversion='0';
                   3088:     my $clientmathml='';
                   3089:     my $clientunicode='0';
1.1137    raeburn  3090:     my $clientmobile=0;
1.1194    raeburn  3091:     my $clientosversion='';
1.87      matthew  3092:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3093:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3094: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3095: 	    $clientbrowser=$bname;
                   3096:             $httpbrowser=~/$vreg/i;
                   3097: 	    $clientversion=$1;
                   3098:             $clientmathml=($clientversion>=$minv);
                   3099:             $clientunicode=($clientversion>=$univ);
                   3100: 	}
                   3101:     }
                   3102:     my $clientos='unknown';
1.1141    raeburn  3103:     my $clientinfo;
1.87      matthew  3104:     if (($httpbrowser=~/linux/i) ||
                   3105:         ($httpbrowser=~/unix/i) ||
                   3106:         ($httpbrowser=~/ux/i) ||
                   3107:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3108:     if (($httpbrowser=~/vax/i) ||
                   3109:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3110:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3111:     if (($httpbrowser=~/mac/i) ||
                   3112:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3113:     if ($httpbrowser=~/win/i) {
                   3114:         $clientos='win';
                   3115:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3116:             $clientosversion = $1;
                   3117:         }
                   3118:     }
1.87      matthew  3119:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3120:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3121:         $clientmobile=lc($1);
                   3122:     }
1.1141    raeburn  3123:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3124:         $clientinfo = 'firefox-'.$1;
                   3125:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3126:         $clientinfo = 'chromeframe-'.$1;
                   3127:     }
1.87      matthew  3128:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3129:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3130:             $clientosversion);
1.87      matthew  3131: }
                   3132: 
1.32      matthew  3133: ###############################################################
                   3134: ##    Authentication changing form generation subroutines    ##
                   3135: ###############################################################
                   3136: ##
                   3137: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3138: ## hash, and have reasonable default values.
                   3139: ##
                   3140: ##    formname = the name given in the <form> tag.
1.35      matthew  3141: #-------------------------------------------
                   3142: 
1.45      matthew  3143: =pod
                   3144: 
1.112     bowersj2 3145: =head1 Authentication Routines
                   3146: 
                   3147: =over 4
                   3148: 
1.648     raeburn  3149: =item * &authform_xxxxxx()
1.35      matthew  3150: 
                   3151: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3152: handle some of the conveniences required for authentication forms.  
                   3153: This is not an optimal method, but it works.  
                   3154: 
                   3155: =over 4
                   3156: 
1.112     bowersj2 3157: =item * authform_header
1.35      matthew  3158: 
1.112     bowersj2 3159: =item * authform_authorwarning
1.35      matthew  3160: 
1.112     bowersj2 3161: =item * authform_nochange
1.35      matthew  3162: 
1.112     bowersj2 3163: =item * authform_kerberos
1.35      matthew  3164: 
1.112     bowersj2 3165: =item * authform_internal
1.35      matthew  3166: 
1.112     bowersj2 3167: =item * authform_filesystem
1.35      matthew  3168: 
1.1310    raeburn  3169: =item * authform_lti
                   3170: 
1.35      matthew  3171: =back
                   3172: 
1.648     raeburn  3173: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3174: 
1.35      matthew  3175: =cut
                   3176: 
                   3177: #-------------------------------------------
1.32      matthew  3178: sub authform_header{  
                   3179:     my %in = (
                   3180:         formname => 'cu',
1.80      albertel 3181:         kerb_def_dom => '',
1.32      matthew  3182:         @_,
                   3183:     );
                   3184:     $in{'formname'} = 'document.' . $in{'formname'};
                   3185:     my $result='';
1.80      albertel 3186: 
                   3187: #---------------------------------------------- Code for upper case translation
                   3188:     my $Javascript_toUpperCase;
                   3189:     unless ($in{kerb_def_dom}) {
                   3190:         $Javascript_toUpperCase =<<"END";
                   3191:         switch (choice) {
                   3192:            case 'krb': currentform.elements[choicearg].value =
                   3193:                currentform.elements[choicearg].value.toUpperCase();
                   3194:                break;
                   3195:            default:
                   3196:         }
                   3197: END
                   3198:     } else {
                   3199:         $Javascript_toUpperCase = "";
                   3200:     }
                   3201: 
1.165     raeburn  3202:     my $radioval = "'nochange'";
1.591     raeburn  3203:     if (defined($in{'curr_authtype'})) {
                   3204:         if ($in{'curr_authtype'} ne '') {
                   3205:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3206:         }
1.174     matthew  3207:     }
1.165     raeburn  3208:     my $argfield = 'null';
1.591     raeburn  3209:     if (defined($in{'mode'})) {
1.165     raeburn  3210:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3211:             if (defined($in{'curr_autharg'})) {
                   3212:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3213:                     $argfield = "'$in{'curr_autharg'}'";
                   3214:                 }
                   3215:             }
                   3216:         }
                   3217:     }
                   3218: 
1.32      matthew  3219:     $result.=<<"END";
                   3220: var current = new Object();
1.165     raeburn  3221: current.radiovalue = $radioval;
                   3222: current.argfield = $argfield;
1.32      matthew  3223: 
                   3224: function changed_radio(choice,currentform) {
                   3225:     var choicearg = choice + 'arg';
                   3226:     // If a radio button in changed, we need to change the argfield
                   3227:     if (current.radiovalue != choice) {
                   3228:         current.radiovalue = choice;
                   3229:         if (current.argfield != null) {
                   3230:             currentform.elements[current.argfield].value = '';
                   3231:         }
                   3232:         if (choice == 'nochange') {
                   3233:             current.argfield = null;
                   3234:         } else {
                   3235:             current.argfield = choicearg;
                   3236:             switch(choice) {
                   3237:                 case 'krb': 
                   3238:                     currentform.elements[current.argfield].value = 
                   3239:                         "$in{'kerb_def_dom'}";
                   3240:                 break;
                   3241:               default:
                   3242:                 break;
                   3243:             }
                   3244:         }
                   3245:     }
                   3246:     return;
                   3247: }
1.22      www      3248: 
1.32      matthew  3249: function changed_text(choice,currentform) {
                   3250:     var choicearg = choice + 'arg';
                   3251:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3252:         $Javascript_toUpperCase
1.32      matthew  3253:         // clear old field
                   3254:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3255:             currentform.elements[current.argfield].value = '';
                   3256:         }
                   3257:         current.argfield = choicearg;
                   3258:     }
                   3259:     set_auth_radio_buttons(choice,currentform);
                   3260:     return;
1.20      www      3261: }
1.32      matthew  3262: 
                   3263: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3264:     var numauthchoices = currentform.login.length;
                   3265:     if (typeof numauthchoices  == "undefined") {
                   3266:         return;
                   3267:     } 
1.32      matthew  3268:     var i=0;
1.986     raeburn  3269:     while (i < numauthchoices) {
1.32      matthew  3270:         if (currentform.login[i].value == newvalue) { break; }
                   3271:         i++;
                   3272:     }
1.986     raeburn  3273:     if (i == numauthchoices) {
1.32      matthew  3274:         return;
                   3275:     }
                   3276:     current.radiovalue = newvalue;
                   3277:     currentform.login[i].checked = true;
                   3278:     return;
                   3279: }
                   3280: END
                   3281:     return $result;
                   3282: }
                   3283: 
1.1106    raeburn  3284: sub authform_authorwarning {
1.32      matthew  3285:     my $result='';
1.144     matthew  3286:     $result='<i>'.
                   3287:         &mt('As a general rule, only authors or co-authors should be '.
                   3288:             'filesystem authenticated '.
                   3289:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3290:     return $result;
                   3291: }
                   3292: 
1.1106    raeburn  3293: sub authform_nochange {
1.32      matthew  3294:     my %in = (
                   3295:               formname => 'document.cu',
                   3296:               kerb_def_dom => 'MSU.EDU',
                   3297:               @_,
                   3298:           );
1.1106    raeburn  3299:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3300:     my $result;
1.1104    raeburn  3301:     if (!$authnum) {
1.1105    raeburn  3302:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3303:     } else {
                   3304:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3305:                   '<input type="radio" name="login" value="nochange" '.
                   3306:                   'checked="checked" onclick="'.
1.281     albertel 3307:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3308: 	    '</label>';
1.586     raeburn  3309:     }
1.32      matthew  3310:     return $result;
                   3311: }
                   3312: 
1.591     raeburn  3313: sub authform_kerberos {
1.32      matthew  3314:     my %in = (
                   3315:               formname => 'document.cu',
                   3316:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3317:               kerb_def_auth => 'krb4',
1.32      matthew  3318:               @_,
                   3319:               );
1.586     raeburn  3320:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3321:         $autharg,$jscall,$disabled);
1.1106    raeburn  3322:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3323:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3324:        $check5 = ' checked="checked"';
1.80      albertel 3325:     } else {
1.772     bisitz   3326:        $check4 = ' checked="checked"';
1.80      albertel 3327:     }
1.1259    raeburn  3328:     if ($in{'readonly'}) {
                   3329:         $disabled = ' disabled="disabled"';
                   3330:     }
1.165     raeburn  3331:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3332:     if (defined($in{'curr_authtype'})) {
                   3333:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3334:             $krbcheck = ' checked="checked"';
1.623     raeburn  3335:             if (defined($in{'mode'})) {
                   3336:                 if ($in{'mode'} eq 'modifyuser') {
                   3337:                     $krbcheck = '';
                   3338:                 }
                   3339:             }
1.591     raeburn  3340:             if (defined($in{'curr_kerb_ver'})) {
                   3341:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3342:                     $check5 = ' checked="checked"';
1.591     raeburn  3343:                     $check4 = '';
                   3344:                 } else {
1.772     bisitz   3345:                     $check4 = ' checked="checked"';
1.591     raeburn  3346:                     $check5 = '';
                   3347:                 }
1.586     raeburn  3348:             }
1.591     raeburn  3349:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3350:                 $krbarg = $in{'curr_autharg'};
                   3351:             }
1.586     raeburn  3352:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3353:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3354:                     $result = 
                   3355:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3356:         $in{'curr_autharg'},$krbver);
                   3357:                 } else {
                   3358:                     $result =
                   3359:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3360:                 }
                   3361:                 return $result; 
                   3362:             }
                   3363:         }
                   3364:     } else {
                   3365:         if ($authnum == 1) {
1.784     bisitz   3366:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3367:         }
                   3368:     }
1.586     raeburn  3369:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3370:         return;
1.587     raeburn  3371:     } elsif ($authtype eq '') {
1.591     raeburn  3372:         if (defined($in{'mode'})) {
1.587     raeburn  3373:             if ($in{'mode'} eq 'modifycourse') {
                   3374:                 if ($authnum == 1) {
1.1259    raeburn  3375:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3376:                 }
                   3377:             }
                   3378:         }
1.586     raeburn  3379:     }
                   3380:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3381:     if ($authtype eq '') {
                   3382:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3383:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3384:                     $krbcheck.$disabled.' />';
1.586     raeburn  3385:     }
                   3386:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3387:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3388:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3389:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3390:          $in{'curr_authtype'} eq 'krb4')) {
                   3391:         $result .= &mt
1.144     matthew  3392:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3393:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3394:          '<label>'.$authtype,
1.281     albertel 3395:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3396:              'value="'.$krbarg.'" '.
1.1259    raeburn  3397:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3398:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3399:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3400: 	 '</label>');
1.586     raeburn  3401:     } elsif ($can_assign{'krb4'}) {
                   3402:         $result .= &mt
                   3403:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3404:          '[_3] Version 4 [_4]',
                   3405:          '<label>'.$authtype,
                   3406:          '</label><input type="text" size="10" name="krbarg" '.
                   3407:              'value="'.$krbarg.'" '.
1.1259    raeburn  3408:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3409:          '<label><input type="hidden" name="krbver" value="4" />',
                   3410:          '</label>');
                   3411:     } elsif ($can_assign{'krb5'}) {
                   3412:         $result .= &mt
                   3413:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3414:          '[_3] Version 5 [_4]',
                   3415:          '<label>'.$authtype,
                   3416:          '</label><input type="text" size="10" name="krbarg" '.
                   3417:              'value="'.$krbarg.'" '.
1.1259    raeburn  3418:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3419:          '<label><input type="hidden" name="krbver" value="5" />',
                   3420:          '</label>');
                   3421:     }
1.32      matthew  3422:     return $result;
                   3423: }
                   3424: 
1.1106    raeburn  3425: sub authform_internal {
1.586     raeburn  3426:     my %in = (
1.32      matthew  3427:                 formname => 'document.cu',
                   3428:                 kerb_def_dom => 'MSU.EDU',
                   3429:                 @_,
                   3430:                 );
1.1259    raeburn  3431:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3432:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3433:     if ($in{'readonly'}) {
                   3434:         $disabled = ' disabled="disabled"';
                   3435:     }
1.591     raeburn  3436:     if (defined($in{'curr_authtype'})) {
                   3437:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3438:             if ($can_assign{'int'}) {
1.772     bisitz   3439:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3440:                 if (defined($in{'mode'})) {
                   3441:                     if ($in{'mode'} eq 'modifyuser') {
                   3442:                         $intcheck = '';
                   3443:                     }
                   3444:                 }
1.591     raeburn  3445:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3446:                     $intarg = $in{'curr_autharg'};
                   3447:                 }
                   3448:             } else {
                   3449:                 $result = &mt('Currently internally authenticated.');
                   3450:                 return $result;
1.165     raeburn  3451:             }
                   3452:         }
1.586     raeburn  3453:     } else {
                   3454:         if ($authnum == 1) {
1.784     bisitz   3455:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3456:         }
                   3457:     }
                   3458:     if (!$can_assign{'int'}) {
                   3459:         return;
1.587     raeburn  3460:     } elsif ($authtype eq '') {
1.591     raeburn  3461:         if (defined($in{'mode'})) {
1.587     raeburn  3462:             if ($in{'mode'} eq 'modifycourse') {
                   3463:                 if ($authnum == 1) {
1.1259    raeburn  3464:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3465:                 }
                   3466:             }
                   3467:         }
1.165     raeburn  3468:     }
1.586     raeburn  3469:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3470:     if ($authtype eq '') {
                   3471:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3472:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3473:     }
1.605     bisitz   3474:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3475:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3476:     $result = &mt
1.144     matthew  3477:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3478:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3479:     $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  3480:     return $result;
                   3481: }
                   3482: 
1.1104    raeburn  3483: sub authform_local {
1.32      matthew  3484:     my %in = (
                   3485:               formname => 'document.cu',
                   3486:               kerb_def_dom => 'MSU.EDU',
                   3487:               @_,
                   3488:               );
1.1259    raeburn  3489:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3490:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3491:     if ($in{'readonly'}) {
                   3492:         $disabled = ' disabled="disabled"';
                   3493:     } 
1.591     raeburn  3494:     if (defined($in{'curr_authtype'})) {
                   3495:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3496:             if ($can_assign{'loc'}) {
1.772     bisitz   3497:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3498:                 if (defined($in{'mode'})) {
                   3499:                     if ($in{'mode'} eq 'modifyuser') {
                   3500:                         $loccheck = '';
                   3501:                     }
                   3502:                 }
1.591     raeburn  3503:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3504:                     $locarg = $in{'curr_autharg'};
                   3505:                 }
                   3506:             } else {
                   3507:                 $result = &mt('Currently using local (institutional) authentication.');
                   3508:                 return $result;
1.165     raeburn  3509:             }
                   3510:         }
1.586     raeburn  3511:     } else {
                   3512:         if ($authnum == 1) {
1.784     bisitz   3513:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3514:         }
                   3515:     }
                   3516:     if (!$can_assign{'loc'}) {
                   3517:         return;
1.587     raeburn  3518:     } elsif ($authtype eq '') {
1.591     raeburn  3519:         if (defined($in{'mode'})) {
1.587     raeburn  3520:             if ($in{'mode'} eq 'modifycourse') {
                   3521:                 if ($authnum == 1) {
1.1259    raeburn  3522:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3523:                 }
                   3524:             }
                   3525:         }
1.165     raeburn  3526:     }
1.586     raeburn  3527:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3528:     if ($authtype eq '') {
                   3529:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3530:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3531:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3532:     }
                   3533:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3534:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3535:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3536:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3537:     return $result;
                   3538: }
                   3539: 
1.1106    raeburn  3540: sub authform_filesystem {
1.32      matthew  3541:     my %in = (
                   3542:               formname => 'document.cu',
                   3543:               kerb_def_dom => 'MSU.EDU',
                   3544:               @_,
                   3545:               );
1.1259    raeburn  3546:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3547:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3548:     if ($in{'readonly'}) {
                   3549:         $disabled = ' disabled="disabled"';
                   3550:     }
1.591     raeburn  3551:     if (defined($in{'curr_authtype'})) {
                   3552:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3553:             if ($can_assign{'fsys'}) {
1.772     bisitz   3554:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3555:                 if (defined($in{'mode'})) {
                   3556:                     if ($in{'mode'} eq 'modifyuser') {
                   3557:                         $fsyscheck = '';
                   3558:                     }
                   3559:                 }
1.586     raeburn  3560:             } else {
                   3561:                 $result = &mt('Currently Filesystem Authenticated.');
                   3562:                 return $result;
1.1259    raeburn  3563:             }
1.586     raeburn  3564:         }
                   3565:     } else {
                   3566:         if ($authnum == 1) {
1.784     bisitz   3567:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3568:         }
                   3569:     }
                   3570:     if (!$can_assign{'fsys'}) {
                   3571:         return;
1.587     raeburn  3572:     } elsif ($authtype eq '') {
1.591     raeburn  3573:         if (defined($in{'mode'})) {
1.587     raeburn  3574:             if ($in{'mode'} eq 'modifycourse') {
                   3575:                 if ($authnum == 1) {
1.1259    raeburn  3576:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3577:                 }
                   3578:             }
                   3579:         }
1.586     raeburn  3580:     }
                   3581:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3582:     if ($authtype eq '') {
                   3583:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3584:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3585:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3586:     }
1.1310    raeburn  3587:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3588:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3589:     $result = &mt
1.144     matthew  3590:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3591:          '<label>'.$authtype,'</label>'.$autharg);
                   3592:     return $result;
                   3593: }
                   3594: 
                   3595: sub authform_lti {
                   3596:     my %in = (
                   3597:               formname => 'document.cu',
                   3598:               kerb_def_dom => 'MSU.EDU',
                   3599:               @_,
                   3600:               );
                   3601:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3602:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3603:     if ($in{'readonly'}) {
                   3604:         $disabled = ' disabled="disabled"';
                   3605:     }
                   3606:     if (defined($in{'curr_authtype'})) {
                   3607:         if ($in{'curr_authtype'} eq 'lti') {
                   3608:             if ($can_assign{'lti'}) {
                   3609:                 $lticheck = 'checked="checked" ';
                   3610:                 if (defined($in{'mode'})) {
                   3611:                     if ($in{'mode'} eq 'modifyuser') {
                   3612:                         $lticheck = '';
                   3613:                     }
                   3614:                 }
                   3615:             } else {
                   3616:                 $result = &mt('Currently LTI Authenticated.');
                   3617:                 return $result;
                   3618:             }
                   3619:         }
                   3620:     } else {
                   3621:         if ($authnum == 1) {
                   3622:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3623:         }
                   3624:     }
                   3625:     if (!$can_assign{'lti'}) {
                   3626:         return;
                   3627:     } elsif ($authtype eq '') {
                   3628:         if (defined($in{'mode'})) {
                   3629:             if ($in{'mode'} eq 'modifycourse') {
                   3630:                 if ($authnum == 1) {
                   3631:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3632:                 }
                   3633:             }
                   3634:         }
                   3635:     }
                   3636:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3637:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3638:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3639:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3640:                     $jscall.'"'.$disabled.' />';
                   3641:     }
                   3642:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3643:     if ($authtype) {
                   3644:         $result = &mt('[_1] LTI Authenticated',
                   3645:                       '<label>'.$authtype.'</label>'.$autharg);
                   3646:     } else {
                   3647:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3648:                   $autharg;
                   3649:     }
1.32      matthew  3650:     return $result;
                   3651: }
                   3652: 
1.586     raeburn  3653: sub get_assignable_auth {
                   3654:     my ($dom) = @_;
                   3655:     if ($dom eq '') {
                   3656:         $dom = $env{'request.role.domain'};
                   3657:     }
                   3658:     my %can_assign = (
                   3659:                           krb4 => 1,
                   3660:                           krb5 => 1,
                   3661:                           int  => 1,
                   3662:                           loc  => 1,
1.1310    raeburn  3663:                           lti  => 1,
1.586     raeburn  3664:                      );
                   3665:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3666:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3667:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3668:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3669:             my $context;
                   3670:             if ($env{'request.role'} =~ /^au/) {
                   3671:                 $context = 'author';
1.1259    raeburn  3672:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3673:                 $context = 'domain';
                   3674:             } elsif ($env{'request.course.id'}) {
                   3675:                 $context = 'course';
                   3676:             }
                   3677:             if ($context) {
                   3678:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3679:                    %can_assign = %{$authhash->{$context}}; 
                   3680:                 }
                   3681:             }
                   3682:         }
                   3683:     }
                   3684:     my $authnum = 0;
                   3685:     foreach my $key (keys(%can_assign)) {
                   3686:         if ($can_assign{$key}) {
                   3687:             $authnum ++;
                   3688:         }
                   3689:     }
                   3690:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3691:         $authnum --;
                   3692:     }
                   3693:     return ($authnum,%can_assign);
                   3694: }
                   3695: 
1.1331    raeburn  3696: sub check_passwd_rules {
                   3697:     my ($domain,$plainpass) = @_;
                   3698:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3699:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3700:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3701:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3702:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3703:             if ($passwdconf{'min'} > $min) {
                   3704:                 $min = $passwdconf{'min'};
                   3705:             }
1.1331    raeburn  3706:         }
                   3707:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3708:             $max = $passwdconf{'max'};
                   3709:         }
                   3710:         @chars = @{$passwdconf{'chars'}};
                   3711:     }
                   3712:     if (($min) && (length($plainpass) < $min)) {
                   3713:         push(@brokerule,'min');
                   3714:     }
                   3715:     if (($max) && (length($plainpass) > $max)) {
                   3716:         push(@brokerule,'max');
                   3717:     }
                   3718:     if (@chars) {
                   3719:         my %rules;
                   3720:         map { $rules{$_} = 1; } @chars;
                   3721:         if ($rules{'uc'}) {
                   3722:             unless ($plainpass =~ /[A-Z]/) {
                   3723:                 push(@brokerule,'uc');
                   3724:             }
                   3725:         }
                   3726:         if ($rules{'lc'}) {
1.1332    raeburn  3727:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3728:                 push(@brokerule,'lc');
                   3729:             }
                   3730:         }
                   3731:         if ($rules{'num'}) {
                   3732:             unless ($plainpass =~ /\d/) {
                   3733:                 push(@brokerule,'num');
                   3734:             }
                   3735:         }
                   3736:         if ($rules{'spec'}) {
                   3737:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3738:                 push(@brokerule,'spec');
                   3739:             }
                   3740:         }
                   3741:     }
                   3742:     if (@brokerule) {
                   3743:         my %rulenames = &Apache::lonlocal::texthash(
                   3744:             uc   => 'At least one upper case letter',
                   3745:             lc   => 'At least one lower case letter',
                   3746:             num  => 'At least one number',
                   3747:             spec => 'At least one non-alphanumeric',
                   3748:         );
                   3749:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3750:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3751:         $rulenames{'num'} .= ': 0123456789';
                   3752:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3753:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3754:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3755:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3756:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3757:             if (grep(/^$rule$/,@brokerule)) {
                   3758:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3759:             }
                   3760:         }
                   3761:         $warning .= '</ul>';
                   3762:     }
1.1332    raeburn  3763:     if (wantarray) {
                   3764:         return @brokerule;
                   3765:     }
1.1331    raeburn  3766:     return $warning;
                   3767: }
                   3768: 
1.1376    raeburn  3769: sub passwd_validation_js {
1.1377    raeburn  3770:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3771:     my (%passwdconf,$alertmsg);
                   3772:     if ($context eq 'linkprot') {
                   3773:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3774:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3775:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3776:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3777:             }
                   3778:         }
                   3779:         if ($id eq 'add') {
                   3780:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3781:         } elsif ($id =~ /^\d+$/) {
                   3782:             my $pos = $id+1;
                   3783:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3784:         } else {
                   3785:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3786:         }
                   3787:     } else {
                   3788:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3789:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3790:     }
1.1376    raeburn  3791:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3792:     $numrules = 0;
                   3793:     $min = $Apache::lonnet::passwdmin;
                   3794:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3795:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3796:             if ($passwdconf{'min'} > $min) {
                   3797:                 $min = $passwdconf{'min'};
                   3798:             }
                   3799:         }
                   3800:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3801:             $max = $passwdconf{'max'};
                   3802:             $numrules ++;
                   3803:         }
                   3804:         @chars = @{$passwdconf{'chars'}};
                   3805:         if (@chars) {
                   3806:             $numrules ++;
                   3807:         }
                   3808:     }
                   3809:     if ($min > 0) {
                   3810:         $numrules ++;
                   3811:     }
                   3812:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3813:         if ($min) {
                   3814:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3815:         }
                   3816:         if ($max) {
                   3817:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3818:         }
                   3819:         my (@charalerts,@charrules);
                   3820:         if (@chars) {
                   3821:             if (grep(/^uc$/,@chars)) {
                   3822:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3823:                 push(@charrules,'uc');
                   3824:             }
                   3825:             if (grep(/^lc$/,@chars)) {
                   3826:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3827:                 push(@charrules,'lc');
                   3828:             }
                   3829:             if (grep(/^num$/,@chars)) {
                   3830:                 push(@charalerts,&mt('contain at least one number'));
                   3831:                 push(@charrules,'num');
                   3832:             }
                   3833:             if (grep(/^spec$/,@chars)) {
                   3834:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3835:                 push(@charrules,'spec');
                   3836:             }
                   3837:         }
                   3838:         $intargjs = qq|            var rulesmsg = '';\n|.
                   3839:                     qq|            var currpwval = $currpasswdval;\n|;
                   3840:             if ($min) {
                   3841:                 $intargjs .= qq|
                   3842:             if (currpwval.length < $min) {
                   3843:                 rulesmsg += ' - $alert{min}';
                   3844:             }
                   3845: |;
                   3846:             }
                   3847:             if ($max) {
                   3848:                 $intargjs .= qq|
                   3849:             if (currpwval.length > $max) {
                   3850:                 rulesmsg += ' - $alert{max}';
                   3851:             }
                   3852: |;
                   3853:             }
                   3854:             if (@chars > 0) {
                   3855:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3856:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3857:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3858:                              qq|            var charrules = new Array($charrulestr);\n|.
                   3859:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3860:                 my %rules;
                   3861:                 map { $rules{$_} = 1; } @chars;
                   3862:                 if ($rules{'uc'}) {
                   3863:                     $intargjs .= qq|
                   3864:             var ucRegExp = /[A-Z]/;
                   3865:             if (!ucRegExp.test(currpwval)) {
                   3866:                 brokerules.push('uc');
                   3867:             }
                   3868: |;
                   3869:                 }
                   3870:                 if ($rules{'lc'}) {
                   3871:                     $intargjs .= qq|
                   3872:             var lcRegExp = /[a-z]/;
                   3873:             if (!lcRegExp.test(currpwval)) {
                   3874:                 brokerules.push('lc');
                   3875:             }
                   3876: |;
                   3877:                 }
                   3878:                 if ($rules{'num'}) {
                   3879:                      $intargjs .= qq|
                   3880:             var numRegExp = /[0-9]/;
                   3881:             if (!numRegExp.test(currpwval)) {
                   3882:                 brokerules.push('num');
                   3883:             }
                   3884: |;
                   3885:                 }
                   3886:                 if ($rules{'spec'}) {
                   3887:                      $intargjs .= q|
                   3888:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3889:             if (!specRegExp.test(currpwval)) {
                   3890:                 brokerules.push('spec');
                   3891:             }
                   3892: |;
                   3893:                 }
                   3894:                 $intargjs .= qq|
                   3895:             if (brokerules.length > 0) {
                   3896:                 for (var i=0; i<brokerules.length; i++) {
                   3897:                     for (var j=0; j<charrules.length; j++) {
                   3898:                         if (brokerules[i] == charrules[j]) {
                   3899:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3900:                             break;
                   3901:                         }
                   3902:                     }
                   3903:                 }
                   3904:             }
                   3905: |;
                   3906:             }
                   3907:             $intargjs .= qq|
                   3908:             if (rulesmsg != '') {
                   3909:                 rulesmsg = '$alertmsg'+rulesmsg;
                   3910:                 alert(rulesmsg);
                   3911:                 return false;
                   3912:             }
                   3913: |;
                   3914:     }
                   3915:     return ($numrules,$intargjs);
                   3916: }
                   3917: 
1.80      albertel 3918: ###############################################################
                   3919: ##    Get Kerberos Defaults for Domain                 ##
                   3920: ###############################################################
                   3921: ##
                   3922: ## Returns default kerberos version and an associated argument
                   3923: ## as listed in file domain.tab. If not listed, provides
                   3924: ## appropriate default domain and kerberos version.
                   3925: ##
                   3926: #-------------------------------------------
                   3927: 
                   3928: =pod
                   3929: 
1.648     raeburn  3930: =item * &get_kerberos_defaults()
1.80      albertel 3931: 
                   3932: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3933: version and domain. If not found, it defaults to version 4 and the 
                   3934: domain of the server.
1.80      albertel 3935: 
1.648     raeburn  3936: =over 4
                   3937: 
1.80      albertel 3938: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3939: 
1.648     raeburn  3940: =back
                   3941: 
                   3942: =back
                   3943: 
1.80      albertel 3944: =cut
                   3945: 
                   3946: #-------------------------------------------
                   3947: sub get_kerberos_defaults {
                   3948:     my $domain=shift;
1.641     raeburn  3949:     my ($krbdef,$krbdefdom);
                   3950:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3951:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3952:         $krbdef = $domdefaults{'auth_def'};
                   3953:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3954:     } else {
1.80      albertel 3955:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3956:         my $krbdefdom=$1;
                   3957:         $krbdefdom=~tr/a-z/A-Z/;
                   3958:         $krbdef = "krb4";
                   3959:     }
                   3960:     return ($krbdef,$krbdefdom);
                   3961: }
1.112     bowersj2 3962: 
1.32      matthew  3963: 
1.46      matthew  3964: ###############################################################
                   3965: ##                Thesaurus Functions                        ##
                   3966: ###############################################################
1.20      www      3967: 
1.46      matthew  3968: =pod
1.20      www      3969: 
1.112     bowersj2 3970: =head1 Thesaurus Functions
                   3971: 
                   3972: =over 4
                   3973: 
1.648     raeburn  3974: =item * &initialize_keywords()
1.46      matthew  3975: 
                   3976: Initializes the package variable %Keywords if it is empty.  Uses the
                   3977: package variable $thesaurus_db_file.
                   3978: 
                   3979: =cut
                   3980: 
                   3981: ###################################################
                   3982: 
                   3983: sub initialize_keywords {
                   3984:     return 1 if (scalar keys(%Keywords));
                   3985:     # If we are here, %Keywords is empty, so fill it up
                   3986:     #   Make sure the file we need exists...
                   3987:     if (! -e $thesaurus_db_file) {
                   3988:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3989:                                  " failed because it does not exist");
                   3990:         return 0;
                   3991:     }
                   3992:     #   Set up the hash as a database
                   3993:     my %thesaurus_db;
                   3994:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3995:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3996:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3997:                                  $thesaurus_db_file);
                   3998:         return 0;
                   3999:     } 
                   4000:     #  Get the average number of appearances of a word.
                   4001:     my $avecount = $thesaurus_db{'average.count'};
                   4002:     #  Put keywords (those that appear > average) into %Keywords
                   4003:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4004:         my ($count,undef) = split /:/,$data;
                   4005:         $Keywords{$word}++ if ($count > $avecount);
                   4006:     }
                   4007:     untie %thesaurus_db;
                   4008:     # Remove special values from %Keywords.
1.356     albertel 4009:     foreach my $value ('total.count','average.count') {
                   4010:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4011:   }
1.46      matthew  4012:     return 1;
                   4013: }
                   4014: 
                   4015: ###################################################
                   4016: 
                   4017: =pod
                   4018: 
1.648     raeburn  4019: =item * &keyword($word)
1.46      matthew  4020: 
                   4021: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4022: than the average number of times in the thesaurus database.  Calls 
                   4023: &initialize_keywords
                   4024: 
                   4025: =cut
                   4026: 
                   4027: ###################################################
1.20      www      4028: 
                   4029: sub keyword {
1.46      matthew  4030:     return if (!&initialize_keywords());
                   4031:     my $word=lc(shift());
                   4032:     $word=~s/\W//g;
                   4033:     return exists($Keywords{$word});
1.20      www      4034: }
1.46      matthew  4035: 
                   4036: ###############################################################
                   4037: 
                   4038: =pod 
1.20      www      4039: 
1.648     raeburn  4040: =item * &get_related_words()
1.46      matthew  4041: 
1.160     matthew  4042: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4043: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4044: will be returned.  The order of the words returned is determined by the
                   4045: database which holds them.
                   4046: 
                   4047: Uses global $thesaurus_db_file.
                   4048: 
1.1057    foxr     4049: 
1.46      matthew  4050: =cut
                   4051: 
                   4052: ###############################################################
                   4053: sub get_related_words {
                   4054:     my $keyword = shift;
                   4055:     my %thesaurus_db;
                   4056:     if (! -e $thesaurus_db_file) {
                   4057:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4058:                                  "failed because the file does not exist");
                   4059:         return ();
                   4060:     }
                   4061:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4062:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4063:         return ();
                   4064:     } 
                   4065:     my @Words=();
1.429     www      4066:     my $count=0;
1.46      matthew  4067:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4068: 	# The first element is the number of times
                   4069: 	# the word appears.  We do not need it now.
1.429     www      4070: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4071: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4072: 	my $threshold=$mostfrequentcount/10;
                   4073:         foreach my $possibleword (@RelatedWords) {
                   4074:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4075:             if ($wordcount>$threshold) {
                   4076: 		push(@Words,$word);
                   4077:                 $count++;
                   4078:                 if ($count>10) { last; }
                   4079: 	    }
1.20      www      4080:         }
                   4081:     }
1.46      matthew  4082:     untie %thesaurus_db;
                   4083:     return @Words;
1.14      harris41 4084: }
1.1090    foxr     4085: ###############################################################
                   4086: #
                   4087: #  Spell checking
                   4088: #
                   4089: 
                   4090: =pod
                   4091: 
1.1142    raeburn  4092: =back
                   4093: 
1.1090    foxr     4094: =head1 Spell checking
                   4095: 
                   4096: =over 4
                   4097: 
                   4098: =item * &check_spelling($wordlist $language)
                   4099: 
                   4100: Takes a string containing words and feeds it to an external
                   4101: spellcheck program via a pipeline. Returns a string containing
                   4102: them mis-spelled words.
                   4103: 
                   4104: Parameters:
                   4105: 
                   4106: =over 4
                   4107: 
                   4108: =item - $wordlist
                   4109: 
                   4110: String that will be fed into the spellcheck program.
                   4111: 
                   4112: =item - $language
                   4113: 
                   4114: Language string that specifies the language for which the spell
                   4115: check will be performed.
                   4116: 
                   4117: =back
                   4118: 
                   4119: =back
                   4120: 
                   4121: Note: This sub assumes that aspell is installed.
                   4122: 
                   4123: 
                   4124: =cut
                   4125: 
1.46      matthew  4126: 
1.1090    foxr     4127: sub check_spelling {
                   4128:     my ($wordlist, $language) = @_;
1.1091    foxr     4129:     my @misspellings;
                   4130:     
                   4131:     # Generate the speller and set the langauge.
                   4132:     # if explicitly selected:
1.1090    foxr     4133: 
1.1091    foxr     4134:     my $speller = Text::Aspell->new;
1.1090    foxr     4135:     if ($language) {
1.1091    foxr     4136: 	$speller->set_option('lang', $language);
1.1090    foxr     4137:     }
                   4138: 
1.1091    foxr     4139:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4140: 
1.1091    foxr     4141:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4142: 
1.1091    foxr     4143:     foreach my $word (@words) {
                   4144: 	if(! $speller->check($word)) {
                   4145: 	    push(@misspellings, $word);
1.1090    foxr     4146: 	}
                   4147:     }
1.1091    foxr     4148:     return join(' ', @misspellings);
                   4149:     
1.1090    foxr     4150: }
                   4151: 
1.61      www      4152: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4153: =pod
                   4154: 
1.112     bowersj2 4155: =head1 User Name Functions
                   4156: 
                   4157: =over 4
                   4158: 
1.648     raeburn  4159: =item * &plainname($uname,$udom,$first)
1.81      albertel 4160: 
1.112     bowersj2 4161: Takes a users logon name and returns it as a string in
1.226     albertel 4162: "first middle last generation" form 
                   4163: if $first is set to 'lastname' then it returns it as
                   4164: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4165: 
                   4166: =cut
1.61      www      4167: 
1.295     www      4168: 
1.81      albertel 4169: ###############################################################
1.61      www      4170: sub plainname {
1.226     albertel 4171:     my ($uname,$udom,$first)=@_;
1.537     albertel 4172:     return if (!defined($uname) || !defined($udom));
1.295     www      4173:     my %names=&getnames($uname,$udom);
1.226     albertel 4174:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4175: 					  $names{'middlename'},
                   4176: 					  $names{'lastname'},
                   4177: 					  $names{'generation'},$first);
                   4178:     $name=~s/^\s+//;
1.62      www      4179:     $name=~s/\s+$//;
                   4180:     $name=~s/\s+/ /g;
1.353     albertel 4181:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4182:     return $name;
1.61      www      4183: }
1.66      www      4184: 
                   4185: # -------------------------------------------------------------------- Nickname
1.81      albertel 4186: =pod
                   4187: 
1.648     raeburn  4188: =item * &nickname($uname,$udom)
1.81      albertel 4189: 
                   4190: Gets a users name and returns it as a string as
                   4191: 
                   4192: "&quot;nickname&quot;"
1.66      www      4193: 
1.81      albertel 4194: if the user has a nickname or
                   4195: 
                   4196: "first middle last generation"
                   4197: 
                   4198: if the user does not
                   4199: 
                   4200: =cut
1.66      www      4201: 
                   4202: sub nickname {
                   4203:     my ($uname,$udom)=@_;
1.537     albertel 4204:     return if (!defined($uname) || !defined($udom));
1.295     www      4205:     my %names=&getnames($uname,$udom);
1.68      albertel 4206:     my $name=$names{'nickname'};
1.66      www      4207:     if ($name) {
                   4208:        $name='&quot;'.$name.'&quot;'; 
                   4209:     } else {
                   4210:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4211: 	     $names{'lastname'}.' '.$names{'generation'};
                   4212:        $name=~s/\s+$//;
                   4213:        $name=~s/\s+/ /g;
                   4214:     }
                   4215:     return $name;
                   4216: }
                   4217: 
1.295     www      4218: sub getnames {
                   4219:     my ($uname,$udom)=@_;
1.537     albertel 4220:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4221:     if ($udom eq 'public' && $uname eq 'public') {
                   4222: 	return ('lastname' => &mt('Public'));
                   4223:     }
1.295     www      4224:     my $id=$uname.':'.$udom;
                   4225:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4226:     if ($cached) {
                   4227: 	return %{$names};
                   4228:     } else {
                   4229: 	my %loadnames=&Apache::lonnet::get('environment',
                   4230:                     ['firstname','middlename','lastname','generation','nickname'],
                   4231: 					 $udom,$uname);
                   4232: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4233: 	return %loadnames;
                   4234:     }
                   4235: }
1.61      www      4236: 
1.542     raeburn  4237: # -------------------------------------------------------------------- getemails
1.648     raeburn  4238: 
1.542     raeburn  4239: =pod
                   4240: 
1.648     raeburn  4241: =item * &getemails($uname,$udom)
1.542     raeburn  4242: 
                   4243: Gets a user's email information and returns it as a hash with keys:
                   4244: notification, critnotification, permanentemail
                   4245: 
                   4246: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4247: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4248:  
1.648     raeburn  4249: 
1.542     raeburn  4250: =cut
                   4251: 
1.648     raeburn  4252: 
1.466     albertel 4253: sub getemails {
                   4254:     my ($uname,$udom)=@_;
                   4255:     if ($udom eq 'public' && $uname eq 'public') {
                   4256: 	return;
                   4257:     }
1.467     www      4258:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4259:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4260:     my $id=$uname.':'.$udom;
                   4261:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4262:     if ($cached) {
                   4263: 	return %{$names};
                   4264:     } else {
                   4265: 	my %loadnames=&Apache::lonnet::get('environment',
                   4266:                     			   ['notification','critnotification',
                   4267: 					    'permanentemail'],
                   4268: 					   $udom,$uname);
                   4269: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4270: 	return %loadnames;
                   4271:     }
                   4272: }
                   4273: 
1.551     albertel 4274: sub flush_email_cache {
                   4275:     my ($uname,$udom)=@_;
                   4276:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4277:     if (!$uname) { $uname=$env{'user.name'};   }
                   4278:     return if ($udom eq 'public' && $uname eq 'public');
                   4279:     my $id=$uname.':'.$udom;
                   4280:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4281: }
                   4282: 
1.728     raeburn  4283: # -------------------------------------------------------------------- getlangs
                   4284: 
                   4285: =pod
                   4286: 
                   4287: =item * &getlangs($uname,$udom)
                   4288: 
                   4289: Gets a user's language preference and returns it as a hash with key:
                   4290: language.
                   4291: 
                   4292: =cut
                   4293: 
                   4294: 
                   4295: sub getlangs {
                   4296:     my ($uname,$udom) = @_;
                   4297:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4298:     if (!$uname) { $uname=$env{'user.name'};   }
                   4299:     my $id=$uname.':'.$udom;
                   4300:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4301:     if ($cached) {
                   4302:         return %{$langs};
                   4303:     } else {
                   4304:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4305:                                            $udom,$uname);
                   4306:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4307:         return %loadlangs;
                   4308:     }
                   4309: }
                   4310: 
                   4311: sub flush_langs_cache {
                   4312:     my ($uname,$udom)=@_;
                   4313:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4314:     if (!$uname) { $uname=$env{'user.name'};   }
                   4315:     return if ($udom eq 'public' && $uname eq 'public');
                   4316:     my $id=$uname.':'.$udom;
                   4317:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4318: }
                   4319: 
1.61      www      4320: # ------------------------------------------------------------------ Screenname
1.81      albertel 4321: 
                   4322: =pod
                   4323: 
1.648     raeburn  4324: =item * &screenname($uname,$udom)
1.81      albertel 4325: 
                   4326: Gets a users screenname and returns it as a string
                   4327: 
                   4328: =cut
1.61      www      4329: 
                   4330: sub screenname {
                   4331:     my ($uname,$udom)=@_;
1.258     albertel 4332:     if ($uname eq $env{'user.name'} &&
                   4333: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4334:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4335:     return $names{'screenname'};
1.62      www      4336: }
                   4337: 
1.212     albertel 4338: 
1.802     bisitz   4339: # ------------------------------------------------------------- Confirm Wrapper
                   4340: =pod
                   4341: 
1.1142    raeburn  4342: =item * &confirmwrapper($message)
1.802     bisitz   4343: 
                   4344: Wrap messages about completion of operation in box
                   4345: 
                   4346: =cut
                   4347: 
                   4348: sub confirmwrapper {
                   4349:     my ($message)=@_;
                   4350:     if ($message) {
                   4351:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4352:                .$message."\n"
                   4353:                .'</div>'."\n";
                   4354:     } else {
                   4355:         return $message;
                   4356:     }
                   4357: }
                   4358: 
1.62      www      4359: # ------------------------------------------------------------- Message Wrapper
                   4360: 
                   4361: sub messagewrapper {
1.369     www      4362:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4363:     return 
1.441     albertel 4364:         '<a href="/adm/email?compose=individual&amp;'.
                   4365:         'recname='.$username.'&amp;recdom='.$domain.
                   4366: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4367:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4368: }
1.802     bisitz   4369: 
1.74      www      4370: # --------------------------------------------------------------- Notes Wrapper
                   4371: 
                   4372: sub noteswrapper {
                   4373:     my ($link,$un,$do)=@_;
                   4374:     return 
1.896     amueller 4375: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4376: }
1.802     bisitz   4377: 
1.62      www      4378: # ------------------------------------------------------------- Aboutme Wrapper
                   4379: 
                   4380: sub aboutmewrapper {
1.1070    raeburn  4381:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4382:     if (!defined($username)  && !defined($domain)) {
                   4383:         return;
                   4384:     }
1.1096    raeburn  4385:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4386: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4387: }
                   4388: 
                   4389: # ------------------------------------------------------------ Syllabus Wrapper
                   4390: 
                   4391: sub syllabuswrapper {
1.707     bisitz   4392:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4393:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4394: }
1.14      harris41 4395: 
1.1397    raeburn  4396: # -----------------------------------------------------------------------------
                   4397: 
1.1396    raeburn  4398: sub aboutme_on {
                   4399:     my ($uname,$udom)=@_;
                   4400:     unless ($uname) { $uname=$env{'user.name'}; }
                   4401:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4402:     return if ($udom eq 'public' && $uname eq 'public');
                   4403:     my $hashkey=$uname.':'.$udom;
                   4404:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4405:     if ($cached) {
                   4406:         return $aboutme;
                   4407:     }
                   4408:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4409:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4410:     return $aboutme;
                   4411: }
                   4412: 
                   4413: sub devalidate_aboutme_cache {
                   4414:     my ($uname,$udom)=@_;
                   4415:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4416:     if (!$uname) { $uname=$env{'user.name'};   }
                   4417:     return if ($udom eq 'public' && $uname eq 'public');
                   4418:     my $id=$uname.':'.$udom;
                   4419:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4420: }
                   4421: 
1.208     matthew  4422: sub track_student_link {
1.887     raeburn  4423:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4424:     my $link ="/adm/trackstudent?";
1.208     matthew  4425:     my $title = 'View recent activity';
                   4426:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4427:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4428:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4429:         $title .= ' of this student';
1.268     albertel 4430:     } 
1.208     matthew  4431:     if (defined($target) && $target !~ /^\s*$/) {
                   4432:         $target = qq{target="$target"};
                   4433:     } else {
                   4434:         $target = '';
                   4435:     }
1.268     albertel 4436:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4437:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4438:     $title = &mt($title);
                   4439:     $linktext = &mt($linktext);
1.448     albertel 4440:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4441: 	&help_open_topic('View_recent_activity');
1.208     matthew  4442: }
                   4443: 
1.781     raeburn  4444: sub slot_reservations_link {
                   4445:     my ($linktext,$sname,$sdom,$target) = @_;
                   4446:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4447:     my $title = 'View slot reservation history';
                   4448:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4449:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4450:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4451:         $title .= ' of this student';
                   4452:     }
                   4453:     if (defined($target) && $target !~ /^\s*$/) {
                   4454:         $target = qq{target="$target"};
                   4455:     } else {
                   4456:         $target = '';
                   4457:     }
                   4458:     $title = &mt($title);
                   4459:     $linktext = &mt($linktext);
                   4460:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4461: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4462: 
                   4463: }
                   4464: 
1.508     www      4465: # ===================================================== Display a student photo
                   4466: 
                   4467: 
1.509     albertel 4468: sub student_image_tag {
1.508     www      4469:     my ($domain,$user)=@_;
                   4470:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4471:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4472: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4473:     } else {
                   4474: 	return '';
                   4475:     }
                   4476: }
                   4477: 
1.112     bowersj2 4478: =pod
                   4479: 
                   4480: =back
                   4481: 
                   4482: =head1 Access .tab File Data
                   4483: 
                   4484: =over 4
                   4485: 
1.648     raeburn  4486: =item * &languageids() 
1.112     bowersj2 4487: 
                   4488: returns list of all language ids
                   4489: 
                   4490: =cut
                   4491: 
1.14      harris41 4492: sub languageids {
1.16      harris41 4493:     return sort(keys(%language));
1.14      harris41 4494: }
                   4495: 
1.112     bowersj2 4496: =pod
                   4497: 
1.648     raeburn  4498: =item * &languagedescription() 
1.112     bowersj2 4499: 
                   4500: returns description of a specified language id
                   4501: 
                   4502: =cut
                   4503: 
1.14      harris41 4504: sub languagedescription {
1.125     www      4505:     my $code=shift;
                   4506:     return  ($supported_language{$code}?'* ':'').
                   4507:             $language{$code}.
1.126     www      4508: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4509: }
                   4510: 
1.1048    foxr     4511: =pod
                   4512: 
                   4513: =item * &plainlanguagedescription
                   4514: 
                   4515: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4516: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4517: 
                   4518: =cut
                   4519: 
1.145     www      4520: sub plainlanguagedescription {
                   4521:     my $code=shift;
                   4522:     return $language{$code};
                   4523: }
                   4524: 
1.1048    foxr     4525: =pod
                   4526: 
                   4527: =item * &supportedlanguagecode
                   4528: 
                   4529: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4530: code.
                   4531: 
                   4532: =cut
                   4533: 
1.145     www      4534: sub supportedlanguagecode {
                   4535:     my $code=shift;
                   4536:     return $supported_language{$code};
1.97      www      4537: }
                   4538: 
1.112     bowersj2 4539: =pod
                   4540: 
1.1048    foxr     4541: =item * &latexlanguage()
                   4542: 
                   4543: Given a language key code returns the correspondnig language to use
                   4544: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4545: is no supported hyphenation for the language code.
                   4546: 
                   4547: =cut
                   4548: 
                   4549: sub latexlanguage {
                   4550:     my $code = shift;
                   4551:     return $latex_language{$code};
                   4552: }
                   4553: 
                   4554: =pod
                   4555: 
                   4556: =item * &latexhyphenation()
                   4557: 
                   4558: Same as above but what's supplied is the language as it might be stored
                   4559: in the metadata.
                   4560: 
                   4561: =cut
                   4562: 
                   4563: sub latexhyphenation {
                   4564:     my $key = shift;
                   4565:     return $latex_language_bykey{$key};
                   4566: }
                   4567: 
                   4568: =pod
                   4569: 
1.648     raeburn  4570: =item * &copyrightids() 
1.112     bowersj2 4571: 
                   4572: returns list of all copyrights
                   4573: 
                   4574: =cut
                   4575: 
                   4576: sub copyrightids {
                   4577:     return sort(keys(%cprtag));
                   4578: }
                   4579: 
                   4580: =pod
                   4581: 
1.648     raeburn  4582: =item * &copyrightdescription() 
1.112     bowersj2 4583: 
                   4584: returns description of a specified copyright id
                   4585: 
                   4586: =cut
                   4587: 
                   4588: sub copyrightdescription {
1.166     www      4589:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4590: }
1.197     matthew  4591: 
                   4592: =pod
                   4593: 
1.648     raeburn  4594: =item * &source_copyrightids() 
1.192     taceyjo1 4595: 
                   4596: returns list of all source copyrights
                   4597: 
                   4598: =cut
                   4599: 
                   4600: sub source_copyrightids {
                   4601:     return sort(keys(%scprtag));
                   4602: }
                   4603: 
                   4604: =pod
                   4605: 
1.648     raeburn  4606: =item * &source_copyrightdescription() 
1.192     taceyjo1 4607: 
                   4608: returns description of a specified source copyright id
                   4609: 
                   4610: =cut
                   4611: 
                   4612: sub source_copyrightdescription {
                   4613:     return &mt($scprtag{shift(@_)});
                   4614: }
1.112     bowersj2 4615: 
                   4616: =pod
                   4617: 
1.648     raeburn  4618: =item * &filecategories() 
1.112     bowersj2 4619: 
                   4620: returns list of all file categories
                   4621: 
                   4622: =cut
                   4623: 
                   4624: sub filecategories {
                   4625:     return sort(keys(%category_extensions));
                   4626: }
                   4627: 
                   4628: =pod
                   4629: 
1.648     raeburn  4630: =item * &filecategorytypes() 
1.112     bowersj2 4631: 
                   4632: returns list of file types belonging to a given file
                   4633: category
                   4634: 
                   4635: =cut
                   4636: 
                   4637: sub filecategorytypes {
1.356     albertel 4638:     my ($cat) = @_;
1.1248    raeburn  4639:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4640:         return @{$category_extensions{lc($cat)}};
                   4641:     } else {
                   4642:         return ();
                   4643:     }
1.112     bowersj2 4644: }
                   4645: 
                   4646: =pod
                   4647: 
1.648     raeburn  4648: =item * &fileembstyle() 
1.112     bowersj2 4649: 
                   4650: returns embedding style for a specified file type
                   4651: 
                   4652: =cut
                   4653: 
                   4654: sub fileembstyle {
                   4655:     return $fe{lc(shift(@_))};
1.169     www      4656: }
                   4657: 
1.351     www      4658: sub filemimetype {
                   4659:     return $fm{lc(shift(@_))};
                   4660: }
                   4661: 
1.169     www      4662: 
                   4663: sub filecategoryselect {
                   4664:     my ($name,$value)=@_;
1.189     matthew  4665:     return &select_form($value,$name,
1.970     raeburn  4666:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4667: }
                   4668: 
                   4669: =pod
                   4670: 
1.648     raeburn  4671: =item * &filedescription() 
1.112     bowersj2 4672: 
                   4673: returns description for a specified file type
                   4674: 
                   4675: =cut
                   4676: 
                   4677: sub filedescription {
1.188     matthew  4678:     my $file_description = $fd{lc(shift())};
                   4679:     $file_description =~ s:([\[\]]):~$1:g;
                   4680:     return &mt($file_description);
1.112     bowersj2 4681: }
                   4682: 
                   4683: =pod
                   4684: 
1.648     raeburn  4685: =item * &filedescriptionex() 
1.112     bowersj2 4686: 
                   4687: returns description for a specified file type with
                   4688: extra formatting
                   4689: 
                   4690: =cut
                   4691: 
                   4692: sub filedescriptionex {
                   4693:     my $ex=shift;
1.188     matthew  4694:     my $file_description = $fd{lc($ex)};
                   4695:     $file_description =~ s:([\[\]]):~$1:g;
                   4696:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4697: }
                   4698: 
                   4699: # End of .tab access
                   4700: =pod
                   4701: 
                   4702: =back
                   4703: 
                   4704: =cut
                   4705: 
                   4706: # ------------------------------------------------------------------ File Types
                   4707: sub fileextensions {
                   4708:     return sort(keys(%fe));
                   4709: }
                   4710: 
1.97      www      4711: # ----------------------------------------------------------- Display Languages
                   4712: # returns a hash with all desired display languages
                   4713: #
                   4714: 
                   4715: sub display_languages {
                   4716:     my %languages=();
1.695     raeburn  4717:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4718: 	$languages{$lang}=1;
1.97      www      4719:     }
                   4720:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4721:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4722: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4723: 	    $languages{$lang}=1;
1.97      www      4724:         }
                   4725:     }
                   4726:     return %languages;
1.14      harris41 4727: }
                   4728: 
1.582     albertel 4729: sub languages {
                   4730:     my ($possible_langs) = @_;
1.695     raeburn  4731:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4732:     if (!ref($possible_langs)) {
                   4733: 	if( wantarray ) {
                   4734: 	    return @preferred_langs;
                   4735: 	} else {
                   4736: 	    return $preferred_langs[0];
                   4737: 	}
                   4738:     }
                   4739:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4740:     my @preferred_possibilities;
                   4741:     foreach my $preferred_lang (@preferred_langs) {
                   4742: 	if (exists($possibilities{$preferred_lang})) {
                   4743: 	    push(@preferred_possibilities, $preferred_lang);
                   4744: 	}
                   4745:     }
                   4746:     if( wantarray ) {
                   4747: 	return @preferred_possibilities;
                   4748:     }
                   4749:     return $preferred_possibilities[0];
                   4750: }
                   4751: 
1.742     raeburn  4752: sub user_lang {
                   4753:     my ($touname,$toudom,$fromcid) = @_;
                   4754:     my @userlangs;
                   4755:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4756:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4757:                     $env{'course.'.$fromcid.'.languages'}));
                   4758:     } else {
                   4759:         my %langhash = &getlangs($touname,$toudom);
                   4760:         if ($langhash{'languages'} ne '') {
                   4761:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4762:         } else {
                   4763:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4764:             if ($domdefs{'lang_def'} ne '') {
                   4765:                 @userlangs = ($domdefs{'lang_def'});
                   4766:             }
                   4767:         }
                   4768:     }
                   4769:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4770:     my $user_lh = Apache::localize->get_handle(@languages);
                   4771:     return $user_lh;
                   4772: }
                   4773: 
                   4774: 
1.112     bowersj2 4775: ###############################################################
                   4776: ##               Student Answer Attempts                     ##
                   4777: ###############################################################
                   4778: 
                   4779: =pod
                   4780: 
                   4781: =head1 Alternate Problem Views
                   4782: 
                   4783: =over 4
                   4784: 
1.648     raeburn  4785: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4786:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4787: 
                   4788: Return string with previous attempt on problem. Arguments:
                   4789: 
                   4790: =over 4
                   4791: 
                   4792: =item * $symb: Problem, including path
                   4793: 
                   4794: =item * $username: username of the desired student
                   4795: 
                   4796: =item * $domain: domain of the desired student
1.14      harris41 4797: 
1.112     bowersj2 4798: =item * $course: Course ID
1.14      harris41 4799: 
1.112     bowersj2 4800: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4801:     something
1.14      harris41 4802: 
1.112     bowersj2 4803: =item * $regexp: if string matches this regexp, the string will be
                   4804:     sent to $gradesub
1.14      harris41 4805: 
1.112     bowersj2 4806: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4807: 
1.1199    raeburn  4808: =item * $usec: section of the desired student
                   4809: 
                   4810: =item * $identifier: counter for student (multiple students one problem) or 
                   4811:     problem (one student; whole sequence).
                   4812: 
1.112     bowersj2 4813: =back
1.14      harris41 4814: 
1.112     bowersj2 4815: The output string is a table containing all desired attempts, if any.
1.16      harris41 4816: 
1.112     bowersj2 4817: =cut
1.1       albertel 4818: 
                   4819: sub get_previous_attempt {
1.1199    raeburn  4820:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4821:   my $prevattempts='';
1.43      ng       4822:   no strict 'refs';
1.1       albertel 4823:   if ($symb) {
1.3       albertel 4824:     my (%returnhash)=
                   4825:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4826:     if ($returnhash{'version'}) {
                   4827:       my %lasthash=();
                   4828:       my $version;
                   4829:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4830:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4831:             if ($key =~ /\.rawrndseed$/) {
                   4832:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4833:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4834:             } else {
                   4835:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4836:             }
1.19      harris41 4837:         }
1.1       albertel 4838:       }
1.596     albertel 4839:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4840:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4841:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4842:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4843:       foreach my $key (sort(keys(%lasthash))) {
                   4844: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4845: 	if ($#parts > 0) {
1.31      albertel 4846: 	  my $data=$parts[-1];
1.989     raeburn  4847:           next if ($data eq 'foilorder');
1.31      albertel 4848: 	  pop(@parts);
1.1010    www      4849:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4850:           if ($data eq 'type') {
                   4851:               unless ($showsurv) {
                   4852:                   my $id = join(',',@parts);
                   4853:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4854:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4855:                       $lasthidden{$ign.'.'.$id} = 1;
                   4856:                   }
1.945     raeburn  4857:               }
1.1199    raeburn  4858:               if ($identifier ne '') {
                   4859:                   my $id = join(',',@parts);
                   4860:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4861:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4862:                       $hidestatus{$ign.'.'.$id} = 1;
                   4863:                   }
                   4864:               }
                   4865:           } elsif ($data eq 'regrader') {
                   4866:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4867:                   my $id = join(',',@parts);
                   4868:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4869:               }
1.1010    www      4870:           } 
1.31      albertel 4871: 	} else {
1.41      ng       4872: 	  if ($#parts == 0) {
                   4873: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4874: 	  } else {
                   4875: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4876: 	  }
1.31      albertel 4877: 	}
1.16      harris41 4878:       }
1.596     albertel 4879:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4880:       if ($getattempt eq '') {
1.1199    raeburn  4881:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4882:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4883:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4884:                 foreach my $id (keys(%regraded)) {
                   4885:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4886:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4887:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4888:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4889:                     }
                   4890:                 }
                   4891:             }
1.1200    raeburn  4892:         }
                   4893: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4894:             my (@hidden,@unsolved);
1.945     raeburn  4895:             if (%typeparts) {
                   4896:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4897:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4898:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4899:                         push(@hidden,$id);
1.1199    raeburn  4900:                     } elsif ($identifier ne '') {
                   4901:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4902:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4903:                                 ($hidestatus{$id})) {
1.1200    raeburn  4904:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4905:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4906:                                 push(@{$solved{$id}},$version);
                   4907:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4908:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4909:                                 my $skip;
                   4910:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4911:                                     foreach my $reset (@{$resets{$id}}) {
                   4912:                                         if ($reset > $solved{$id}[-1]) {
                   4913:                                             $skip=1;
                   4914:                                             last;
                   4915:                                         }
                   4916:                                     }
                   4917:                                 }
                   4918:                                 unless ($skip) {
                   4919:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4920:                                     push(@unsolved,$partslist);
                   4921:                                 }
                   4922:                             }
                   4923:                         }
1.945     raeburn  4924:                     }
                   4925:                 }
                   4926:             }
                   4927:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4928:                            '<td>'.&mt('Transaction [_1]',$version);
                   4929:             if (@unsolved) {
                   4930:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4931:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4932:                                  &mt('Hide').'</label></span>';
                   4933:             }
                   4934:             $prevattempts .= '</td>';
1.945     raeburn  4935:             if (@hidden) {
                   4936:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4937:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4938:                     my $hide;
                   4939:                     foreach my $id (@hidden) {
                   4940:                         if ($key =~ /^\Q$id\E/) {
                   4941:                             $hide = 1;
                   4942:                             last;
                   4943:                         }
                   4944:                     }
                   4945:                     if ($hide) {
                   4946:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4947:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4948:                             my $value = &format_previous_attempt_value($key,
                   4949:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4950:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4951:                         } else {
                   4952:                             $prevattempts.='<td>&nbsp;</td>';
                   4953:                         }
                   4954:                     } else {
                   4955:                         if ($key =~ /\./) {
1.1212    raeburn  4956:                             my $value = $returnhash{$version.':'.$key};
                   4957:                             if ($key =~ /\.rndseed$/) {
                   4958:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4959:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4960:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4961:                                 }
                   4962:                             }
                   4963:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4964:                                            '&nbsp;</td>';
1.945     raeburn  4965:                         } else {
                   4966:                             $prevattempts.='<td>&nbsp;</td>';
                   4967:                         }
                   4968:                     }
                   4969:                 }
                   4970:             } else {
                   4971: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4972:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4973:                     my $value = $returnhash{$version.':'.$key};
                   4974:                     if ($key =~ /\.rndseed$/) {
                   4975:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4976:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4977:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4978:                         }
                   4979:                     }
                   4980:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4981:                                    '&nbsp;</td>';
1.945     raeburn  4982: 	        }
                   4983:             }
                   4984: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4985: 	 }
1.1       albertel 4986:       }
1.945     raeburn  4987:       my @currhidden = keys(%lasthidden);
1.596     albertel 4988:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4989:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4990:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4991:           if (%typeparts) {
                   4992:               my $hidden;
                   4993:               foreach my $id (@currhidden) {
                   4994:                   if ($key =~ /^\Q$id\E/) {
                   4995:                       $hidden = 1;
                   4996:                       last;
                   4997:                   }
                   4998:               }
                   4999:               if ($hidden) {
                   5000:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5001:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5002:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5003:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5004:                           $value = &$gradesub($value);
                   5005:                       }
1.1173    kruse    5006:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5007:                   } else {
                   5008:                       $prevattempts.='<td>&nbsp;</td>';
                   5009:                   }
                   5010:               } else {
                   5011:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5012:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5013:                       $value = &$gradesub($value);
                   5014:                   }
1.1173    kruse    5015:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5016:               }
                   5017:           } else {
                   5018: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5019: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5020:                   $value = &$gradesub($value);
                   5021:               }
1.1173    kruse    5022: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5023:           }
1.16      harris41 5024:       }
1.596     albertel 5025:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5026:     } else {
1.1305    raeburn  5027:       my $msg;
                   5028:       if ($symb =~ /ext\.tool$/) {
                   5029:           $msg = &mt('No grade passed back.');
                   5030:       } else {
                   5031:           $msg = &mt('Nothing submitted - no attempts.');
                   5032:       }
1.596     albertel 5033:       $prevattempts=
                   5034: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5035: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5036: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5037:     }
                   5038:   } else {
1.596     albertel 5039:     $prevattempts=
                   5040: 	  &start_data_table().&start_data_table_row().
                   5041: 	  '<td>'.&mt('No data.').'</td>'.
                   5042: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5043:   }
1.10      albertel 5044: }
                   5045: 
1.581     albertel 5046: sub format_previous_attempt_value {
                   5047:     my ($key,$value) = @_;
1.1011    www      5048:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5049:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5050:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5051:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5052:     } elsif ($key =~ /answerstring$/) {
                   5053:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5054:         my @answer = %answers;
                   5055:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5056:         my @anskeys = sort(keys(%answers));
                   5057:         if (@anskeys == 1) {
                   5058:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5059:             if ($answer =~ m{\0}) {
                   5060:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5061:             }
                   5062:             my $tag_internal_answer_name = 'INTERNAL';
                   5063:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5064:                 $value = $answer; 
                   5065:             } else {
                   5066:                 $value = $anskeys[0].'='.$answer;
                   5067:             }
                   5068:         } else {
                   5069:             foreach my $ans (@anskeys) {
                   5070:                 my $answer = $answers{$ans};
1.1001    raeburn  5071:                 if ($answer =~ m{\0}) {
                   5072:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5073:                 }
                   5074:                 $value .=  $ans.'='.$answer.'<br />';;
                   5075:             } 
                   5076:         }
1.581     albertel 5077:     } else {
1.1173    kruse    5078:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5079:     }
                   5080:     return $value;
                   5081: }
                   5082: 
                   5083: 
1.107     albertel 5084: sub relative_to_absolute {
                   5085:     my ($url,$output)=@_;
                   5086:     my $parser=HTML::TokeParser->new(\$output);
                   5087:     my $token;
                   5088:     my $thisdir=$url;
                   5089:     my @rlinks=();
                   5090:     while ($token=$parser->get_token) {
                   5091: 	if ($token->[0] eq 'S') {
                   5092: 	    if ($token->[1] eq 'a') {
                   5093: 		if ($token->[2]->{'href'}) {
                   5094: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5095: 		}
                   5096: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5097: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5098: 	    } elsif ($token->[1] eq 'base') {
                   5099: 		$thisdir=$token->[2]->{'href'};
                   5100: 	    }
                   5101: 	}
                   5102:     }
                   5103:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5104:     foreach my $link (@rlinks) {
1.726     raeburn  5105: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5106: 		($link=~/^\//) ||
                   5107: 		($link=~/^javascript:/i) ||
                   5108: 		($link=~/^mailto:/i) ||
                   5109: 		($link=~/^\#/)) {
                   5110: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5111: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5112: 	}
                   5113:     }
                   5114: # -------------------------------------------------- Deal with Applet codebases
                   5115:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5116:     return $output;
                   5117: }
                   5118: 
1.112     bowersj2 5119: =pod
                   5120: 
1.648     raeburn  5121: =item * &get_student_view()
1.112     bowersj2 5122: 
                   5123: show a snapshot of what student was looking at
                   5124: 
                   5125: =cut
                   5126: 
1.10      albertel 5127: sub get_student_view {
1.186     albertel 5128:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5129:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5130:   my (%form);
1.10      albertel 5131:   my @elements=('symb','courseid','domain','username');
                   5132:   foreach my $element (@elements) {
1.186     albertel 5133:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5134:   }
1.186     albertel 5135:   if (defined($moreenv)) {
                   5136:       %form=(%form,%{$moreenv});
                   5137:   }
1.236     albertel 5138:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5139:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5140:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5141:       $feedurl =~ s{^/adm/wrapper}{};
                   5142:   }
1.650     www      5143:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5144:   $userview=~s/\<body[^\>]*\>//gi;
                   5145:   $userview=~s/\<\/body\>//gi;
                   5146:   $userview=~s/\<html\>//gi;
                   5147:   $userview=~s/\<\/html\>//gi;
                   5148:   $userview=~s/\<head\>//gi;
                   5149:   $userview=~s/\<\/head\>//gi;
                   5150:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5151:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5152:   if (wantarray) {
                   5153:      return ($userview,$response);
                   5154:   } else {
                   5155:      return $userview;
                   5156:   }
                   5157: }
                   5158: 
                   5159: sub get_student_view_with_retries {
                   5160:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5161: 
                   5162:     my $ok = 0;                 # True if we got a good response.
                   5163:     my $content;
                   5164:     my $response;
                   5165: 
                   5166:     # Try to get the student_view done. within the retries count:
                   5167:     
                   5168:     do {
                   5169:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5170:          $ok      = $response->is_success;
                   5171:          if (!$ok) {
                   5172:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5173:          }
                   5174:          $retries--;
                   5175:     } while (!$ok && ($retries > 0));
                   5176:     
                   5177:     if (!$ok) {
                   5178:        $content = '';          # On error return an empty content.
                   5179:     }
1.651     www      5180:     if (wantarray) {
                   5181:        return ($content, $response);
                   5182:     } else {
                   5183:        return $content;
                   5184:     }
1.11      albertel 5185: }
                   5186: 
1.1349    raeburn  5187: sub css_links {
                   5188:     my ($currsymb,$level) = @_;
                   5189:     my ($links,@symbs,%cssrefs,%httpref);
                   5190:     if ($level eq 'map') {
                   5191:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5192:         if (ref($navmap)) {
                   5193:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5194:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5195:             foreach my $res (@resources) {
                   5196:                 if (ref($res) && $res->symb()) {
                   5197:                     push(@symbs,$res->symb());
                   5198:                 }
                   5199:             }
                   5200:         }
                   5201:     } else {
                   5202:         @symbs = ($currsymb);
                   5203:     }
                   5204:     foreach my $symb (@symbs) {
                   5205:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5206:         if ($css_href =~ /\S/) {
                   5207:             unless ($css_href =~ m{https?://}) {
                   5208:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5209:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5210:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5211:                 unless ($css_href =~ m{^/}) {
                   5212:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5213:                 }
                   5214:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5215:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5216:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5217:                         my $thisurl = $proburl;
                   5218:                         if ($env{'httpref.'.$proburl}) {
                   5219:                             $thisurl = $env{'httpref.'.$proburl};
                   5220:                         }
                   5221:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5222:                     }
                   5223:                 }
                   5224:             }
                   5225:             $cssrefs{$css_href} = 1;
                   5226:         }
                   5227:     }
                   5228:     if (keys(%httpref)) {
                   5229:         &Apache::lonnet::appenv(\%httpref);
                   5230:     }
                   5231:     if (keys(%cssrefs)) {
                   5232:         foreach my $css_href (keys(%cssrefs)) {
                   5233:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5234:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5235:         }
                   5236:     }
                   5237:     return $links;
                   5238: }
                   5239: 
1.112     bowersj2 5240: =pod
                   5241: 
1.648     raeburn  5242: =item * &get_student_answers() 
1.112     bowersj2 5243: 
                   5244: show a snapshot of how student was answering problem
                   5245: 
                   5246: =cut
                   5247: 
1.11      albertel 5248: sub get_student_answers {
1.100     sakharuk 5249:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5250:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5251:   my (%moreenv);
1.11      albertel 5252:   my @elements=('symb','courseid','domain','username');
                   5253:   foreach my $element (@elements) {
1.186     albertel 5254:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5255:   }
1.186     albertel 5256:   $moreenv{'grade_target'}='answer';
                   5257:   %moreenv=(%form,%moreenv);
1.497     raeburn  5258:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5259:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5260:   return $userview;
1.1       albertel 5261: }
1.116     albertel 5262: 
                   5263: =pod
                   5264: 
                   5265: =item * &submlink()
                   5266: 
1.242     albertel 5267: Inputs: $text $uname $udom $symb $target
1.116     albertel 5268: 
                   5269: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5270: 
                   5271: =cut
                   5272: 
                   5273: ###############################################
                   5274: sub submlink {
1.242     albertel 5275:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5276:     if (!($uname && $udom)) {
                   5277: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5278: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5279: 	if (!$symb) { $symb=$cursymb; }
                   5280:     }
1.254     matthew  5281:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5282:     $symb=&escape($symb);
1.960     bisitz   5283:     if ($target) { $target=" target=\"$target\""; }
                   5284:     return
                   5285:         '<a href="/adm/grades?command=submission'.
                   5286:         '&amp;symb='.$symb.
                   5287:         '&amp;student='.$uname.
                   5288:         '&amp;userdom='.$udom.'"'.
                   5289:         $target.'>'.$text.'</a>';
1.242     albertel 5290: }
                   5291: ##############################################
                   5292: 
                   5293: =pod
                   5294: 
                   5295: =item * &pgrdlink()
                   5296: 
                   5297: Inputs: $text $uname $udom $symb $target
                   5298: 
                   5299: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5300: 
                   5301: =cut
                   5302: 
                   5303: ###############################################
                   5304: sub pgrdlink {
                   5305:     my $link=&submlink(@_);
                   5306:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5307:     return $link;
                   5308: }
                   5309: ##############################################
                   5310: 
                   5311: =pod
                   5312: 
                   5313: =item * &pprmlink()
                   5314: 
                   5315: Inputs: $text $uname $udom $symb $target
                   5316: 
                   5317: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5318: student and a specific resource
1.242     albertel 5319: 
                   5320: =cut
                   5321: 
                   5322: ###############################################
                   5323: sub pprmlink {
                   5324:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5325:     if (!($uname && $udom)) {
                   5326: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5327: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5328: 	if (!$symb) { $symb=$cursymb; }
                   5329:     }
1.254     matthew  5330:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5331:     $symb=&escape($symb);
1.242     albertel 5332:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5333:     return '<a href="/adm/parmset?command=set&amp;'.
                   5334: 	'symb='.$symb.'&amp;uname='.$uname.
                   5335: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5336: }
                   5337: ##############################################
1.37      matthew  5338: 
1.112     bowersj2 5339: =pod
                   5340: 
                   5341: =back
                   5342: 
                   5343: =cut
                   5344: 
1.37      matthew  5345: ###############################################
1.51      www      5346: 
                   5347: 
                   5348: sub timehash {
1.687     raeburn  5349:     my ($thistime) = @_;
                   5350:     my $timezone = &Apache::lonlocal::gettimezone();
                   5351:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5352:                      ->set_time_zone($timezone);
                   5353:     my $wday = $dt->day_of_week();
                   5354:     if ($wday == 7) { $wday = 0; }
                   5355:     return ( 'second' => $dt->second(),
                   5356:              'minute' => $dt->minute(),
                   5357:              'hour'   => $dt->hour(),
                   5358:              'day'     => $dt->day_of_month(),
                   5359:              'month'   => $dt->month(),
                   5360:              'year'    => $dt->year(),
                   5361:              'weekday' => $wday,
                   5362:              'dayyear' => $dt->day_of_year(),
                   5363:              'dlsav'   => $dt->is_dst() );
1.51      www      5364: }
                   5365: 
1.370     www      5366: sub utc_string {
                   5367:     my ($date)=@_;
1.371     www      5368:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5369: }
                   5370: 
1.51      www      5371: sub maketime {
                   5372:     my %th=@_;
1.687     raeburn  5373:     my ($epoch_time,$timezone,$dt);
                   5374:     $timezone = &Apache::lonlocal::gettimezone();
                   5375:     eval {
                   5376:         $dt = DateTime->new( year   => $th{'year'},
                   5377:                              month  => $th{'month'},
                   5378:                              day    => $th{'day'},
                   5379:                              hour   => $th{'hour'},
                   5380:                              minute => $th{'minute'},
                   5381:                              second => $th{'second'},
                   5382:                              time_zone => $timezone,
                   5383:                          );
                   5384:     };
                   5385:     if (!$@) {
                   5386:         $epoch_time = $dt->epoch;
                   5387:         if ($epoch_time) {
                   5388:             return $epoch_time;
                   5389:         }
                   5390:     }
1.51      www      5391:     return POSIX::mktime(
                   5392:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5393:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5394: }
                   5395: 
                   5396: #########################################
1.51      www      5397: 
                   5398: sub findallcourses {
1.482     raeburn  5399:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5400:     my %roles;
                   5401:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5402:     my %courses;
1.51      www      5403:     my $now=time;
1.482     raeburn  5404:     if (!defined($uname)) {
                   5405:         $uname = $env{'user.name'};
                   5406:     }
                   5407:     if (!defined($udom)) {
                   5408:         $udom = $env{'user.domain'};
                   5409:     }
                   5410:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5411:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5412:         if (!%roles) {
                   5413:             %roles = (
                   5414:                        cc => 1,
1.907     raeburn  5415:                        co => 1,
1.482     raeburn  5416:                        in => 1,
                   5417:                        ep => 1,
                   5418:                        ta => 1,
                   5419:                        cr => 1,
                   5420:                        st => 1,
                   5421:              );
                   5422:         }
                   5423:         foreach my $entry (keys(%roleshash)) {
                   5424:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5425:             if ($trole =~ /^cr/) { 
                   5426:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5427:             } else {
                   5428:                 next if (!exists($roles{$trole}));
                   5429:             }
                   5430:             if ($tend) {
                   5431:                 next if ($tend < $now);
                   5432:             }
                   5433:             if ($tstart) {
                   5434:                 next if ($tstart > $now);
                   5435:             }
1.1058    raeburn  5436:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5437:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5438:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5439:             if ($secpart eq '') {
                   5440:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5441:                 $sec = 'none';
1.1058    raeburn  5442:                 $value .= $cnum.'/';
1.482     raeburn  5443:             } else {
                   5444:                 $cnum = $cnumpart;
                   5445:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5446:                 $value .= $cnum.'/'.$sec;
                   5447:             }
                   5448:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5449:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5450:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5451:                 }
                   5452:             } else {
                   5453:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5454:             }
1.482     raeburn  5455:         }
                   5456:     } else {
                   5457:         foreach my $key (keys(%env)) {
1.483     albertel 5458: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5459:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5460: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5461: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5462: 	        next if (%roles && !exists($roles{$role}));
                   5463: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5464:                 my $active=1;
                   5465:                 if ($starttime) {
                   5466: 		    if ($now<$starttime) { $active=0; }
                   5467:                 }
                   5468:                 if ($endtime) {
                   5469:                     if ($now>$endtime) { $active=0; }
                   5470:                 }
                   5471:                 if ($active) {
1.1058    raeburn  5472:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5473:                     if ($sec eq '') {
                   5474:                         $sec = 'none';
1.1058    raeburn  5475:                     } else {
                   5476:                         $value .= $sec;
                   5477:                     }
                   5478:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5479:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5480:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5481:                         }
                   5482:                     } else {
                   5483:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5484:                     }
1.474     raeburn  5485:                 }
                   5486:             }
1.51      www      5487:         }
                   5488:     }
1.474     raeburn  5489:     return %courses;
1.51      www      5490: }
1.37      matthew  5491: 
1.54      www      5492: ###############################################
1.474     raeburn  5493: 
                   5494: sub blockcheck {
1.1372    raeburn  5495:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5496:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5497:         my ($has_evb,$check_ipaccess);
                   5498:         my $dom = $env{'user.domain'};
                   5499:         if ($env{'request.course.id'}) {
                   5500:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5501:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5502:             my $checkrole = "cm./$cdom/$cnum";
                   5503:             my $sec = $env{'request.course.sec'};
                   5504:             if ($sec ne '') {
                   5505:                 $checkrole .= "/$sec";
                   5506:             }
                   5507:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5508:                 ($env{'request.role'} !~ /^st/)) {
                   5509:                 $has_evb = 1;
                   5510:             }
                   5511:             unless ($has_evb) {
                   5512:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5513:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5514:                     if ($udom eq $cdom) {
                   5515:                         $check_ipaccess = 1;
                   5516:                     }
                   5517:                 }
                   5518:             }
1.1375    raeburn  5519:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5520:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5521:             my $checkrole;
                   5522:             if ($env{'request.role.domain'} eq '') {
                   5523:                 $checkrole = "cm./$env{'user.domain'}/";
                   5524:             } else {
                   5525:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5526:             }
                   5527:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5528:                 $has_evb = 1;
                   5529:             }
1.1372    raeburn  5530:         }
                   5531:         unless ($has_evb || $check_ipaccess) {
                   5532:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5533:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5534:                 $dom = $udom;
                   5535:             }
                   5536:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5537:                 $check_ipaccess = 1;
                   5538:             } else {
                   5539:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5540:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5541:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5542:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5543:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5544:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5545:                         $check_ipaccess = 1;
                   5546:                     }
                   5547:                 }
                   5548:             }
                   5549:         }
                   5550:         if ($check_ipaccess) {
                   5551:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5552:             unless (defined($cached)) {
                   5553:                 my %domconfig =
                   5554:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5555:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5556:             }
                   5557:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5558:                 foreach my $id (keys(%{$ipaccessref})) {
                   5559:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5560:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5561:                         if ($range) {
                   5562:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5563:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5564:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5565:                                         return ('','','',$id,$dom);
                   5566:                                         last;
                   5567:                                     }
                   5568:                                 }
                   5569:                             }
                   5570:                         }
                   5571:                     }
                   5572:                 }
                   5573:             }
                   5574:         }
1.1373    raeburn  5575:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5576:             return ();
                   5577:         }
1.1372    raeburn  5578:     }
1.1189    raeburn  5579:     if (defined($udom) && defined($uname)) {
                   5580:         # If uname and udom are for a course, check for blocks in the course.
                   5581:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5582:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5583:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5584:             return ($startblock,$endblock,$triggerblock);
                   5585:         }
                   5586:     } else {
1.490     raeburn  5587:         $udom = $env{'user.domain'};
                   5588:         $uname = $env{'user.name'};
                   5589:     }
                   5590: 
1.502     raeburn  5591:     my $startblock = 0;
                   5592:     my $endblock = 0;
1.1062    raeburn  5593:     my $triggerblock = '';
1.1373    raeburn  5594:     my %live_courses;
                   5595:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5596:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5597:     }
1.474     raeburn  5598: 
1.490     raeburn  5599:     # If uname is for a user, and activity is course-specific, i.e.,
                   5600:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5601: 
1.490     raeburn  5602:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5603:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5604:          $activity eq 'search' || $activity eq 'reinit' ||
                   5605:          $activity eq 'alert') &&
1.1189    raeburn  5606:         ($env{'request.course.id'})) {
1.490     raeburn  5607:         foreach my $key (keys(%live_courses)) {
                   5608:             if ($key ne $env{'request.course.id'}) {
                   5609:                 delete($live_courses{$key});
                   5610:             }
                   5611:         }
                   5612:     }
                   5613: 
                   5614:     my $otheruser = 0;
                   5615:     my %own_courses;
                   5616:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5617:         # Resource belongs to user other than current user.
                   5618:         $otheruser = 1;
                   5619:         # Gather courses for current user
                   5620:         %own_courses = 
                   5621:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5622:     }
                   5623: 
                   5624:     # Gather active course roles - course coordinator, instructor, 
                   5625:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5626: 
                   5627:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5628:         my ($cdom,$cnum);
                   5629:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5630:             $cdom = $env{'course.'.$course.'.domain'};
                   5631:             $cnum = $env{'course.'.$course.'.num'};
                   5632:         } else {
1.490     raeburn  5633:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5634:         }
                   5635:         my $no_ownblock = 0;
                   5636:         my $no_userblock = 0;
1.533     raeburn  5637:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5638:             # Check if current user has 'evb' priv for this
                   5639:             if (defined($own_courses{$course})) {
                   5640:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5641:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5642:                     if ($sec ne 'none') {
                   5643:                         $checkrole .= '/'.$sec;
                   5644:                     }
                   5645:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5646:                         $no_ownblock = 1;
                   5647:                         last;
                   5648:                     }
                   5649:                 }
                   5650:             }
                   5651:             # if they have 'evb' priv and are currently not playing student
                   5652:             next if (($no_ownblock) &&
                   5653:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5654:         }
1.474     raeburn  5655:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5656:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5657:             if ($sec ne 'none') {
1.482     raeburn  5658:                 $checkrole .= '/'.$sec;
1.474     raeburn  5659:             }
1.490     raeburn  5660:             if ($otheruser) {
                   5661:                 # Resource belongs to user other than current user.
                   5662:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5663:                 my (%allroles,%userroles);
                   5664:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5665:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5666:                         my ($trole,$tdom,$tnum,$tsec);
                   5667:                         if ($entry =~ /^cr/) {
                   5668:                             ($trole,$tdom,$tnum,$tsec) = 
                   5669:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5670:                         } else {
                   5671:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5672:                         }
                   5673:                         my ($spec,$area,$trest);
                   5674:                         $area = '/'.$tdom.'/'.$tnum;
                   5675:                         $trest = $tnum;
                   5676:                         if ($tsec ne '') {
                   5677:                             $area .= '/'.$tsec;
                   5678:                             $trest .= '/'.$tsec;
                   5679:                         }
                   5680:                         $spec = $trole.'.'.$area;
                   5681:                         if ($trole =~ /^cr/) {
                   5682:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5683:                                                               $tdom,$spec,$trest,$area);
                   5684:                         } else {
                   5685:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5686:                                                                 $tdom,$spec,$trest,$area);
                   5687:                         }
                   5688:                     }
1.1276    raeburn  5689:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5690:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5691:                         if ($1) {
                   5692:                             $no_userblock = 1;
                   5693:                             last;
                   5694:                         }
1.486     raeburn  5695:                     }
                   5696:                 }
1.490     raeburn  5697:             } else {
                   5698:                 # Resource belongs to current user
                   5699:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5700:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5701:                     $no_ownblock = 1;
                   5702:                     last;
                   5703:                 }
1.474     raeburn  5704:             }
                   5705:         }
                   5706:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5707:         next if (($no_ownblock) &&
1.491     albertel 5708:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5709:         next if ($no_userblock);
1.474     raeburn  5710: 
1.1303    raeburn  5711:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5712:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5713: 
1.1062    raeburn  5714:         my ($start,$end,$trigger) = 
1.1347    raeburn  5715:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5716:         if (($start != 0) && 
                   5717:             (($startblock == 0) || ($startblock > $start))) {
                   5718:             $startblock = $start;
1.1062    raeburn  5719:             if ($trigger ne '') {
                   5720:                 $triggerblock = $trigger;
                   5721:             }
1.502     raeburn  5722:         }
                   5723:         if (($end != 0)  &&
                   5724:             (($endblock == 0) || ($endblock < $end))) {
                   5725:             $endblock = $end;
1.1062    raeburn  5726:             if ($trigger ne '') {
                   5727:                 $triggerblock = $trigger;
                   5728:             }
1.502     raeburn  5729:         }
1.490     raeburn  5730:     }
1.1062    raeburn  5731:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5732: }
                   5733: 
                   5734: sub get_blocks {
1.1347    raeburn  5735:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5736:     my $startblock = 0;
                   5737:     my $endblock = 0;
1.1062    raeburn  5738:     my $triggerblock = '';
1.490     raeburn  5739:     my $course = $cdom.'_'.$cnum;
                   5740:     $setters->{$course} = {};
                   5741:     $setters->{$course}{'staff'} = [];
                   5742:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5743:     $setters->{$course}{'triggers'} = [];
                   5744:     my (@blockers,%triggered);
                   5745:     my $now = time;
                   5746:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5747:     if ($activity eq 'docs') {
1.1348    raeburn  5748:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5749:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5750:             $blocked = 1;
                   5751:             $nosymbcache = 1;
1.1348    raeburn  5752:             $noenccheck = 1;
1.1347    raeburn  5753:         }
1.1348    raeburn  5754:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5755:         foreach my $block (@blockers) {
                   5756:             if ($block =~ /^firstaccess____(.+)$/) {
                   5757:                 my $item = $1;
                   5758:                 my $type = 'map';
                   5759:                 my $timersymb = $item;
                   5760:                 if ($item eq 'course') {
                   5761:                     $type = 'course';
                   5762:                 } elsif ($item =~ /___\d+___/) {
                   5763:                     $type = 'resource';
                   5764:                 } else {
                   5765:                     $timersymb = &Apache::lonnet::symbread($item);
                   5766:                 }
                   5767:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5768:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5769:                 $triggered{$block} = {
                   5770:                                        start => $start,
                   5771:                                        end   => $end,
                   5772:                                        type  => $type,
                   5773:                                      };
                   5774:             }
                   5775:         }
                   5776:     } else {
                   5777:         foreach my $block (keys(%commblocks)) {
                   5778:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5779:                 my ($start,$end) = ($1,$2);
                   5780:                 if ($start <= time && $end >= time) {
                   5781:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5782:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5783:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5784:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5785:                                     push(@blockers,$block);
                   5786:                                 }
                   5787:                             }
                   5788:                         }
                   5789:                     }
                   5790:                 }
                   5791:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5792:                 my $item = $1;
                   5793:                 my $timersymb = $item; 
                   5794:                 my $type = 'map';
                   5795:                 if ($item eq 'course') {
                   5796:                     $type = 'course';
                   5797:                 } elsif ($item =~ /___\d+___/) {
                   5798:                     $type = 'resource';
                   5799:                 } else {
                   5800:                     $timersymb = &Apache::lonnet::symbread($item);
                   5801:                 }
                   5802:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5803:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5804:                 if ($start && $end) {
                   5805:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5806:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5807:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5808:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5809:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5810:                                         push(@blockers,$block);
                   5811:                                         $triggered{$block} = {
                   5812:                                                                start => $start,
                   5813:                                                                end   => $end,
                   5814:                                                                type  => $type,
                   5815:                                                              };
                   5816:                                     }
                   5817:                                 }
                   5818:                             }
1.1062    raeburn  5819:                         }
                   5820:                     }
1.490     raeburn  5821:                 }
1.1062    raeburn  5822:             }
                   5823:         }
                   5824:     }
                   5825:     foreach my $blocker (@blockers) {
                   5826:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5827:             &parse_block_record($commblocks{$blocker});
                   5828:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5829:         my ($start,$end,$triggertype);
                   5830:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5831:             ($start,$end) = ($1,$2);
                   5832:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5833:             $start = $triggered{$blocker}{'start'};
                   5834:             $end = $triggered{$blocker}{'end'};
                   5835:             $triggertype = $triggered{$blocker}{'type'};
                   5836:         }
                   5837:         if ($start) {
                   5838:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5839:             if ($triggertype) {
                   5840:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5841:             } else {
                   5842:                 push(@{$$setters{$course}{'triggers'}},0);
                   5843:             }
                   5844:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5845:                 $startblock = $start;
                   5846:                 if ($triggertype) {
                   5847:                     $triggerblock = $blocker;
1.474     raeburn  5848:                 }
                   5849:             }
1.1062    raeburn  5850:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5851:                $endblock = $end;
                   5852:                if ($triggertype) {
                   5853:                    $triggerblock = $blocker;
                   5854:                }
                   5855:             }
1.474     raeburn  5856:         }
                   5857:     }
1.1062    raeburn  5858:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5859: }
                   5860: 
                   5861: sub parse_block_record {
                   5862:     my ($record) = @_;
                   5863:     my ($setuname,$setudom,$title,$blocks);
                   5864:     if (ref($record) eq 'HASH') {
                   5865:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5866:         $title = &unescape($record->{'event'});
                   5867:         $blocks = $record->{'blocks'};
                   5868:     } else {
                   5869:         my @data = split(/:/,$record,3);
                   5870:         if (scalar(@data) eq 2) {
                   5871:             $title = $data[1];
                   5872:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5873:         } else {
                   5874:             ($setuname,$setudom,$title) = @data;
                   5875:         }
                   5876:         $blocks = { 'com' => 'on' };
                   5877:     }
                   5878:     return ($setuname,$setudom,$title,$blocks);
                   5879: }
                   5880: 
1.854     kalberla 5881: sub blocking_status {
1.1372    raeburn  5882:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5883:     my %setters;
1.890     droeschl 5884: 
1.1061    raeburn  5885: # check for active blocking
1.1372    raeburn  5886:     if ($clientip eq '') {
                   5887:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5888:     }
                   5889:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5890:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5891:     my $blocked = 0;
1.1372    raeburn  5892:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5893:         $blocked = 1;
                   5894:     }
1.890     droeschl 5895: 
1.1061    raeburn  5896: # caller just wants to know whether a block is active
                   5897:     if (!wantarray) { return $blocked; }
                   5898: 
                   5899: # build a link to a popup window containing the details
                   5900:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5901: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5902:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5903:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5904:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5905:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5906:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5907:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5908:         if ($symb) {
                   5909:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5910:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5911:         }
1.1062    raeburn  5912:     }
1.1061    raeburn  5913: 
                   5914:     my $output .= <<'END_MYBLOCK';
                   5915: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5916:     var options = "width=" + w + ",height=" + h + ",";
                   5917:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5918:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5919:     var newWin = window.open(url, wdwName, options);
                   5920:     newWin.focus();
                   5921: }
1.890     droeschl 5922: END_MYBLOCK
1.854     kalberla 5923: 
1.1061    raeburn  5924:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5925:   
1.1061    raeburn  5926:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5927:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5928:     my $class = 'LC_comblock';
1.1062    raeburn  5929:     if ($activity eq 'docs') {
                   5930:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5931:         $class = '';
1.1063    raeburn  5932:     } elsif ($activity eq 'printout') {
                   5933:         $text = &mt('Printing Blocked');
1.1232    raeburn  5934:     } elsif ($activity eq 'passwd') {
                   5935:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5936:     } elsif ($activity eq 'grades') {
                   5937:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5938:     } elsif ($activity eq 'search') {
                   5939:         $text = &mt('Search Blocked');
1.1282    raeburn  5940:     } elsif ($activity eq 'alert') {
                   5941:         $text = &mt('Checking Critical Messages Blocked');
                   5942:     } elsif ($activity eq 'reinit') {
                   5943:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5944:     } elsif ($activity eq 'about') {
                   5945:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  5946:     } elsif ($activity eq 'wishlist') {
                   5947:         $text = &mt('Access to Stored Links Blocked');
                   5948:     } elsif ($activity eq 'annotate') {
                   5949:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5950:     }
1.1061    raeburn  5951:     $output .= <<"END_BLOCK";
1.1217    raeburn  5952: <div class='$class'>
1.869     kalberla 5953:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5954:   title='$text'>
                   5955:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5956:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5957:   title='$text'>$text</a>
1.867     kalberla 5958: </div>
                   5959: 
                   5960: END_BLOCK
1.474     raeburn  5961: 
1.1061    raeburn  5962:     return ($blocked, $output);
1.854     kalberla 5963: }
1.490     raeburn  5964: 
1.60      matthew  5965: ###############################################
                   5966: 
1.682     raeburn  5967: sub check_ip_acc {
1.1201    raeburn  5968:     my ($acc,$clientip)=@_;
1.682     raeburn  5969:     &Apache::lonxml::debug("acc is $acc");
                   5970:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5971:         return 1;
                   5972:     }
1.1339    raeburn  5973:     my ($ip,$allowed);
                   5974:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5975:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5976:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5977:     } else {
1.1350    raeburn  5978:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5979:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5980:     }
1.682     raeburn  5981: 
                   5982:     my $name;
1.1219    raeburn  5983:     my %access = (
                   5984:                      allowfrom => 1,
                   5985:                      denyfrom  => 0,
                   5986:                  );
                   5987:     my @allows;
                   5988:     my @denies;
                   5989:     foreach my $item (split(',',$acc)) {
                   5990:         $item =~ s/^\s*//;
                   5991:         $item =~ s/\s*$//;
                   5992:         my $pattern;
                   5993:         if ($item =~ /^\!(.+)$/) {
                   5994:             push(@denies,$1);
                   5995:         } else {
                   5996:             push(@allows,$item);
                   5997:         }
                   5998:    }
                   5999:    my $numdenies = scalar(@denies);
                   6000:    my $numallows = scalar(@allows);
                   6001:    my $count = 0;
                   6002:    foreach my $pattern (@denies,@allows) {
                   6003:         $count ++; 
                   6004:         my $acctype = 'allowfrom';
                   6005:         if ($count <= $numdenies) {
                   6006:             $acctype = 'denyfrom';
                   6007:         }
1.682     raeburn  6008:         if ($pattern =~ /\*$/) {
                   6009:             #35.8.*
                   6010:             $pattern=~s/\*//;
1.1219    raeburn  6011:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6012:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6013:             #35.8.3.[34-56]
                   6014:             my $low=$2;
                   6015:             my $high=$3;
                   6016:             $pattern=$1;
                   6017:             if ($ip =~ /^\Q$pattern\E/) {
                   6018:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6019:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6020:             }
                   6021:         } elsif ($pattern =~ /^\*/) {
                   6022:             #*.msu.edu
                   6023:             $pattern=~s/\*//;
                   6024:             if (!defined($name)) {
                   6025:                 use Socket;
                   6026:                 my $netaddr=inet_aton($ip);
                   6027:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6028:             }
1.1219    raeburn  6029:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6030:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6031:             #127.0.0.1
1.1219    raeburn  6032:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6033:         } else {
                   6034:             #some.name.com
                   6035:             if (!defined($name)) {
                   6036:                 use Socket;
                   6037:                 my $netaddr=inet_aton($ip);
                   6038:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6039:             }
1.1219    raeburn  6040:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6041:         }
                   6042:         if ($allowed =~ /^(0|1)$/) { last; }
                   6043:     }
                   6044:     if ($allowed eq '') {
                   6045:         if ($numdenies && !$numallows) {
                   6046:             $allowed = 1;
                   6047:         } else {
                   6048:             $allowed = 0;
1.682     raeburn  6049:         }
                   6050:     }
                   6051:     return $allowed;
                   6052: }
                   6053: 
                   6054: ###############################################
                   6055: 
1.60      matthew  6056: =pod
                   6057: 
1.112     bowersj2 6058: =head1 Domain Template Functions
                   6059: 
                   6060: =over 4
                   6061: 
                   6062: =item * &determinedomain()
1.60      matthew  6063: 
                   6064: Inputs: $domain (usually will be undef)
                   6065: 
1.63      www      6066: Returns: Determines which domain should be used for designs
1.60      matthew  6067: 
                   6068: =cut
1.54      www      6069: 
1.60      matthew  6070: ###############################################
1.63      www      6071: sub determinedomain {
                   6072:     my $domain=shift;
1.531     albertel 6073:     if (! $domain) {
1.60      matthew  6074:         # Determine domain if we have not been given one
1.893     raeburn  6075:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6076:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6077:         if ($env{'request.role.domain'}) { 
                   6078:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6079:         }
                   6080:     }
1.63      www      6081:     return $domain;
                   6082: }
                   6083: ###############################################
1.517     raeburn  6084: 
1.518     albertel 6085: sub devalidate_domconfig_cache {
                   6086:     my ($udom)=@_;
                   6087:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6088: }
                   6089: 
                   6090: # ---------------------- Get domain configuration for a domain
                   6091: sub get_domainconf {
                   6092:     my ($udom) = @_;
                   6093:     my $cachetime=1800;
                   6094:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6095:     if (defined($cached)) { return %{$result}; }
                   6096: 
                   6097:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6098: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6099:     my (%designhash,%legacy);
1.518     albertel 6100:     if (keys(%domconfig) > 0) {
                   6101:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6102:             if (keys(%{$domconfig{'login'}})) {
                   6103:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6104:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6105:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6106:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6107:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6108:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6109:                                         if ($key eq 'loginvia') {
                   6110:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6111:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6112:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6113:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6114: 
                   6115:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6116:                                                 } else {
                   6117:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6118:                                                 }
1.948     raeburn  6119:                                             }
1.1208    raeburn  6120:                                         } elsif ($key eq 'headtag') {
                   6121:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6122:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6123:                                             }
1.946     raeburn  6124:                                         }
1.1208    raeburn  6125:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6126:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6127:                                         }
1.946     raeburn  6128:                                     }
                   6129:                                 }
                   6130:                             }
1.1366    raeburn  6131:                         } elsif ($key eq 'saml') {
                   6132:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6133:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6134:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6135:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6136:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6137:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6138:                                         }
                   6139:                                     }
                   6140:                                 }
                   6141:                             }
1.946     raeburn  6142:                         } else {
                   6143:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6144:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6145:                                     $domconfig{'login'}{$key}{$img};
                   6146:                             }
1.699     raeburn  6147:                         }
                   6148:                     } else {
                   6149:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6150:                     }
1.632     raeburn  6151:                 }
                   6152:             } else {
                   6153:                 $legacy{'login'} = 1;
1.518     albertel 6154:             }
1.632     raeburn  6155:         } else {
                   6156:             $legacy{'login'} = 1;
1.518     albertel 6157:         }
                   6158:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6159:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6160:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6161:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6162:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6163:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6164:                         }
1.518     albertel 6165:                     }
                   6166:                 }
1.632     raeburn  6167:             } else {
                   6168:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6169:             }
1.632     raeburn  6170:         } else {
                   6171:             $legacy{'rolecolors'} = 1;
1.518     albertel 6172:         }
1.948     raeburn  6173:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6174:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6175:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6176:             }
                   6177:         }
1.632     raeburn  6178:         if (keys(%legacy) > 0) {
                   6179:             my %legacyhash = &get_legacy_domconf($udom);
                   6180:             foreach my $item (keys(%legacyhash)) {
                   6181:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6182:                     if ($legacy{'login'}) { 
                   6183:                         $designhash{$item} = $legacyhash{$item};
                   6184:                     }
                   6185:                 } else {
                   6186:                     if ($legacy{'rolecolors'}) {
                   6187:                         $designhash{$item} = $legacyhash{$item};
                   6188:                     }
1.518     albertel 6189:                 }
                   6190:             }
                   6191:         }
1.632     raeburn  6192:     } else {
                   6193:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6194:     }
                   6195:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6196: 				  $cachetime);
                   6197:     return %designhash;
                   6198: }
                   6199: 
1.632     raeburn  6200: sub get_legacy_domconf {
                   6201:     my ($udom) = @_;
                   6202:     my %legacyhash;
                   6203:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6204:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6205:     if (-e $designfile) {
1.1317    raeburn  6206:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6207:             while (my $line = <$fh>) {
                   6208:                 next if ($line =~ /^\#/);
                   6209:                 chomp($line);
                   6210:                 my ($key,$val)=(split(/\=/,$line));
                   6211:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6212:             }
                   6213:             close($fh);
                   6214:         }
                   6215:     }
1.1026    raeburn  6216:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6217:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6218:     }
                   6219:     return %legacyhash;
                   6220: }
                   6221: 
1.63      www      6222: =pod
                   6223: 
1.112     bowersj2 6224: =item * &domainlogo()
1.63      www      6225: 
                   6226: Inputs: $domain (usually will be undef)
                   6227: 
                   6228: Returns: A link to a domain logo, if the domain logo exists.
                   6229: If the domain logo does not exist, a description of the domain.
                   6230: 
                   6231: =cut
1.112     bowersj2 6232: 
1.63      www      6233: ###############################################
                   6234: sub domainlogo {
1.517     raeburn  6235:     my $domain = &determinedomain(shift);
1.518     albertel 6236:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6237:     # See if there is a logo
                   6238:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6239:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6240:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6241: 	    if ($imgsrc =~ m{^/res/}) {
                   6242: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6243: 		&Apache::lonnet::repcopy($local_name);
                   6244: 	    }
                   6245: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6246:         }
                   6247:         my $alttext = $domain;
                   6248:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6249:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6250:         }
                   6251:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6252:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6253:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6254:     } else {
1.60      matthew  6255:         return '';
1.59      www      6256:     }
                   6257: }
1.63      www      6258: ##############################################
                   6259: 
                   6260: =pod
                   6261: 
1.112     bowersj2 6262: =item * &designparm()
1.63      www      6263: 
                   6264: Inputs: $which parameter; $domain (usually will be undef)
                   6265: 
                   6266: Returns: value of designparamter $which
                   6267: 
                   6268: =cut
1.112     bowersj2 6269: 
1.397     albertel 6270: 
1.400     albertel 6271: ##############################################
1.397     albertel 6272: sub designparm {
                   6273:     my ($which,$domain)=@_;
                   6274:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6275:         return $env{'environment.color.'.$which};
1.96      www      6276:     }
1.63      www      6277:     $domain=&determinedomain($domain);
1.1016    raeburn  6278:     my %domdesign;
                   6279:     unless ($domain eq 'public') {
                   6280:         %domdesign = &get_domainconf($domain);
                   6281:     }
1.520     raeburn  6282:     my $output;
1.517     raeburn  6283:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6284:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6285:     } else {
1.520     raeburn  6286:         $output = $defaultdesign{$which};
                   6287:     }
                   6288:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6289:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6290:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6291:             if ($output =~ m{^/res/}) {
                   6292:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6293:                 &Apache::lonnet::repcopy($local_name);
                   6294:             }
1.520     raeburn  6295:             $output = &lonhttpdurl($output);
                   6296:         }
1.63      www      6297:     }
1.520     raeburn  6298:     return $output;
1.63      www      6299: }
1.59      www      6300: 
1.822     bisitz   6301: ##############################################
                   6302: =pod
                   6303: 
1.832     bisitz   6304: =item * &authorspace()
                   6305: 
1.1028    raeburn  6306: Inputs: $url (usually will be undef).
1.832     bisitz   6307: 
1.1132    raeburn  6308: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6309:          directory being viewed (or for which action is being taken). 
                   6310:          If $url is provided, and begins /priv/<domain>/<uname>
                   6311:          the path will be that portion of the $context argument.
                   6312:          Otherwise the path will be for the author space of the current
                   6313:          user when the current role is author, or for that of the 
                   6314:          co-author/assistant co-author space when the current role 
                   6315:          is co-author or assistant co-author.
1.832     bisitz   6316: 
                   6317: =cut
                   6318: 
                   6319: sub authorspace {
1.1028    raeburn  6320:     my ($url) = @_;
                   6321:     if ($url ne '') {
                   6322:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6323:            return $1;
                   6324:         }
                   6325:     }
1.832     bisitz   6326:     my $caname = '';
1.1024    www      6327:     my $cadom = '';
1.1028    raeburn  6328:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6329:         ($cadom,$caname) =
1.832     bisitz   6330:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6331:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6332:         $caname = $env{'user.name'};
1.1024    www      6333:         $cadom = $env{'user.domain'};
1.832     bisitz   6334:     }
1.1028    raeburn  6335:     if (($caname ne '') && ($cadom ne '')) {
                   6336:         return "/priv/$cadom/$caname/";
                   6337:     }
                   6338:     return;
1.832     bisitz   6339: }
                   6340: 
                   6341: ##############################################
                   6342: =pod
                   6343: 
1.822     bisitz   6344: =item * &head_subbox()
                   6345: 
                   6346: Inputs: $content (contains HTML code with page functions, etc.)
                   6347: 
                   6348: Returns: HTML div with $content
                   6349:          To be included in page header
                   6350: 
                   6351: =cut
                   6352: 
                   6353: sub head_subbox {
                   6354:     my ($content)=@_;
                   6355:     my $output =
1.993     raeburn  6356:         '<div class="LC_head_subbox">'
1.822     bisitz   6357:        .$content
                   6358:        .'</div>'
                   6359: }
                   6360: 
                   6361: ##############################################
                   6362: =pod
                   6363: 
                   6364: =item * &CSTR_pageheader()
                   6365: 
1.1026    raeburn  6366: Input: (optional) filename from which breadcrumb trail is built.
                   6367:        In most cases no input as needed, as $env{'request.filename'}
                   6368:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6369:        frameset flag
                   6370:        If page header is being requested for use in a frameset, then
                   6371:        the second (option) argument -- frameset will be true, and
                   6372:        the target attribute set for links should be target="_parent".
1.1407    raeburn  6373:        If $title is supplied as the thitd arg, that will be used to 
                   6374:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6375: 
                   6376: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6377:          To be included on Authoring Space pages
1.822     bisitz   6378: 
                   6379: =cut
                   6380: 
                   6381: sub CSTR_pageheader {
1.1407    raeburn  6382:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6383:     if ($trailfile eq '') {
                   6384:         $trailfile = $env{'request.filename'};
                   6385:     }
                   6386: 
                   6387: # this is for resources; directories have customtitle, and crumbs
                   6388: # and select recent are created in lonpubdir.pm
                   6389: 
                   6390:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6391:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6392:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6393:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6394:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6395: 
                   6396:     my $parentpath = '';
                   6397:     my $lastitem = '';
                   6398:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6399:         $parentpath = $1;
                   6400:         $lastitem = $2;
                   6401:     } else {
                   6402:         $lastitem = $thisdisfn;
                   6403:     }
1.921     bisitz   6404: 
1.1406    raeburn  6405:     my $crsauthor;
1.1246    raeburn  6406:     if (($env{'request.course.id'}) &&
                   6407:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6408:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6409:         $crsauthor = 1;
1.1406    raeburn  6410:         if ($title eq '') {
                   6411:             $title = &mt('Course Authoring Space');
                   6412:         }
                   6413:     } elsif ($title eq '') {
1.1246    raeburn  6414:         $title = &mt('Authoring Space');
                   6415:     }
                   6416: 
1.1379    raeburn  6417:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6418:     if ($frameset) {
                   6419:         $target = ' target="_parent"';
                   6420:         $crumbtarget = '_parent';
                   6421:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6422:         $target = '';
                   6423:         $crumbtarget = '';
1.1379    raeburn  6424:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6425:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6426:         $crumbtarget = $env{'request.deeplink.target'};
                   6427:     }
1.1313    raeburn  6428: 
1.921     bisitz   6429:     my $output =
1.1407    raeburn  6430:          '<div>'
1.822     bisitz   6431:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6432:         .'<b>'.$title.'</b> '
1.1314    raeburn  6433:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6434:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6435: 
                   6436:     if ($lastitem) {
                   6437:         $output .=
                   6438:              '<span class="LC_filename">'
                   6439:             .$lastitem
                   6440:             .'</span>';
                   6441:     }
1.1245    raeburn  6442: 
1.1246    raeburn  6443:     if ($crsauthor) {
1.1379    raeburn  6444:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6445:     } else {
                   6446:         $output .=
                   6447:              '<br />'
1.1314    raeburn  6448:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6449:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6450:             .'</form>'
1.1379    raeburn  6451:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6452:     }
1.1407    raeburn  6453:     $output .= '</div>';
1.921     bisitz   6454: 
                   6455:     return $output;
1.822     bisitz   6456: }
                   6457: 
1.60      matthew  6458: ###############################################
                   6459: ###############################################
                   6460: 
                   6461: =pod
                   6462: 
1.112     bowersj2 6463: =back
                   6464: 
1.549     albertel 6465: =head1 HTML Helpers
1.112     bowersj2 6466: 
                   6467: =over 4
                   6468: 
                   6469: =item * &bodytag()
1.60      matthew  6470: 
                   6471: Returns a uniform header for LON-CAPA web pages.
                   6472: 
                   6473: Inputs: 
                   6474: 
1.112     bowersj2 6475: =over 4
                   6476: 
                   6477: =item * $title, A title to be displayed on the page.
                   6478: 
                   6479: =item * $function, the current role (can be undef).
                   6480: 
                   6481: =item * $addentries, extra parameters for the <body> tag.
                   6482: 
                   6483: =item * $bodyonly, if defined, only return the <body> tag.
                   6484: 
                   6485: =item * $domain, if defined, force a given domain.
                   6486: 
                   6487: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6488:             text interface only)
1.60      matthew  6489: 
1.814     bisitz   6490: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6491:                      navigational links
1.317     albertel 6492: 
1.338     albertel 6493: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6494: 
1.460     albertel 6495: =item * $args, optional argument valid values are
                   6496:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6497:             use_absolute     -> for external resource or syllabus, this will
                   6498:                                 contain https://<hostname> if server uses
                   6499:                                 https (as per hosts.tab), but request is for http
                   6500:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6501: 
1.1096    raeburn  6502: =item * $advtoolsref, optional argument, ref to an array containing
                   6503:             inlineremote items to be added in "Functions" menu below
                   6504:             breadcrumbs.
                   6505: 
1.1316    raeburn  6506: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6507:             course, if LON-CAPA is in LTI Provider context. Value is
                   6508:             the scope of use, i.e., launch was for access to a single, a map
                   6509:             or the entire course.
                   6510: 
                   6511: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6512:             context, this will contain the URL for the landing item in
                   6513:             the course, after launch from an LTI Consumer
                   6514: 
1.1318    raeburn  6515: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6516:             context, this will contain a reference to hash of items
                   6517:             to be included in the page header and/or inline menu.
                   6518: 
1.1385    raeburn  6519: =item * $menucoll, optional argument, if specific menu collection is in
                   6520:             effect, either set as the default for the course, or set for
                   6521:             the deeplink paramater for $env{'request.deeplink.login'}
                   6522:             then $menucoll will be the number of that collection. 
                   6523: 
                   6524: =item * $menuref, optional argument, reference to a hash, containing the
                   6525:             menu options included for the menu in effect, based on the
                   6526:             configuration for the numbered menu collection in use.  
                   6527: 
                   6528: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6529:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6530:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6531:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6532:             being called a second time.
                   6533: 
1.112     bowersj2 6534: =back
                   6535: 
1.60      matthew  6536: Returns: A uniform header for LON-CAPA web pages.  
                   6537: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6538: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6539: other decorations will be returned.
                   6540: 
                   6541: =cut
                   6542: 
1.54      www      6543: sub bodytag {
1.831     bisitz   6544:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6545:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6546:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6547: 
1.954     raeburn  6548:     my $public;
                   6549:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6550:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6551:         $public = 1;
                   6552:     }
1.460     albertel 6553:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6554:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6555:     my $hostname = $args->{'hostname'};
1.339     albertel 6556: 
1.183     matthew  6557:     $function = &get_users_function() if (!$function);
1.339     albertel 6558:     my $img =    &designparm($function.'.img',$domain);
                   6559:     my $font =   &designparm($function.'.font',$domain);
                   6560:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6561: 
1.803     bisitz   6562:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6563: 		   'bgcolor' => $pgbg,
1.339     albertel 6564: 		   'text'    => $font,
                   6565:                    'alink'   => &designparm($function.'.alink',$domain),
                   6566: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6567: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6568:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6569: 
1.63      www      6570:  # role and realm
1.1178    raeburn  6571:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6572:     if ($realm) {
                   6573:         $realm = '/'.$realm;
                   6574:     }
1.1357    raeburn  6575:     if ($role eq 'ca') {
1.479     albertel 6576:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6577:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6578:     } 
1.55      www      6579: # realm
1.1357    raeburn  6580:     my ($cid,$sec);
1.258     albertel 6581:     if ($env{'request.course.id'}) {
1.1357    raeburn  6582:         $cid = $env{'request.course.id'};
                   6583:         if ($env{'request.course.sec'}) {
                   6584:             $sec = $env{'request.course.sec'};
                   6585:         }
                   6586:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6587:         if (&Apache::lonnet::is_course($1,$2)) {
                   6588:             $cid = $1.'_'.$2;
                   6589:             $sec = $3;
                   6590:         }
                   6591:     }
                   6592:     if ($cid) {
1.378     raeburn  6593:         if ($env{'request.role'} !~ /^cr/) {
                   6594:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6595:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6596:             if ($env{'request.role.desc'}) {
                   6597:                 $role = $env{'request.role.desc'};
                   6598:             } else {
                   6599:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6600:             }
1.1257    raeburn  6601:         } else {
                   6602:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6603:         }
1.1357    raeburn  6604:         if ($sec) {
                   6605:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6606:         }   
1.1357    raeburn  6607: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6608:     } else {
                   6609:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6610:     }
1.433     albertel 6611: 
1.359     albertel 6612:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6613: 
1.438     albertel 6614:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6615: 
1.101     www      6616: # construct main body tag
1.359     albertel 6617:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6618: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6619: 
1.1131    raeburn  6620:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6621: 
1.1130    raeburn  6622:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6623:         return $bodytag;
1.1130    raeburn  6624:     }
1.359     albertel 6625: 
1.954     raeburn  6626:     if ($public) {
1.433     albertel 6627: 	undef($role);
                   6628:     }
1.1318    raeburn  6629: 
1.1359    raeburn  6630:     my $showcrstitle = 1;
1.1357    raeburn  6631:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6632:         if (ref($ltimenu) eq 'HASH') {
                   6633:             unless ($ltimenu->{'role'}) {
                   6634:                 undef($role);
                   6635:             }
                   6636:             unless ($ltimenu->{'coursetitle'}) {
                   6637:                 $realm='&nbsp;';
1.1359    raeburn  6638:                 $showcrstitle = 0;
                   6639:             }
                   6640:         }
                   6641:     } elsif (($cid) && ($menucoll)) {
                   6642:         if (ref($menuref) eq 'HASH') {
                   6643:             unless ($menuref->{'role'}) {
                   6644:                 undef($role);
                   6645:             }
                   6646:             unless ($menuref->{'crs'}) {
                   6647:                 $realm='&nbsp;';
                   6648:                 $showcrstitle = 0;
1.1318    raeburn  6649:             }
                   6650:         }
                   6651:     }
                   6652: 
1.762     bisitz   6653:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6654:     #
                   6655:     # Extra info if you are the DC
                   6656:     my $dc_info = '';
1.1359    raeburn  6657:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6658:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6659:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6660:         $dc_info =~ s/\s+$//;
1.359     albertel 6661:     }
                   6662: 
1.1237    raeburn  6663:     my $crstype;
1.1357    raeburn  6664:     if ($cid) {
                   6665:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6666:     } elsif ($args->{'crstype'}) {
                   6667:         $crstype = $args->{'crstype'};
                   6668:     }
                   6669:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6670:         undef($role);
                   6671:     } else {
1.1242    raeburn  6672:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6673:     }
1.853     droeschl 6674: 
1.903     droeschl 6675:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6676: 
                   6677:         #    if ($env{'request.state'} eq 'construct') {
                   6678:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6679:         #    }
                   6680: 
1.1130    raeburn  6681:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6682:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6683: 
1.1318    raeburn  6684:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6685:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6686:                                                               $args->{'links_disabled'},
                   6687:                                                               $args->{'links_target'});
1.359     albertel 6688: 
1.1318    raeburn  6689:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6690:                 if ($dc_info) {
                   6691:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6692:                 }
                   6693:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6694:                                <em>$realm</em> $dc_info</div>|;
                   6695:                 return $bodytag;
                   6696:             }
1.894     droeschl 6697: 
1.1318    raeburn  6698:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6699:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6700:             }
1.916     droeschl 6701: 
1.1318    raeburn  6702:             $bodytag .= $right;
1.852     droeschl 6703: 
1.1318    raeburn  6704:             if ($dc_info) {
                   6705:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6706:             }
                   6707:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6708:         }
1.916     droeschl 6709: 
1.1169    raeburn  6710:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6711:         if ($args->{'no_secondary_menu'}) {
                   6712:             return $bodytag;
                   6713:         }
1.1169    raeburn  6714:         #don't show menus for public users
1.954     raeburn  6715:         if (!$public){
1.1318    raeburn  6716:             unless ($args->{'no_inline_menu'}) {
                   6717:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6718:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6719:                                                             $menucoll,$menuref,
1.1380    raeburn  6720:                                                             $args->{'links_disabled'},
                   6721:                                                             $args->{'links_target'});
1.1318    raeburn  6722:             }
1.903     droeschl 6723:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6724:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6725:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6726:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  6727:                                 $args->{'bread_crumbs'},'','',$hostname,
                   6728:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6729:             } elsif ($forcereg) {
                   6730:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  6731:                                 $args->{'group'},$args->{'hide_buttons'},
                   6732:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6733:             } else {
                   6734:                 $bodytag .= 
                   6735:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6736:                                                         $forcereg,$args->{'group'},
                   6737:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6738:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6739:             }
1.903     droeschl 6740:         }else{
                   6741:             # this is to seperate menu from content when there's no secondary
                   6742:             # menu. Especially needed for public accessible ressources.
                   6743:             $bodytag .= '<hr style="clear:both" />';
                   6744:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6745:         }
1.903     droeschl 6746: 
1.235     raeburn  6747:         return $bodytag;
1.182     matthew  6748: }
                   6749: 
1.917     raeburn  6750: sub dc_courseid_toggle {
                   6751:     my ($dc_info) = @_;
1.980     raeburn  6752:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6753:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6754:            &mt('(More ...)').'</a></span>'.
                   6755:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6756: }
                   6757: 
1.330     albertel 6758: sub make_attr_string {
                   6759:     my ($register,$attr_ref) = @_;
                   6760: 
                   6761:     if ($attr_ref && !ref($attr_ref)) {
                   6762: 	die("addentries Must be a hash ref ".
                   6763: 	    join(':',caller(1))." ".
                   6764: 	    join(':',caller(0))." ");
                   6765:     }
                   6766: 
                   6767:     if ($register) {
1.339     albertel 6768: 	my ($on_load,$on_unload);
                   6769: 	foreach my $key (keys(%{$attr_ref})) {
                   6770: 	    if      (lc($key) eq 'onload') {
                   6771: 		$on_load.=$attr_ref->{$key}.';';
                   6772: 		delete($attr_ref->{$key});
                   6773: 
                   6774: 	    } elsif (lc($key) eq 'onunload') {
                   6775: 		$on_unload.=$attr_ref->{$key}.';';
                   6776: 		delete($attr_ref->{$key});
                   6777: 	    }
                   6778: 	}
1.953     droeschl 6779: 	$attr_ref->{'onload'}  = $on_load;
                   6780: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6781:     }
1.339     albertel 6782: 
1.330     albertel 6783:     my $attr_string;
1.1159    raeburn  6784:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6785: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6786:     }
                   6787:     return $attr_string;
                   6788: }
                   6789: 
                   6790: 
1.182     matthew  6791: ###############################################
1.251     albertel 6792: ###############################################
                   6793: 
                   6794: =pod
                   6795: 
                   6796: =item * &endbodytag()
                   6797: 
                   6798: Returns a uniform footer for LON-CAPA web pages.
                   6799: 
1.635     raeburn  6800: Inputs: 1 - optional reference to an args hash
                   6801: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6802: a 'Continue' link is not displayed if the page contains an
                   6803: internal redirect in the <head></head> section,
                   6804: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6805: 
                   6806: =cut
                   6807: 
                   6808: sub endbodytag {
1.635     raeburn  6809:     my ($args) = @_;
1.1080    raeburn  6810:     my $endbodytag;
                   6811:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6812:         $endbodytag='</body>';
                   6813:     }
1.315     albertel 6814:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6815:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  6816:             my ($endbodyjs,$idattr);
                   6817:             if ($env{'internal.head.to_opener'}) {
                   6818:                 my $linkid = 'LC_continue_link';
                   6819:                 $idattr = ' id="'.$linkid.'"';
                   6820:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6821:                 $endbodyjs=<<ENDJS;
                   6822: <script type="text/javascript">
                   6823: // <![CDATA[
                   6824: function ebFunction(evt) {
                   6825:     evt.preventDefault();
                   6826:     var dest = '$redirect_for_js';
                   6827:     if (window.opener != null && !window.opener.closed) {
                   6828:         window.opener.location.href=dest;
                   6829:         window.close();
                   6830:     } else {
                   6831:         window.location.href=dest;
                   6832:     }
                   6833:     return false;
                   6834: }
                   6835: 
                   6836: \$(document).ready(function () {
                   6837:   if (document.getElementById('$linkid')) {
                   6838:     var clickelem = document.getElementById('$linkid');
                   6839:     clickelem.addEventListener('click',ebFunction,false);
                   6840:   }
                   6841: });
                   6842: // ]]>
                   6843: </script>
                   6844: ENDJS
                   6845:             }
1.635     raeburn  6846: 	    $endbodytag=
1.1386    raeburn  6847: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6848: 	        &mt('Continue').'</a>'.
                   6849: 	        $endbodytag;
                   6850:         }
1.315     albertel 6851:     }
1.251     albertel 6852:     return $endbodytag;
                   6853: }
                   6854: 
1.352     albertel 6855: =pod
                   6856: 
                   6857: =item * &standard_css()
                   6858: 
                   6859: Returns a style sheet
                   6860: 
                   6861: Inputs: (all optional)
                   6862:             domain         -> force to color decorate a page for a specific
                   6863:                                domain
                   6864:             function       -> force usage of a specific rolish color scheme
                   6865:             bgcolor        -> override the default page bgcolor
                   6866: 
                   6867: =cut
                   6868: 
1.343     albertel 6869: sub standard_css {
1.345     albertel 6870:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6871:     $function  = &get_users_function() if (!$function);
                   6872:     my $img    = &designparm($function.'.img',   $domain);
                   6873:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6874:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6875:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6876: #second colour for later usage
1.345     albertel 6877:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6878:     my $pgbg_or_bgcolor =
                   6879: 	         $bgcolor ||
1.352     albertel 6880: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6881:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6882:     my $alink  = &designparm($function.'.alink', $domain);
                   6883:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6884:     my $link   = &designparm($function.'.link',  $domain);
                   6885: 
1.602     albertel 6886:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6887:     my $mono                 = 'monospace';
1.850     bisitz   6888:     my $data_table_head      = $sidebg;
                   6889:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6890:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6891:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6892:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6893:     my $mail_new             = '#FFBB77';
                   6894:     my $mail_new_hover       = '#DD9955';
                   6895:     my $mail_read            = '#BBBB77';
                   6896:     my $mail_read_hover      = '#999944';
                   6897:     my $mail_replied         = '#AAAA88';
                   6898:     my $mail_replied_hover   = '#888855';
                   6899:     my $mail_other           = '#99BBBB';
                   6900:     my $mail_other_hover     = '#669999';
1.391     albertel 6901:     my $table_header         = '#DDDDDD';
1.489     raeburn  6902:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6903:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6904:     my $button_hover         = '#BF2317';
1.392     albertel 6905: 
1.608     albertel 6906:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6907:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6908:                                              : '0 3px 0 4px';
1.448     albertel 6909: 
1.523     albertel 6910: 
1.343     albertel 6911:     return <<END;
1.947     droeschl 6912: 
                   6913: /* needed for iframe to allow 100% height in FF */
                   6914: body, html { 
                   6915:     margin: 0;
                   6916:     padding: 0 0.5%;
                   6917:     height: 99%; /* to avoid scrollbars */
                   6918: }
                   6919: 
1.795     www      6920: body {
1.911     bisitz   6921:   font-family: $sans;
                   6922:   line-height:130%;
                   6923:   font-size:0.83em;
                   6924:   color:$font;
1.795     www      6925: }
                   6926: 
1.959     onken    6927: a:focus,
                   6928: a:focus img {
1.795     www      6929:   color: red;
                   6930: }
1.698     harmsja  6931: 
1.911     bisitz   6932: form, .inline {
                   6933:   display: inline;
1.795     www      6934: }
1.721     harmsja  6935: 
1.795     www      6936: .LC_right {
1.911     bisitz   6937:   text-align:right;
1.795     www      6938: }
                   6939: 
                   6940: .LC_middle {
1.911     bisitz   6941:   vertical-align:middle;
1.795     www      6942: }
1.721     harmsja  6943: 
1.1130    raeburn  6944: .LC_floatleft {
                   6945:   float: left;
                   6946: }
                   6947: 
                   6948: .LC_floatright {
                   6949:   float: right;
                   6950: }
                   6951: 
1.911     bisitz   6952: .LC_400Box {
                   6953:   width:400px;
                   6954: }
1.721     harmsja  6955: 
1.947     droeschl 6956: .LC_iframecontainer {
                   6957:     width: 98%;
                   6958:     margin: 0;
                   6959:     position: fixed;
                   6960:     top: 8.5em;
                   6961:     bottom: 0;
                   6962: }
                   6963: 
                   6964: .LC_iframecontainer iframe{
                   6965:     border: none;
                   6966:     width: 100%;
                   6967:     height: 100%;
                   6968: }
                   6969: 
1.778     bisitz   6970: .LC_filename {
                   6971:   font-family: $mono;
                   6972:   white-space:pre;
1.921     bisitz   6973:   font-size: 120%;
1.778     bisitz   6974: }
                   6975: 
                   6976: .LC_fileicon {
                   6977:   border: none;
                   6978:   height: 1.3em;
                   6979:   vertical-align: text-bottom;
                   6980:   margin-right: 0.3em;
                   6981:   text-decoration:none;
                   6982: }
                   6983: 
1.1008    www      6984: .LC_setting {
                   6985:   text-decoration:underline;
                   6986: }
                   6987: 
1.350     albertel 6988: .LC_error {
                   6989:   color: red;
                   6990: }
1.795     www      6991: 
1.1097    bisitz   6992: .LC_warning {
                   6993:   color: darkorange;
                   6994: }
                   6995: 
1.457     albertel 6996: .LC_diff_removed {
1.733     bisitz   6997:   color: red;
1.394     albertel 6998: }
1.532     albertel 6999: 
                   7000: .LC_info,
1.457     albertel 7001: .LC_success,
                   7002: .LC_diff_added {
1.350     albertel 7003:   color: green;
                   7004: }
1.795     www      7005: 
1.802     bisitz   7006: div.LC_confirm_box {
                   7007:   background-color: #FAFAFA;
                   7008:   border: 1px solid $lg_border_color;
                   7009:   margin-right: 0;
                   7010:   padding: 5px;
                   7011: }
                   7012: 
                   7013: div.LC_confirm_box .LC_error img,
                   7014: div.LC_confirm_box .LC_success img {
                   7015:   vertical-align: middle;
                   7016: }
                   7017: 
1.1242    raeburn  7018: .LC_maxwidth {
                   7019:   max-width: 100%;
                   7020:   height: auto;
                   7021: }
                   7022: 
1.1243    raeburn  7023: .LC_textsize_mobile {
                   7024:   \@media only screen and (max-device-width: 480px) {
                   7025:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7026:   }
                   7027: }
                   7028: 
1.440     albertel 7029: .LC_icon {
1.771     droeschl 7030:   border: none;
1.790     droeschl 7031:   vertical-align: middle;
1.771     droeschl 7032: }
                   7033: 
1.543     albertel 7034: .LC_docs_spacer {
                   7035:   width: 25px;
                   7036:   height: 1px;
1.771     droeschl 7037:   border: none;
1.543     albertel 7038: }
1.346     albertel 7039: 
1.532     albertel 7040: .LC_internal_info {
1.735     bisitz   7041:   color: #999999;
1.532     albertel 7042: }
                   7043: 
1.794     www      7044: .LC_discussion {
1.1050    www      7045:   background: $data_table_dark;
1.911     bisitz   7046:   border: 1px solid black;
                   7047:   margin: 2px;
1.794     www      7048: }
                   7049: 
                   7050: .LC_disc_action_left {
1.1050    www      7051:   background: $sidebg;
1.911     bisitz   7052:   text-align: left;
1.1050    www      7053:   padding: 4px;
                   7054:   margin: 2px;
1.794     www      7055: }
                   7056: 
                   7057: .LC_disc_action_right {
1.1050    www      7058:   background: $sidebg;
1.911     bisitz   7059:   text-align: right;
1.1050    www      7060:   padding: 4px;
                   7061:   margin: 2px;
1.794     www      7062: }
                   7063: 
                   7064: .LC_disc_new_item {
1.911     bisitz   7065:   background: white;
                   7066:   border: 2px solid red;
1.1050    www      7067:   margin: 4px;
                   7068:   padding: 4px;
1.794     www      7069: }
                   7070: 
                   7071: .LC_disc_old_item {
1.911     bisitz   7072:   background: white;
1.1050    www      7073:   margin: 4px;
                   7074:   padding: 4px;
1.794     www      7075: }
                   7076: 
1.458     albertel 7077: table.LC_pastsubmission {
                   7078:   border: 1px solid black;
                   7079:   margin: 2px;
                   7080: }
                   7081: 
1.924     bisitz   7082: table#LC_menubuttons {
1.345     albertel 7083:   width: 100%;
                   7084:   background: $pgbg;
1.392     albertel 7085:   border: 2px;
1.402     albertel 7086:   border-collapse: separate;
1.803     bisitz   7087:   padding: 0;
1.345     albertel 7088: }
1.392     albertel 7089: 
1.801     tempelho 7090: table#LC_title_bar a {
                   7091:   color: $fontmenu;
                   7092: }
1.836     bisitz   7093: 
1.807     droeschl 7094: table#LC_title_bar {
1.819     tempelho 7095:   clear: both;
1.836     bisitz   7096:   display: none;
1.807     droeschl 7097: }
                   7098: 
1.795     www      7099: table#LC_title_bar,
1.933     droeschl 7100: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7101: table#LC_title_bar.LC_with_remote {
1.359     albertel 7102:   width: 100%;
1.392     albertel 7103:   border-color: $pgbg;
                   7104:   border-style: solid;
                   7105:   border-width: $border;
1.379     albertel 7106:   background: $pgbg;
1.801     tempelho 7107:   color: $fontmenu;
1.392     albertel 7108:   border-collapse: collapse;
1.803     bisitz   7109:   padding: 0;
1.819     tempelho 7110:   margin: 0;
1.359     albertel 7111: }
1.795     www      7112: 
1.933     droeschl 7113: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7114:     margin: 0;
                   7115:     padding: 0;
1.933     droeschl 7116:     position: relative;
                   7117:     list-style: none;
1.913     droeschl 7118: }
1.933     droeschl 7119: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7120:     display: inline;
                   7121: }
1.933     droeschl 7122: 
                   7123: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7124:     padding: 0;
1.933     droeschl 7125:     margin: 0;
                   7126:     float: left;
1.913     droeschl 7127: }
1.933     droeschl 7128: .LC_breadcrumb_tools_tools {
                   7129:     padding: 0;
                   7130:     margin: 0;
1.913     droeschl 7131:     float: right;
                   7132: }
                   7133: 
1.1240    raeburn  7134: .LC_placement_prog {
                   7135:     padding-right: 20px;
                   7136:     font-weight: bold;
                   7137:     font-size: 90%;
                   7138: }
                   7139: 
1.359     albertel 7140: table#LC_title_bar td {
                   7141:   background: $tabbg;
                   7142: }
1.795     www      7143: 
1.911     bisitz   7144: table#LC_menubuttons img {
1.803     bisitz   7145:   border: none;
1.346     albertel 7146: }
1.795     www      7147: 
1.842     droeschl 7148: .LC_breadcrumbs_component {
1.911     bisitz   7149:   float: right;
                   7150:   margin: 0 1em;
1.357     albertel 7151: }
1.842     droeschl 7152: .LC_breadcrumbs_component img {
1.911     bisitz   7153:   vertical-align: middle;
1.777     tempelho 7154: }
1.795     www      7155: 
1.1243    raeburn  7156: .LC_breadcrumbs_hoverable {
                   7157:   background: $sidebg;
                   7158: }
                   7159: 
1.383     albertel 7160: td.LC_table_cell_checkbox {
                   7161:   text-align: center;
                   7162: }
1.795     www      7163: 
                   7164: .LC_fontsize_small {
1.911     bisitz   7165:   font-size: 70%;
1.705     tempelho 7166: }
                   7167: 
1.844     bisitz   7168: #LC_breadcrumbs {
1.911     bisitz   7169:   clear:both;
                   7170:   background: $sidebg;
                   7171:   border-bottom: 1px solid $lg_border_color;
                   7172:   line-height: 2.5em;
1.933     droeschl 7173:   overflow: hidden;
1.911     bisitz   7174:   margin: 0;
                   7175:   padding: 0;
1.995     raeburn  7176:   text-align: left;
1.819     tempelho 7177: }
1.862     bisitz   7178: 
1.1098    bisitz   7179: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7180:   clear:both;
                   7181:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7182:   border: 1px solid $sidebg;
1.1098    bisitz   7183:   margin: 0 0 10px 0;
1.966     bisitz   7184:   padding: 3px;
1.995     raeburn  7185:   text-align: left;
1.822     bisitz   7186: }
                   7187: 
1.795     www      7188: .LC_fontsize_medium {
1.911     bisitz   7189:   font-size: 85%;
1.705     tempelho 7190: }
                   7191: 
1.795     www      7192: .LC_fontsize_large {
1.911     bisitz   7193:   font-size: 120%;
1.705     tempelho 7194: }
                   7195: 
1.346     albertel 7196: .LC_menubuttons_inline_text {
                   7197:   color: $font;
1.698     harmsja  7198:   font-size: 90%;
1.701     harmsja  7199:   padding-left:3px;
1.346     albertel 7200: }
                   7201: 
1.934     droeschl 7202: .LC_menubuttons_inline_text img{
                   7203:   vertical-align: middle;
                   7204: }
                   7205: 
1.1051    www      7206: li.LC_menubuttons_inline_text img {
1.951     onken    7207:   cursor:pointer;
1.1002    droeschl 7208:   text-decoration: none;
1.951     onken    7209: }
                   7210: 
1.526     www      7211: .LC_menubuttons_link {
                   7212:   text-decoration: none;
                   7213: }
1.795     www      7214: 
1.522     albertel 7215: .LC_menubuttons_category {
1.521     www      7216:   color: $font;
1.526     www      7217:   background: $pgbg;
1.521     www      7218:   font-size: larger;
                   7219:   font-weight: bold;
                   7220: }
                   7221: 
1.346     albertel 7222: td.LC_menubuttons_text {
1.911     bisitz   7223:   color: $font;
1.346     albertel 7224: }
1.706     harmsja  7225: 
1.346     albertel 7226: .LC_current_location {
                   7227:   background: $tabbg;
                   7228: }
1.795     www      7229: 
1.1286    raeburn  7230: td.LC_zero_height {
                   7231:   line-height: 0; 
                   7232:   cellpadding: 0;
                   7233: }
                   7234: 
1.938     bisitz   7235: table.LC_data_table {
1.347     albertel 7236:   border: 1px solid #000000;
1.402     albertel 7237:   border-collapse: separate;
1.426     albertel 7238:   border-spacing: 1px;
1.610     albertel 7239:   background: $pgbg;
1.347     albertel 7240: }
1.795     www      7241: 
1.422     albertel 7242: .LC_data_table_dense {
                   7243:   font-size: small;
                   7244: }
1.795     www      7245: 
1.507     raeburn  7246: table.LC_nested_outer {
                   7247:   border: 1px solid #000000;
1.589     raeburn  7248:   border-collapse: collapse;
1.803     bisitz   7249:   border-spacing: 0;
1.507     raeburn  7250:   width: 100%;
                   7251: }
1.795     www      7252: 
1.879     raeburn  7253: table.LC_innerpickbox,
1.507     raeburn  7254: table.LC_nested {
1.803     bisitz   7255:   border: none;
1.589     raeburn  7256:   border-collapse: collapse;
1.803     bisitz   7257:   border-spacing: 0;
1.507     raeburn  7258:   width: 100%;
                   7259: }
1.795     www      7260: 
1.911     bisitz   7261: table.LC_data_table tr th,
                   7262: table.LC_calendar tr th,
1.879     raeburn  7263: table.LC_prior_tries tr th,
                   7264: table.LC_innerpickbox tr th {
1.349     albertel 7265:   font-weight: bold;
                   7266:   background-color: $data_table_head;
1.801     tempelho 7267:   color:$fontmenu;
1.701     harmsja  7268:   font-size:90%;
1.347     albertel 7269: }
1.795     www      7270: 
1.879     raeburn  7271: table.LC_innerpickbox tr th,
                   7272: table.LC_innerpickbox tr td {
                   7273:   vertical-align: top;
                   7274: }
                   7275: 
1.711     raeburn  7276: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7277:   background-color: #CCCCCC;
1.711     raeburn  7278:   font-weight: bold;
                   7279:   text-align: left;
                   7280: }
1.795     www      7281: 
1.912     bisitz   7282: table.LC_data_table tr.LC_odd_row > td {
                   7283:   background-color: $data_table_light;
                   7284:   padding: 2px;
                   7285:   vertical-align: top;
                   7286: }
                   7287: 
1.809     bisitz   7288: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7289:   background-color: $data_table_light;
1.912     bisitz   7290:   vertical-align: top;
                   7291: }
                   7292: 
                   7293: table.LC_data_table tr.LC_even_row > td {
                   7294:   background-color: $data_table_dark;
1.425     albertel 7295:   padding: 2px;
1.900     bisitz   7296:   vertical-align: top;
1.347     albertel 7297: }
1.795     www      7298: 
1.809     bisitz   7299: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7300:   background-color: $data_table_dark;
1.900     bisitz   7301:   vertical-align: top;
1.347     albertel 7302: }
1.795     www      7303: 
1.425     albertel 7304: table.LC_data_table tr.LC_data_table_highlight td {
                   7305:   background-color: $data_table_darker;
                   7306: }
1.795     www      7307: 
1.639     raeburn  7308: table.LC_data_table tr td.LC_leftcol_header {
                   7309:   background-color: $data_table_head;
                   7310:   font-weight: bold;
                   7311: }
1.795     www      7312: 
1.451     albertel 7313: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7314: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7315:   font-weight: bold;
                   7316:   font-style: italic;
                   7317:   text-align: center;
                   7318:   padding: 8px;
1.347     albertel 7319: }
1.795     www      7320: 
1.1114    raeburn  7321: table.LC_data_table tr.LC_empty_row td,
                   7322: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7323:   background-color: $sidebg;
                   7324: }
                   7325: 
                   7326: table.LC_nested tr.LC_empty_row td {
                   7327:   background-color: #FFFFFF;
                   7328: }
                   7329: 
1.890     droeschl 7330: table.LC_caption {
                   7331: }
                   7332: 
1.507     raeburn  7333: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7334:   padding: 4ex
                   7335: }
1.795     www      7336: 
1.507     raeburn  7337: table.LC_nested_outer tr th {
                   7338:   font-weight: bold;
1.801     tempelho 7339:   color:$fontmenu;
1.507     raeburn  7340:   background-color: $data_table_head;
1.701     harmsja  7341:   font-size: small;
1.507     raeburn  7342:   border-bottom: 1px solid #000000;
                   7343: }
1.795     www      7344: 
1.507     raeburn  7345: table.LC_nested_outer tr td.LC_subheader {
                   7346:   background-color: $data_table_head;
                   7347:   font-weight: bold;
                   7348:   font-size: small;
                   7349:   border-bottom: 1px solid #000000;
                   7350:   text-align: right;
1.451     albertel 7351: }
1.795     www      7352: 
1.507     raeburn  7353: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7354:   background-color: #CCCCCC;
1.451     albertel 7355:   font-weight: bold;
                   7356:   font-size: small;
1.507     raeburn  7357:   text-align: center;
                   7358: }
1.795     www      7359: 
1.589     raeburn  7360: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7361: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7362:   text-align: left;
1.451     albertel 7363: }
1.795     www      7364: 
1.507     raeburn  7365: table.LC_nested td {
1.735     bisitz   7366:   background-color: #FFFFFF;
1.451     albertel 7367:   font-size: small;
1.507     raeburn  7368: }
1.795     www      7369: 
1.507     raeburn  7370: table.LC_nested_outer tr th.LC_right_item,
                   7371: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7372: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7373: table.LC_nested tr td.LC_right_item {
1.451     albertel 7374:   text-align: right;
                   7375: }
                   7376: 
1.507     raeburn  7377: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7378:   background-color: #EEEEEE;
1.451     albertel 7379: }
                   7380: 
1.473     raeburn  7381: table.LC_createuser {
                   7382: }
                   7383: 
                   7384: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7385:   font-size: small;
1.473     raeburn  7386: }
                   7387: 
                   7388: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7389:   background-color: #CCCCCC;
1.473     raeburn  7390:   font-weight: bold;
                   7391:   text-align: center;
                   7392: }
                   7393: 
1.349     albertel 7394: table.LC_calendar {
                   7395:   border: 1px solid #000000;
                   7396:   border-collapse: collapse;
1.917     raeburn  7397:   width: 98%;
1.349     albertel 7398: }
1.795     www      7399: 
1.349     albertel 7400: table.LC_calendar_pickdate {
                   7401:   font-size: xx-small;
                   7402: }
1.795     www      7403: 
1.349     albertel 7404: table.LC_calendar tr td {
                   7405:   border: 1px solid #000000;
                   7406:   vertical-align: top;
1.917     raeburn  7407:   width: 14%;
1.349     albertel 7408: }
1.795     www      7409: 
1.349     albertel 7410: table.LC_calendar tr td.LC_calendar_day_empty {
                   7411:   background-color: $data_table_dark;
                   7412: }
1.795     www      7413: 
1.779     bisitz   7414: table.LC_calendar tr td.LC_calendar_day_current {
                   7415:   background-color: $data_table_highlight;
1.777     tempelho 7416: }
1.795     www      7417: 
1.938     bisitz   7418: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7419:   background-color: $mail_new;
                   7420: }
1.795     www      7421: 
1.938     bisitz   7422: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7423:   background-color: $mail_new_hover;
                   7424: }
1.795     www      7425: 
1.938     bisitz   7426: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7427:   background-color: $mail_read;
                   7428: }
1.795     www      7429: 
1.938     bisitz   7430: /*
                   7431: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7432:   background-color: $mail_read_hover;
                   7433: }
1.938     bisitz   7434: */
1.795     www      7435: 
1.938     bisitz   7436: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7437:   background-color: $mail_replied;
                   7438: }
1.795     www      7439: 
1.938     bisitz   7440: /*
                   7441: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7442:   background-color: $mail_replied_hover;
                   7443: }
1.938     bisitz   7444: */
1.795     www      7445: 
1.938     bisitz   7446: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7447:   background-color: $mail_other;
                   7448: }
1.795     www      7449: 
1.938     bisitz   7450: /*
                   7451: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7452:   background-color: $mail_other_hover;
                   7453: }
1.938     bisitz   7454: */
1.494     raeburn  7455: 
1.777     tempelho 7456: table.LC_data_table tr > td.LC_browser_file,
                   7457: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7458:   background: #AAEE77;
1.389     albertel 7459: }
1.795     www      7460: 
1.777     tempelho 7461: table.LC_data_table tr > td.LC_browser_file_locked,
                   7462: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7463:   background: #FFAA99;
1.387     albertel 7464: }
1.795     www      7465: 
1.777     tempelho 7466: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7467:   background: #888888;
1.779     bisitz   7468: }
1.795     www      7469: 
1.777     tempelho 7470: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7471: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7472:   background: #F8F866;
1.777     tempelho 7473: }
1.795     www      7474: 
1.696     bisitz   7475: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7476:   background: #E0E8FF;
1.387     albertel 7477: }
1.696     bisitz   7478: 
1.707     bisitz   7479: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7480:   /* background: #77FF77; */
1.707     bisitz   7481: }
1.795     www      7482: 
1.707     bisitz   7483: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7484:   border-right: 8px solid #FFFF77;
1.707     bisitz   7485: }
1.795     www      7486: 
1.707     bisitz   7487: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7488:   border-right: 8px solid #FFAA77;
1.707     bisitz   7489: }
1.795     www      7490: 
1.707     bisitz   7491: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7492:   border-right: 8px solid #FF7777;
1.707     bisitz   7493: }
1.795     www      7494: 
1.707     bisitz   7495: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7496:   border-right: 8px solid #AAFF77;
1.707     bisitz   7497: }
1.795     www      7498: 
1.707     bisitz   7499: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7500:   border-right: 8px solid #11CC55;
1.707     bisitz   7501: }
                   7502: 
1.388     albertel 7503: span.LC_current_location {
1.701     harmsja  7504:   font-size:larger;
1.388     albertel 7505:   background: $pgbg;
                   7506: }
1.387     albertel 7507: 
1.1029    www      7508: span.LC_current_nav_location {
                   7509:   font-weight:bold;
                   7510:   background: $sidebg;
                   7511: }
                   7512: 
1.395     albertel 7513: span.LC_parm_menu_item {
                   7514:   font-size: larger;
                   7515: }
1.795     www      7516: 
1.395     albertel 7517: span.LC_parm_scope_all {
                   7518:   color: red;
                   7519: }
1.795     www      7520: 
1.395     albertel 7521: span.LC_parm_scope_folder {
                   7522:   color: green;
                   7523: }
1.795     www      7524: 
1.395     albertel 7525: span.LC_parm_scope_resource {
                   7526:   color: orange;
                   7527: }
1.795     www      7528: 
1.395     albertel 7529: span.LC_parm_part {
                   7530:   color: blue;
                   7531: }
1.795     www      7532: 
1.911     bisitz   7533: span.LC_parm_folder,
                   7534: span.LC_parm_symb {
1.395     albertel 7535:   font-size: x-small;
                   7536:   font-family: $mono;
                   7537:   color: #AAAAAA;
                   7538: }
                   7539: 
1.977     bisitz   7540: ul.LC_parm_parmlist li {
                   7541:   display: inline-block;
                   7542:   padding: 0.3em 0.8em;
                   7543:   vertical-align: top;
                   7544:   width: 150px;
                   7545:   border-top:1px solid $lg_border_color;
                   7546: }
                   7547: 
1.795     www      7548: td.LC_parm_overview_level_menu,
                   7549: td.LC_parm_overview_map_menu,
                   7550: td.LC_parm_overview_parm_selectors,
                   7551: td.LC_parm_overview_restrictions  {
1.396     albertel 7552:   border: 1px solid black;
                   7553:   border-collapse: collapse;
                   7554: }
1.795     www      7555: 
1.1285    raeburn  7556: span.LC_parm_recursive,
                   7557: td.LC_parm_recursive {
                   7558:   font-weight: bold;
                   7559:   font-size: smaller;
                   7560: }
                   7561: 
1.396     albertel 7562: table.LC_parm_overview_restrictions td {
                   7563:   border-width: 1px 4px 1px 4px;
                   7564:   border-style: solid;
                   7565:   border-color: $pgbg;
                   7566:   text-align: center;
                   7567: }
1.795     www      7568: 
1.396     albertel 7569: table.LC_parm_overview_restrictions th {
                   7570:   background: $tabbg;
                   7571:   border-width: 1px 4px 1px 4px;
                   7572:   border-style: solid;
                   7573:   border-color: $pgbg;
                   7574: }
1.795     www      7575: 
1.398     albertel 7576: table#LC_helpmenu {
1.803     bisitz   7577:   border: none;
1.398     albertel 7578:   height: 55px;
1.803     bisitz   7579:   border-spacing: 0;
1.398     albertel 7580: }
                   7581: 
                   7582: table#LC_helpmenu fieldset legend {
                   7583:   font-size: larger;
                   7584: }
1.795     www      7585: 
1.397     albertel 7586: table#LC_helpmenu_links {
                   7587:   width: 100%;
                   7588:   border: 1px solid black;
                   7589:   background: $pgbg;
1.803     bisitz   7590:   padding: 0;
1.397     albertel 7591:   border-spacing: 1px;
                   7592: }
1.795     www      7593: 
1.397     albertel 7594: table#LC_helpmenu_links tr td {
                   7595:   padding: 1px;
                   7596:   background: $tabbg;
1.399     albertel 7597:   text-align: center;
                   7598:   font-weight: bold;
1.397     albertel 7599: }
1.396     albertel 7600: 
1.795     www      7601: table#LC_helpmenu_links a:link,
                   7602: table#LC_helpmenu_links a:visited,
1.397     albertel 7603: table#LC_helpmenu_links a:active {
                   7604:   text-decoration: none;
                   7605:   color: $font;
                   7606: }
1.795     www      7607: 
1.397     albertel 7608: table#LC_helpmenu_links a:hover {
                   7609:   text-decoration: underline;
                   7610:   color: $vlink;
                   7611: }
1.396     albertel 7612: 
1.417     albertel 7613: .LC_chrt_popup_exists {
                   7614:   border: 1px solid #339933;
                   7615:   margin: -1px;
                   7616: }
1.795     www      7617: 
1.417     albertel 7618: .LC_chrt_popup_up {
                   7619:   border: 1px solid yellow;
                   7620:   margin: -1px;
                   7621: }
1.795     www      7622: 
1.417     albertel 7623: .LC_chrt_popup {
                   7624:   border: 1px solid #8888FF;
                   7625:   background: #CCCCFF;
                   7626: }
1.795     www      7627: 
1.421     albertel 7628: table.LC_pick_box {
                   7629:   border-collapse: separate;
                   7630:   background: white;
                   7631:   border: 1px solid black;
                   7632:   border-spacing: 1px;
                   7633: }
1.795     www      7634: 
1.421     albertel 7635: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7636:   background: $sidebg;
1.421     albertel 7637:   font-weight: bold;
1.900     bisitz   7638:   text-align: left;
1.740     bisitz   7639:   vertical-align: top;
1.421     albertel 7640:   width: 184px;
                   7641:   padding: 8px;
                   7642: }
1.795     www      7643: 
1.579     raeburn  7644: table.LC_pick_box td.LC_pick_box_value {
                   7645:   text-align: left;
                   7646:   padding: 8px;
                   7647: }
1.795     www      7648: 
1.579     raeburn  7649: table.LC_pick_box td.LC_pick_box_select {
                   7650:   text-align: left;
                   7651:   padding: 8px;
                   7652: }
1.795     www      7653: 
1.424     albertel 7654: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7655:   padding: 0;
1.421     albertel 7656:   height: 1px;
                   7657:   background: black;
                   7658: }
1.795     www      7659: 
1.421     albertel 7660: table.LC_pick_box td.LC_pick_box_submit {
                   7661:   text-align: right;
                   7662: }
1.795     www      7663: 
1.579     raeburn  7664: table.LC_pick_box td.LC_evenrow_value {
                   7665:   text-align: left;
                   7666:   padding: 8px;
                   7667:   background-color: $data_table_light;
                   7668: }
1.795     www      7669: 
1.579     raeburn  7670: table.LC_pick_box td.LC_oddrow_value {
                   7671:   text-align: left;
                   7672:   padding: 8px;
                   7673:   background-color: $data_table_light;
                   7674: }
1.795     www      7675: 
1.579     raeburn  7676: span.LC_helpform_receipt_cat {
                   7677:   font-weight: bold;
                   7678: }
1.795     www      7679: 
1.424     albertel 7680: table.LC_group_priv_box {
                   7681:   background: white;
                   7682:   border: 1px solid black;
                   7683:   border-spacing: 1px;
                   7684: }
1.795     www      7685: 
1.424     albertel 7686: table.LC_group_priv_box td.LC_pick_box_title {
                   7687:   background: $tabbg;
                   7688:   font-weight: bold;
                   7689:   text-align: right;
                   7690:   width: 184px;
                   7691: }
1.795     www      7692: 
1.424     albertel 7693: table.LC_group_priv_box td.LC_groups_fixed {
                   7694:   background: $data_table_light;
                   7695:   text-align: center;
                   7696: }
1.795     www      7697: 
1.424     albertel 7698: table.LC_group_priv_box td.LC_groups_optional {
                   7699:   background: $data_table_dark;
                   7700:   text-align: center;
                   7701: }
1.795     www      7702: 
1.424     albertel 7703: table.LC_group_priv_box td.LC_groups_functionality {
                   7704:   background: $data_table_darker;
                   7705:   text-align: center;
                   7706:   font-weight: bold;
                   7707: }
1.795     www      7708: 
1.424     albertel 7709: table.LC_group_priv td {
                   7710:   text-align: left;
1.803     bisitz   7711:   padding: 0;
1.424     albertel 7712: }
                   7713: 
                   7714: .LC_navbuttons {
                   7715:   margin: 2ex 0ex 2ex 0ex;
                   7716: }
1.795     www      7717: 
1.423     albertel 7718: .LC_topic_bar {
                   7719:   font-weight: bold;
                   7720:   background: $tabbg;
1.918     wenzelju 7721:   margin: 1em 0em 1em 2em;
1.805     bisitz   7722:   padding: 3px;
1.918     wenzelju 7723:   font-size: 1.2em;
1.423     albertel 7724: }
1.795     www      7725: 
1.423     albertel 7726: .LC_topic_bar span {
1.918     wenzelju 7727:   left: 0.5em;
                   7728:   position: absolute;
1.423     albertel 7729:   vertical-align: middle;
1.918     wenzelju 7730:   font-size: 1.2em;
1.423     albertel 7731: }
1.795     www      7732: 
1.423     albertel 7733: table.LC_course_group_status {
                   7734:   margin: 20px;
                   7735: }
1.795     www      7736: 
1.423     albertel 7737: table.LC_status_selector td {
                   7738:   vertical-align: top;
                   7739:   text-align: center;
1.424     albertel 7740:   padding: 4px;
                   7741: }
1.795     www      7742: 
1.599     albertel 7743: div.LC_feedback_link {
1.616     albertel 7744:   clear: both;
1.829     kalberla 7745:   background: $sidebg;
1.779     bisitz   7746:   width: 100%;
1.829     kalberla 7747:   padding-bottom: 10px;
                   7748:   border: 1px $tabbg solid;
1.833     kalberla 7749:   height: 22px;
                   7750:   line-height: 22px;
                   7751:   padding-top: 5px;
                   7752: }
                   7753: 
                   7754: div.LC_feedback_link img {
                   7755:   height: 22px;
1.867     kalberla 7756:   vertical-align:middle;
1.829     kalberla 7757: }
                   7758: 
1.911     bisitz   7759: div.LC_feedback_link a {
1.829     kalberla 7760:   text-decoration: none;
1.489     raeburn  7761: }
1.795     www      7762: 
1.867     kalberla 7763: div.LC_comblock {
1.911     bisitz   7764:   display:inline;
1.867     kalberla 7765:   color:$font;
                   7766:   font-size:90%;
                   7767: }
                   7768: 
                   7769: div.LC_feedback_link div.LC_comblock {
                   7770:   padding-left:5px;
                   7771: }
                   7772: 
                   7773: div.LC_feedback_link div.LC_comblock a {
                   7774:   color:$font;
                   7775: }
                   7776: 
1.489     raeburn  7777: span.LC_feedback_link {
1.858     bisitz   7778:   /* background: $feedback_link_bg; */
1.599     albertel 7779:   font-size: larger;
                   7780: }
1.795     www      7781: 
1.599     albertel 7782: span.LC_message_link {
1.858     bisitz   7783:   /* background: $feedback_link_bg; */
1.599     albertel 7784:   font-size: larger;
                   7785:   position: absolute;
                   7786:   right: 1em;
1.489     raeburn  7787: }
1.421     albertel 7788: 
1.515     albertel 7789: table.LC_prior_tries {
1.524     albertel 7790:   border: 1px solid #000000;
                   7791:   border-collapse: separate;
                   7792:   border-spacing: 1px;
1.515     albertel 7793: }
1.523     albertel 7794: 
1.515     albertel 7795: table.LC_prior_tries td {
1.524     albertel 7796:   padding: 2px;
1.515     albertel 7797: }
1.523     albertel 7798: 
                   7799: .LC_answer_correct {
1.795     www      7800:   background: lightgreen;
                   7801:   color: darkgreen;
                   7802:   padding: 6px;
1.523     albertel 7803: }
1.795     www      7804: 
1.523     albertel 7805: .LC_answer_charged_try {
1.797     www      7806:   background: #FFAAAA;
1.795     www      7807:   color: darkred;
                   7808:   padding: 6px;
1.523     albertel 7809: }
1.795     www      7810: 
1.779     bisitz   7811: .LC_answer_not_charged_try,
1.523     albertel 7812: .LC_answer_no_grade,
                   7813: .LC_answer_late {
1.795     www      7814:   background: lightyellow;
1.523     albertel 7815:   color: black;
1.795     www      7816:   padding: 6px;
1.523     albertel 7817: }
1.795     www      7818: 
1.523     albertel 7819: .LC_answer_previous {
1.795     www      7820:   background: lightblue;
                   7821:   color: darkblue;
                   7822:   padding: 6px;
1.523     albertel 7823: }
1.795     www      7824: 
1.779     bisitz   7825: .LC_answer_no_message {
1.777     tempelho 7826:   background: #FFFFFF;
                   7827:   color: black;
1.795     www      7828:   padding: 6px;
1.779     bisitz   7829: }
1.795     www      7830: 
1.1334    raeburn  7831: .LC_answer_unknown,
                   7832: .LC_answer_warning {
1.779     bisitz   7833:   background: orange;
                   7834:   color: black;
1.795     www      7835:   padding: 6px;
1.777     tempelho 7836: }
1.795     www      7837: 
1.529     albertel 7838: span.LC_prior_numerical,
                   7839: span.LC_prior_string,
                   7840: span.LC_prior_custom,
                   7841: span.LC_prior_reaction,
                   7842: span.LC_prior_math {
1.925     bisitz   7843:   font-family: $mono;
1.523     albertel 7844:   white-space: pre;
                   7845: }
                   7846: 
1.525     albertel 7847: span.LC_prior_string {
1.925     bisitz   7848:   font-family: $mono;
1.525     albertel 7849:   white-space: pre;
                   7850: }
                   7851: 
1.523     albertel 7852: table.LC_prior_option {
                   7853:   width: 100%;
                   7854:   border-collapse: collapse;
                   7855: }
1.795     www      7856: 
1.911     bisitz   7857: table.LC_prior_rank,
1.795     www      7858: table.LC_prior_match {
1.528     albertel 7859:   border-collapse: collapse;
                   7860: }
1.795     www      7861: 
1.528     albertel 7862: table.LC_prior_option tr td,
                   7863: table.LC_prior_rank tr td,
                   7864: table.LC_prior_match tr td {
1.524     albertel 7865:   border: 1px solid #000000;
1.515     albertel 7866: }
                   7867: 
1.855     bisitz   7868: .LC_nobreak {
1.544     albertel 7869:   white-space: nowrap;
1.519     raeburn  7870: }
                   7871: 
1.576     raeburn  7872: span.LC_cusr_emph {
                   7873:   font-style: italic;
                   7874: }
                   7875: 
1.633     raeburn  7876: span.LC_cusr_subheading {
                   7877:   font-weight: normal;
                   7878:   font-size: 85%;
                   7879: }
                   7880: 
1.861     bisitz   7881: div.LC_docs_entry_move {
1.859     bisitz   7882:   border: 1px solid #BBBBBB;
1.545     albertel 7883:   background: #DDDDDD;
1.861     bisitz   7884:   width: 22px;
1.859     bisitz   7885:   padding: 1px;
                   7886:   margin: 0;
1.545     albertel 7887: }
                   7888: 
1.861     bisitz   7889: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7890: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7891:   font-size: x-small;
                   7892: }
1.795     www      7893: 
1.861     bisitz   7894: .LC_docs_entry_parameter {
                   7895:   white-space: nowrap;
                   7896: }
                   7897: 
1.544     albertel 7898: .LC_docs_copy {
1.545     albertel 7899:   color: #000099;
1.544     albertel 7900: }
1.795     www      7901: 
1.544     albertel 7902: .LC_docs_cut {
1.545     albertel 7903:   color: #550044;
1.544     albertel 7904: }
1.795     www      7905: 
1.544     albertel 7906: .LC_docs_rename {
1.545     albertel 7907:   color: #009900;
1.544     albertel 7908: }
1.795     www      7909: 
1.544     albertel 7910: .LC_docs_remove {
1.545     albertel 7911:   color: #990000;
                   7912: }
                   7913: 
1.1284    raeburn  7914: .LC_docs_alias {
                   7915:   color: #440055;  
                   7916: }
                   7917: 
1.1286    raeburn  7918: .LC_domprefs_email,
1.1284    raeburn  7919: .LC_docs_alias_name,
1.547     albertel 7920: .LC_docs_reinit_warn,
                   7921: .LC_docs_ext_edit {
                   7922:   font-size: x-small;
                   7923: }
                   7924: 
1.545     albertel 7925: table.LC_docs_adddocs td,
                   7926: table.LC_docs_adddocs th {
                   7927:   border: 1px solid #BBBBBB;
                   7928:   padding: 4px;
                   7929:   background: #DDDDDD;
1.543     albertel 7930: }
                   7931: 
1.584     albertel 7932: table.LC_sty_begin {
                   7933:   background: #BBFFBB;
                   7934: }
1.795     www      7935: 
1.584     albertel 7936: table.LC_sty_end {
                   7937:   background: #FFBBBB;
                   7938: }
                   7939: 
1.589     raeburn  7940: table.LC_double_column {
1.803     bisitz   7941:   border-width: 0;
1.589     raeburn  7942:   border-collapse: collapse;
                   7943:   width: 100%;
                   7944:   padding: 2px;
                   7945: }
                   7946: 
                   7947: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7948:   top: 2px;
1.589     raeburn  7949:   left: 2px;
                   7950:   width: 47%;
                   7951:   vertical-align: top;
                   7952: }
                   7953: 
                   7954: table.LC_double_column tr td.LC_right_col {
                   7955:   top: 2px;
1.779     bisitz   7956:   right: 2px;
1.589     raeburn  7957:   width: 47%;
                   7958:   vertical-align: top;
                   7959: }
                   7960: 
1.591     raeburn  7961: div.LC_left_float {
                   7962:   float: left;
                   7963:   padding-right: 5%;
1.597     albertel 7964:   padding-bottom: 4px;
1.591     raeburn  7965: }
                   7966: 
                   7967: div.LC_clear_float_header {
1.597     albertel 7968:   padding-bottom: 2px;
1.591     raeburn  7969: }
                   7970: 
                   7971: div.LC_clear_float_footer {
1.597     albertel 7972:   padding-top: 10px;
1.591     raeburn  7973:   clear: both;
                   7974: }
                   7975: 
1.597     albertel 7976: div.LC_grade_show_user {
1.941     bisitz   7977: /*  border-left: 5px solid $sidebg; */
                   7978:   border-top: 5px solid #000000;
                   7979:   margin: 50px 0 0 0;
1.936     bisitz   7980:   padding: 15px 0 5px 10px;
1.597     albertel 7981: }
1.795     www      7982: 
1.936     bisitz   7983: div.LC_grade_show_user_odd_row {
1.941     bisitz   7984: /*  border-left: 5px solid #000000; */
                   7985: }
                   7986: 
                   7987: div.LC_grade_show_user div.LC_Box {
                   7988:   margin-right: 50px;
1.597     albertel 7989: }
                   7990: 
                   7991: div.LC_grade_submissions,
                   7992: div.LC_grade_message_center,
1.936     bisitz   7993: div.LC_grade_info_links {
1.597     albertel 7994:   margin: 5px;
                   7995:   width: 99%;
                   7996:   background: #FFFFFF;
                   7997: }
1.795     www      7998: 
1.597     albertel 7999: div.LC_grade_submissions_header,
1.936     bisitz   8000: div.LC_grade_message_center_header {
1.705     tempelho 8001:   font-weight: bold;
                   8002:   font-size: large;
1.597     albertel 8003: }
1.795     www      8004: 
1.597     albertel 8005: div.LC_grade_submissions_body,
1.936     bisitz   8006: div.LC_grade_message_center_body {
1.597     albertel 8007:   border: 1px solid black;
                   8008:   width: 99%;
                   8009:   background: #FFFFFF;
                   8010: }
1.795     www      8011: 
1.613     albertel 8012: table.LC_scantron_action {
                   8013:   width: 100%;
                   8014: }
1.795     www      8015: 
1.613     albertel 8016: table.LC_scantron_action tr th {
1.698     harmsja  8017:   font-weight:bold;
                   8018:   font-style:normal;
1.613     albertel 8019: }
1.795     www      8020: 
1.779     bisitz   8021: .LC_edit_problem_header,
1.614     albertel 8022: div.LC_edit_problem_footer {
1.705     tempelho 8023:   font-weight: normal;
                   8024:   font-size:  medium;
1.602     albertel 8025:   margin: 2px;
1.1060    bisitz   8026:   background-color: $sidebg;
1.600     albertel 8027: }
1.795     www      8028: 
1.600     albertel 8029: div.LC_edit_problem_header,
1.602     albertel 8030: div.LC_edit_problem_header div,
1.614     albertel 8031: div.LC_edit_problem_footer,
                   8032: div.LC_edit_problem_footer div,
1.602     albertel 8033: div.LC_edit_problem_editxml_header,
                   8034: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8035:   z-index: 100;
1.600     albertel 8036: }
1.795     www      8037: 
1.600     albertel 8038: div.LC_edit_problem_header_title {
1.705     tempelho 8039:   font-weight: bold;
                   8040:   font-size: larger;
1.602     albertel 8041:   background: $tabbg;
                   8042:   padding: 3px;
1.1060    bisitz   8043:   margin: 0 0 5px 0;
1.602     albertel 8044: }
1.795     www      8045: 
1.602     albertel 8046: table.LC_edit_problem_header_title {
                   8047:   width: 100%;
1.600     albertel 8048:   background: $tabbg;
1.602     albertel 8049: }
                   8050: 
1.1205    golterma 8051: div.LC_edit_actionbar {
                   8052:     background-color: $sidebg;
1.1218    droeschl 8053:     margin: 0;
                   8054:     padding: 0;
                   8055:     line-height: 200%;
1.602     albertel 8056: }
1.795     www      8057: 
1.1218    droeschl 8058: div.LC_edit_actionbar div{
                   8059:     padding: 0;
                   8060:     margin: 0;
                   8061:     display: inline-block;
1.600     albertel 8062: }
1.795     www      8063: 
1.1124    bisitz   8064: .LC_edit_opt {
                   8065:   padding-left: 1em;
                   8066:   white-space: nowrap;
                   8067: }
                   8068: 
1.1152    golterma 8069: .LC_edit_problem_latexhelper{
                   8070:     text-align: right;
                   8071: }
                   8072: 
                   8073: #LC_edit_problem_colorful div{
                   8074:     margin-left: 40px;
                   8075: }
                   8076: 
1.1205    golterma 8077: #LC_edit_problem_codemirror div{
                   8078:     margin-left: 0px;
                   8079: }
                   8080: 
1.911     bisitz   8081: img.stift {
1.803     bisitz   8082:   border-width: 0;
                   8083:   vertical-align: middle;
1.677     riegler  8084: }
1.680     riegler  8085: 
1.923     bisitz   8086: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8087:   vertical-align: top;
1.777     tempelho 8088: }
1.795     www      8089: 
1.716     raeburn  8090: div.LC_createcourse {
1.911     bisitz   8091:   margin: 10px 10px 10px 10px;
1.716     raeburn  8092: }
                   8093: 
1.917     raeburn  8094: .LC_dccid {
1.1130    raeburn  8095:   float: right;
1.917     raeburn  8096:   margin: 0.2em 0 0 0;
                   8097:   padding: 0;
                   8098:   font-size: 90%;
                   8099:   display:none;
                   8100: }
                   8101: 
1.897     wenzelju 8102: ol.LC_primary_menu a:hover,
1.721     harmsja  8103: ol#LC_MenuBreadcrumbs a:hover,
                   8104: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8105: ul#LC_secondary_menu a:hover,
1.721     harmsja  8106: .LC_FormSectionClearButton input:hover
1.795     www      8107: ul.LC_TabContent   li:hover a {
1.952     onken    8108:   color:$button_hover;
1.911     bisitz   8109:   text-decoration:none;
1.693     droeschl 8110: }
                   8111: 
1.779     bisitz   8112: h1 {
1.911     bisitz   8113:   padding: 0;
                   8114:   line-height:130%;
1.693     droeschl 8115: }
1.698     harmsja  8116: 
1.911     bisitz   8117: h2,
                   8118: h3,
                   8119: h4,
                   8120: h5,
                   8121: h6 {
                   8122:   margin: 5px 0 5px 0;
                   8123:   padding: 0;
                   8124:   line-height:130%;
1.693     droeschl 8125: }
1.795     www      8126: 
                   8127: .LC_hcell {
1.911     bisitz   8128:   padding:3px 15px 3px 15px;
                   8129:   margin: 0;
                   8130:   background-color:$tabbg;
                   8131:   color:$fontmenu;
                   8132:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8133: }
1.795     www      8134: 
1.840     bisitz   8135: .LC_Box > .LC_hcell {
1.911     bisitz   8136:   margin: 0 -10px 10px -10px;
1.835     bisitz   8137: }
                   8138: 
1.721     harmsja  8139: .LC_noBorder {
1.911     bisitz   8140:   border: 0;
1.698     harmsja  8141: }
1.693     droeschl 8142: 
1.721     harmsja  8143: .LC_FormSectionClearButton input {
1.911     bisitz   8144:   background-color:transparent;
                   8145:   border: none;
                   8146:   cursor:pointer;
                   8147:   text-decoration:underline;
1.693     droeschl 8148: }
1.763     bisitz   8149: 
                   8150: .LC_help_open_topic {
1.911     bisitz   8151:   color: #FFFFFF;
                   8152:   background-color: #EEEEFF;
                   8153:   margin: 1px;
                   8154:   padding: 4px;
                   8155:   border: 1px solid #000033;
                   8156:   white-space: nowrap;
                   8157:   /* vertical-align: middle; */
1.759     neumanie 8158: }
1.693     droeschl 8159: 
1.911     bisitz   8160: dl,
                   8161: ul,
                   8162: div,
                   8163: fieldset {
                   8164:   margin: 10px 10px 10px 0;
                   8165:   /* overflow: hidden; */
1.693     droeschl 8166: }
1.795     www      8167: 
1.1404    raeburn  8168: fieldset#LC_selectuser {
                   8169:     margin: 0;
                   8170:     padding: 0;
                   8171: }
                   8172: 
1.1211    raeburn  8173: article.geogebraweb div {
                   8174:     margin: 0;
                   8175: }
                   8176: 
1.838     bisitz   8177: fieldset > legend {
1.911     bisitz   8178:   font-weight: bold;
                   8179:   padding: 0 5px 0 5px;
1.838     bisitz   8180: }
                   8181: 
1.813     bisitz   8182: #LC_nav_bar {
1.911     bisitz   8183:   float: left;
1.995     raeburn  8184:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8185:   margin: 0 0 2px 0;
1.807     droeschl 8186: }
                   8187: 
1.916     droeschl 8188: #LC_realm {
                   8189:   margin: 0.2em 0 0 0;
                   8190:   padding: 0;
                   8191:   font-weight: bold;
                   8192:   text-align: center;
1.995     raeburn  8193:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8194: }
                   8195: 
1.911     bisitz   8196: #LC_nav_bar em {
                   8197:   font-weight: bold;
                   8198:   font-style: normal;
1.807     droeschl 8199: }
                   8200: 
1.897     wenzelju 8201: ol.LC_primary_menu {
1.934     droeschl 8202:   margin: 0;
1.1076    raeburn  8203:   padding: 0;
1.807     droeschl 8204: }
                   8205: 
1.852     droeschl 8206: ol#LC_PathBreadcrumbs {
1.911     bisitz   8207:   margin: 0;
1.693     droeschl 8208: }
                   8209: 
1.897     wenzelju 8210: ol.LC_primary_menu li {
1.1076    raeburn  8211:   color: RGB(80, 80, 80);
                   8212:   vertical-align: middle;
                   8213:   text-align: left;
                   8214:   list-style: none;
1.1205    golterma 8215:   position: relative;
1.1076    raeburn  8216:   float: left;
1.1205    golterma 8217:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8218:   line-height: 1.5em;
1.1076    raeburn  8219: }
                   8220: 
1.1205    golterma 8221: ol.LC_primary_menu li a,
                   8222: ol.LC_primary_menu li p {
1.1076    raeburn  8223:   display: block;
                   8224:   margin: 0;
                   8225:   padding: 0 5px 0 10px;
                   8226:   text-decoration: none;
                   8227: }
                   8228: 
1.1205    golterma 8229: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8230:   display: inline-block;
                   8231:   width: 95%;
                   8232:   text-align: left;
                   8233: }
                   8234: 
                   8235: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8236:   display: inline-block;	
                   8237:   width: 5%;
                   8238:   float: right;
                   8239:   text-align: right;
                   8240:   font-size: 70%;
                   8241: }
                   8242: 
                   8243: ol.LC_primary_menu ul {
1.1076    raeburn  8244:   display: none;
1.1205    golterma 8245:   width: 15em;
1.1076    raeburn  8246:   background-color: $data_table_light;
1.1205    golterma 8247:   position: absolute;
                   8248:   top: 100%;
1.1076    raeburn  8249: }
                   8250: 
1.1205    golterma 8251: ol.LC_primary_menu ul ul {
                   8252:   left: 100%;
                   8253:   top: 0;
                   8254: }
                   8255: 
                   8256: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8257:   display: block;
                   8258:   position: absolute;
                   8259:   margin: 0;
                   8260:   padding: 0;
1.1078    raeburn  8261:   z-index: 2;
1.1076    raeburn  8262: }
                   8263: 
                   8264: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8265: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8266:   font-size: 90%;
1.911     bisitz   8267:   vertical-align: top;
1.1076    raeburn  8268:   float: none;
1.1079    raeburn  8269:   border-left: 1px solid black;
                   8270:   border-right: 1px solid black;
1.1205    golterma 8271: /* A dark bottom border to visualize different menu options; 
                   8272: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8273:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8274: }
                   8275: 
1.1205    golterma 8276: ol.LC_primary_menu li li p:hover {
                   8277:   color:$button_hover;
                   8278:   text-decoration:none;
                   8279:   background-color:$data_table_dark;
1.1076    raeburn  8280: }
                   8281: 
                   8282: ol.LC_primary_menu li li a:hover {
                   8283:    color:$button_hover;
                   8284:    background-color:$data_table_dark;
1.693     droeschl 8285: }
                   8286: 
1.1205    golterma 8287: /* Font-size equal to the size of the predecessors*/
                   8288: ol.LC_primary_menu li:hover li li {
                   8289:   font-size: 100%;
                   8290: }
                   8291: 
1.897     wenzelju 8292: ol.LC_primary_menu li img {
1.911     bisitz   8293:   vertical-align: bottom;
1.934     droeschl 8294:   height: 1.1em;
1.1077    raeburn  8295:   margin: 0.2em 0 0 0;
1.693     droeschl 8296: }
                   8297: 
1.897     wenzelju 8298: ol.LC_primary_menu a {
1.911     bisitz   8299:   color: RGB(80, 80, 80);
                   8300:   text-decoration: none;
1.693     droeschl 8301: }
1.795     www      8302: 
1.949     droeschl 8303: ol.LC_primary_menu a.LC_new_message {
                   8304:   font-weight:bold;
                   8305:   color: darkred;
                   8306: }
                   8307: 
1.975     raeburn  8308: ol.LC_docs_parameters {
                   8309:   margin-left: 0;
                   8310:   padding: 0;
                   8311:   list-style: none;
                   8312: }
                   8313: 
                   8314: ol.LC_docs_parameters li {
                   8315:   margin: 0;
                   8316:   padding-right: 20px;
                   8317:   display: inline;
                   8318: }
                   8319: 
1.976     raeburn  8320: ol.LC_docs_parameters li:before {
                   8321:   content: "\\002022 \\0020";
                   8322: }
                   8323: 
                   8324: li.LC_docs_parameters_title {
                   8325:   font-weight: bold;
                   8326: }
                   8327: 
                   8328: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8329:   content: "";
                   8330: }
                   8331: 
1.897     wenzelju 8332: ul#LC_secondary_menu {
1.1107    raeburn  8333:   clear: right;
1.911     bisitz   8334:   color: $fontmenu;
                   8335:   background: $tabbg;
                   8336:   list-style: none;
                   8337:   padding: 0;
                   8338:   margin: 0;
                   8339:   width: 100%;
1.995     raeburn  8340:   text-align: left;
1.1107    raeburn  8341:   float: left;
1.808     droeschl 8342: }
                   8343: 
1.897     wenzelju 8344: ul#LC_secondary_menu li {
1.911     bisitz   8345:   font-weight: bold;
                   8346:   line-height: 1.8em;
1.1107    raeburn  8347:   border-right: 1px solid black;
                   8348:   float: left;
                   8349: }
                   8350: 
                   8351: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8352:   background-color: $data_table_light;
                   8353: }
                   8354: 
                   8355: ul#LC_secondary_menu li a {
1.911     bisitz   8356:   padding: 0 0.8em;
1.1107    raeburn  8357: }
                   8358: 
                   8359: ul#LC_secondary_menu li ul {
                   8360:   display: none;
                   8361: }
                   8362: 
                   8363: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8364:   display: block;
                   8365:   position: absolute;
                   8366:   margin: 0;
                   8367:   padding: 0;
                   8368:   list-style:none;
                   8369:   float: none;
                   8370:   background-color: $data_table_light;
                   8371:   z-index: 2;
                   8372:   margin-left: -1px;
                   8373: }
                   8374: 
                   8375: ul#LC_secondary_menu li ul li {
                   8376:   font-size: 90%;
                   8377:   vertical-align: top;
                   8378:   border-left: 1px solid black;
1.911     bisitz   8379:   border-right: 1px solid black;
1.1119    raeburn  8380:   background-color: $data_table_light;
1.1107    raeburn  8381:   list-style:none;
                   8382:   float: none;
                   8383: }
                   8384: 
                   8385: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8386:   background-color: $data_table_dark;
1.807     droeschl 8387: }
                   8388: 
1.847     tempelho 8389: ul.LC_TabContent {
1.911     bisitz   8390:   display:block;
                   8391:   background: $sidebg;
                   8392:   border-bottom: solid 1px $lg_border_color;
                   8393:   list-style:none;
1.1020    raeburn  8394:   margin: -1px -10px 0 -10px;
1.911     bisitz   8395:   padding: 0;
1.693     droeschl 8396: }
                   8397: 
1.795     www      8398: ul.LC_TabContent li,
                   8399: ul.LC_TabContentBigger li {
1.911     bisitz   8400:   float:left;
1.741     harmsja  8401: }
1.795     www      8402: 
1.897     wenzelju 8403: ul#LC_secondary_menu li a {
1.911     bisitz   8404:   color: $fontmenu;
                   8405:   text-decoration: none;
1.693     droeschl 8406: }
1.795     www      8407: 
1.721     harmsja  8408: ul.LC_TabContent {
1.952     onken    8409:   min-height:20px;
1.721     harmsja  8410: }
1.795     www      8411: 
                   8412: ul.LC_TabContent li {
1.911     bisitz   8413:   vertical-align:middle;
1.959     onken    8414:   padding: 0 16px 0 10px;
1.911     bisitz   8415:   background-color:$tabbg;
                   8416:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8417:   border-left: solid 1px $font;
1.721     harmsja  8418: }
1.795     www      8419: 
1.847     tempelho 8420: ul.LC_TabContent .right {
1.911     bisitz   8421:   float:right;
1.847     tempelho 8422: }
                   8423: 
1.911     bisitz   8424: ul.LC_TabContent li a,
                   8425: ul.LC_TabContent li {
                   8426:   color:rgb(47,47,47);
                   8427:   text-decoration:none;
                   8428:   font-size:95%;
                   8429:   font-weight:bold;
1.952     onken    8430:   min-height:20px;
                   8431: }
                   8432: 
1.959     onken    8433: ul.LC_TabContent li a:hover,
                   8434: ul.LC_TabContent li a:focus {
1.952     onken    8435:   color: $button_hover;
1.959     onken    8436:   background:none;
                   8437:   outline:none;
1.952     onken    8438: }
                   8439: 
                   8440: ul.LC_TabContent li:hover {
                   8441:   color: $button_hover;
                   8442:   cursor:pointer;
1.721     harmsja  8443: }
1.795     www      8444: 
1.911     bisitz   8445: ul.LC_TabContent li.active {
1.952     onken    8446:   color: $font;
1.911     bisitz   8447:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8448:   border-bottom:solid 1px #FFFFFF;
                   8449:   cursor: default;
1.744     ehlerst  8450: }
1.795     www      8451: 
1.959     onken    8452: ul.LC_TabContent li.active a {
                   8453:   color:$font;
                   8454:   background:#FFFFFF;
                   8455:   outline: none;
                   8456: }
1.1047    raeburn  8457: 
                   8458: ul.LC_TabContent li.goback {
                   8459:   float: left;
                   8460:   border-left: none;
                   8461: }
                   8462: 
1.870     tempelho 8463: #maincoursedoc {
1.911     bisitz   8464:   clear:both;
1.870     tempelho 8465: }
                   8466: 
                   8467: ul.LC_TabContentBigger {
1.911     bisitz   8468:   display:block;
                   8469:   list-style:none;
                   8470:   padding: 0;
1.870     tempelho 8471: }
                   8472: 
1.795     www      8473: ul.LC_TabContentBigger li {
1.911     bisitz   8474:   vertical-align:bottom;
                   8475:   height: 30px;
                   8476:   font-size:110%;
                   8477:   font-weight:bold;
                   8478:   color: #737373;
1.841     tempelho 8479: }
                   8480: 
1.957     onken    8481: ul.LC_TabContentBigger li.active {
                   8482:   position: relative;
                   8483:   top: 1px;
                   8484: }
                   8485: 
1.870     tempelho 8486: ul.LC_TabContentBigger li a {
1.911     bisitz   8487:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8488:   height: 30px;
                   8489:   line-height: 30px;
                   8490:   text-align: center;
                   8491:   display: block;
                   8492:   text-decoration: none;
1.958     onken    8493:   outline: none;  
1.741     harmsja  8494: }
1.795     www      8495: 
1.870     tempelho 8496: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8497:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8498:   color:$font;
1.744     ehlerst  8499: }
1.795     www      8500: 
1.870     tempelho 8501: ul.LC_TabContentBigger li b {
1.911     bisitz   8502:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8503:   display: block;
                   8504:   float: left;
                   8505:   padding: 0 30px;
1.957     onken    8506:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8507: }
                   8508: 
1.956     onken    8509: ul.LC_TabContentBigger li:hover b {
                   8510:   color:$button_hover;
                   8511: }
                   8512: 
1.870     tempelho 8513: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8514:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8515:   color:$font;
1.957     onken    8516:   border: 0;
1.741     harmsja  8517: }
1.693     droeschl 8518: 
1.870     tempelho 8519: 
1.862     bisitz   8520: ul.LC_CourseBreadcrumbs {
                   8521:   background: $sidebg;
1.1020    raeburn  8522:   height: 2em;
1.862     bisitz   8523:   padding-left: 10px;
1.1020    raeburn  8524:   margin: 0;
1.862     bisitz   8525:   list-style-position: inside;
                   8526: }
                   8527: 
1.911     bisitz   8528: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8529: ol#LC_PathBreadcrumbs {
1.911     bisitz   8530:   padding-left: 10px;
                   8531:   margin: 0;
1.933     droeschl 8532:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8533: }
                   8534: 
1.911     bisitz   8535: ol#LC_MenuBreadcrumbs li,
                   8536: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8537: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8538:   display: inline;
1.933     droeschl 8539:   white-space: normal;  
1.693     droeschl 8540: }
                   8541: 
1.823     bisitz   8542: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8543: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8544:   text-decoration: none;
                   8545:   font-size:90%;
1.693     droeschl 8546: }
1.795     www      8547: 
1.969     droeschl 8548: ol#LC_MenuBreadcrumbs h1 {
                   8549:   display: inline;
                   8550:   font-size: 90%;
                   8551:   line-height: 2.5em;
                   8552:   margin: 0;
                   8553:   padding: 0;
                   8554: }
                   8555: 
1.795     www      8556: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8557:   text-decoration:none;
                   8558:   font-size:100%;
                   8559:   font-weight:bold;
1.693     droeschl 8560: }
1.795     www      8561: 
1.840     bisitz   8562: .LC_Box {
1.911     bisitz   8563:   border: solid 1px $lg_border_color;
                   8564:   padding: 0 10px 10px 10px;
1.746     neumanie 8565: }
1.795     www      8566: 
1.1020    raeburn  8567: .LC_DocsBox {
                   8568:   border: solid 1px $lg_border_color;
                   8569:   padding: 0 0 10px 10px;
                   8570: }
                   8571: 
1.795     www      8572: .LC_AboutMe_Image {
1.911     bisitz   8573:   float:left;
                   8574:   margin-right:10px;
1.747     neumanie 8575: }
1.795     www      8576: 
                   8577: .LC_Clear_AboutMe_Image {
1.911     bisitz   8578:   clear:left;
1.747     neumanie 8579: }
1.795     www      8580: 
1.721     harmsja  8581: dl.LC_ListStyleClean dt {
1.911     bisitz   8582:   padding-right: 5px;
                   8583:   display: table-header-group;
1.693     droeschl 8584: }
                   8585: 
1.721     harmsja  8586: dl.LC_ListStyleClean dd {
1.911     bisitz   8587:   display: table-row;
1.693     droeschl 8588: }
                   8589: 
1.721     harmsja  8590: .LC_ListStyleClean,
                   8591: .LC_ListStyleSimple,
                   8592: .LC_ListStyleNormal,
1.795     www      8593: .LC_ListStyleSpecial {
1.911     bisitz   8594:   /* display:block; */
                   8595:   list-style-position: inside;
                   8596:   list-style-type: none;
                   8597:   overflow: hidden;
                   8598:   padding: 0;
1.693     droeschl 8599: }
                   8600: 
1.721     harmsja  8601: .LC_ListStyleSimple li,
                   8602: .LC_ListStyleSimple dd,
                   8603: .LC_ListStyleNormal li,
                   8604: .LC_ListStyleNormal dd,
                   8605: .LC_ListStyleSpecial li,
1.795     www      8606: .LC_ListStyleSpecial dd {
1.911     bisitz   8607:   margin: 0;
                   8608:   padding: 5px 5px 5px 10px;
                   8609:   clear: both;
1.693     droeschl 8610: }
                   8611: 
1.721     harmsja  8612: .LC_ListStyleClean li,
                   8613: .LC_ListStyleClean dd {
1.911     bisitz   8614:   padding-top: 0;
                   8615:   padding-bottom: 0;
1.693     droeschl 8616: }
                   8617: 
1.721     harmsja  8618: .LC_ListStyleSimple dd,
1.795     www      8619: .LC_ListStyleSimple li {
1.911     bisitz   8620:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8621: }
                   8622: 
1.721     harmsja  8623: .LC_ListStyleSpecial li,
                   8624: .LC_ListStyleSpecial dd {
1.911     bisitz   8625:   list-style-type: none;
                   8626:   background-color: RGB(220, 220, 220);
                   8627:   margin-bottom: 4px;
1.693     droeschl 8628: }
                   8629: 
1.721     harmsja  8630: table.LC_SimpleTable {
1.911     bisitz   8631:   margin:5px;
                   8632:   border:solid 1px $lg_border_color;
1.795     www      8633: }
1.693     droeschl 8634: 
1.721     harmsja  8635: table.LC_SimpleTable tr {
1.911     bisitz   8636:   padding: 0;
                   8637:   border:solid 1px $lg_border_color;
1.693     droeschl 8638: }
1.795     www      8639: 
                   8640: table.LC_SimpleTable thead {
1.911     bisitz   8641:   background:rgb(220,220,220);
1.693     droeschl 8642: }
                   8643: 
1.721     harmsja  8644: div.LC_columnSection {
1.911     bisitz   8645:   display: block;
                   8646:   clear: both;
                   8647:   overflow: hidden;
                   8648:   margin: 0;
1.693     droeschl 8649: }
                   8650: 
1.721     harmsja  8651: div.LC_columnSection>* {
1.911     bisitz   8652:   float: left;
                   8653:   margin: 10px 20px 10px 0;
                   8654:   overflow:hidden;
1.693     droeschl 8655: }
1.721     harmsja  8656: 
1.795     www      8657: table em {
1.911     bisitz   8658:   font-weight: bold;
                   8659:   font-style: normal;
1.748     schulted 8660: }
1.795     www      8661: 
1.779     bisitz   8662: table.LC_tableBrowseRes,
1.795     www      8663: table.LC_tableOfContent {
1.911     bisitz   8664:   border:none;
                   8665:   border-spacing: 1px;
                   8666:   padding: 3px;
                   8667:   background-color: #FFFFFF;
                   8668:   font-size: 90%;
1.753     droeschl 8669: }
1.789     droeschl 8670: 
1.911     bisitz   8671: table.LC_tableOfContent {
                   8672:   border-collapse: collapse;
1.789     droeschl 8673: }
                   8674: 
1.771     droeschl 8675: table.LC_tableBrowseRes a,
1.768     schulted 8676: table.LC_tableOfContent a {
1.911     bisitz   8677:   background-color: transparent;
                   8678:   text-decoration: none;
1.753     droeschl 8679: }
                   8680: 
1.795     www      8681: table.LC_tableOfContent img {
1.911     bisitz   8682:   border: none;
                   8683:   height: 1.3em;
                   8684:   vertical-align: text-bottom;
                   8685:   margin-right: 0.3em;
1.753     droeschl 8686: }
1.757     schulted 8687: 
1.795     www      8688: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8689:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8690: }
                   8691: 
1.795     www      8692: a#LC_content_toolbar_everything {
1.911     bisitz   8693:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8694: }
                   8695: 
1.795     www      8696: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8697:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8698: }
                   8699: 
1.795     www      8700: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8701:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8702: }
                   8703: 
1.795     www      8704: a#LC_content_toolbar_changefolder {
1.911     bisitz   8705:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8706: }
                   8707: 
1.795     www      8708: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8709:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8710: }
                   8711: 
1.1043    raeburn  8712: a#LC_content_toolbar_edittoplevel {
                   8713:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8714: }
                   8715: 
1.1384    raeburn  8716: a#LC_content_toolbar_printout {
                   8717:   background-image:url(/res/adm/pages/printout.gif);
                   8718: }
                   8719: 
1.795     www      8720: ul#LC_toolbar li a:hover {
1.911     bisitz   8721:   background-position: bottom center;
1.757     schulted 8722: }
                   8723: 
1.795     www      8724: ul#LC_toolbar {
1.911     bisitz   8725:   padding: 0;
                   8726:   margin: 2px;
                   8727:   list-style:none;
                   8728:   position:relative;
                   8729:   background-color:white;
1.1082    raeburn  8730:   overflow: auto;
1.757     schulted 8731: }
                   8732: 
1.795     www      8733: ul#LC_toolbar li {
1.911     bisitz   8734:   border:1px solid white;
                   8735:   padding: 0;
                   8736:   margin: 0;
                   8737:   float: left;
                   8738:   display:inline;
                   8739:   vertical-align:middle;
1.1082    raeburn  8740:   white-space: nowrap;
1.911     bisitz   8741: }
1.757     schulted 8742: 
1.783     amueller 8743: 
1.795     www      8744: a.LC_toolbarItem {
1.911     bisitz   8745:   display:block;
                   8746:   padding: 0;
                   8747:   margin: 0;
                   8748:   height: 32px;
                   8749:   width: 32px;
                   8750:   color:white;
                   8751:   border: none;
                   8752:   background-repeat:no-repeat;
                   8753:   background-color:transparent;
1.757     schulted 8754: }
                   8755: 
1.915     droeschl 8756: ul.LC_funclist {
                   8757:     margin: 0;
                   8758:     padding: 0.5em 1em 0.5em 0;
                   8759: }
                   8760: 
1.933     droeschl 8761: ul.LC_funclist > li:first-child {
                   8762:     font-weight:bold; 
                   8763:     margin-left:0.8em;
                   8764: }
                   8765: 
1.915     droeschl 8766: ul.LC_funclist + ul.LC_funclist {
                   8767:     /* 
                   8768:        left border as a seperator if we have more than
                   8769:        one list 
                   8770:     */
                   8771:     border-left: 1px solid $sidebg;
                   8772:     /* 
                   8773:        this hides the left border behind the border of the 
                   8774:        outer box if element is wrapped to the next 'line' 
                   8775:     */
                   8776:     margin-left: -1px;
                   8777: }
                   8778: 
1.843     bisitz   8779: ul.LC_funclist li {
1.915     droeschl 8780:   display: inline;
1.782     bisitz   8781:   white-space: nowrap;
1.915     droeschl 8782:   margin: 0 0 0 25px;
                   8783:   line-height: 150%;
1.782     bisitz   8784: }
                   8785: 
1.974     wenzelju 8786: .LC_hidden {
                   8787:   display: none;
                   8788: }
                   8789: 
1.1030    www      8790: .LCmodal-overlay {
                   8791: 		position:fixed;
                   8792: 		top:0;
                   8793: 		right:0;
                   8794: 		bottom:0;
                   8795: 		left:0;
                   8796: 		height:100%;
                   8797: 		width:100%;
                   8798: 		margin:0;
                   8799: 		padding:0;
                   8800: 		background:#999;
                   8801: 		opacity:.75;
                   8802: 		filter: alpha(opacity=75);
                   8803: 		-moz-opacity: 0.75;
                   8804: 		z-index:101;
                   8805: }
                   8806: 
                   8807: * html .LCmodal-overlay {   
                   8808: 		position: absolute;
                   8809: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8810: }
                   8811: 
                   8812: .LCmodal-window {
                   8813: 		position:fixed;
                   8814: 		top:50%;
                   8815: 		left:50%;
                   8816: 		margin:0;
                   8817: 		padding:0;
                   8818: 		z-index:102;
                   8819: 	}
                   8820: 
                   8821: * html .LCmodal-window {
                   8822: 		position:absolute;
                   8823: }
                   8824: 
                   8825: .LCclose-window {
                   8826: 		position:absolute;
                   8827: 		width:32px;
                   8828: 		height:32px;
                   8829: 		right:8px;
                   8830: 		top:8px;
                   8831: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8832: 		text-indent:-99999px;
                   8833: 		overflow:hidden;
                   8834: 		cursor:pointer;
                   8835: }
                   8836: 
1.1369    raeburn  8837: .LCisDisabled {
                   8838:   cursor: not-allowed;
                   8839:   opacity: 0.5;
                   8840: }
                   8841: 
                   8842: a[aria-disabled="true"] {
                   8843:   color: currentColor;
                   8844:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8845:   pointer-events: none;
                   8846:   text-decoration: none;
                   8847: }
                   8848: 
1.1335    raeburn  8849: pre.LC_wordwrap {
                   8850:   white-space: pre-wrap;
                   8851:   white-space: -moz-pre-wrap;
                   8852:   white-space: -pre-wrap;
                   8853:   white-space: -o-pre-wrap;
                   8854:   word-wrap: break-word;
                   8855: }
                   8856: 
1.1100    raeburn  8857: /*
1.1231    damieng  8858:   styles used for response display
                   8859: */
                   8860: div.LC_radiofoil, div.LC_rankfoil {
                   8861:   margin: .5em 0em .5em 0em;
                   8862: }
                   8863: table.LC_itemgroup {
                   8864:   margin-top: 1em;
                   8865: }
                   8866: 
                   8867: /*
1.1100    raeburn  8868:   styles used by TTH when "Default set of options to pass to tth/m
                   8869:   when converting TeX" in course settings has been set
                   8870: 
                   8871:   option passed: -t
                   8872: 
                   8873: */
                   8874: 
                   8875: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8876: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8877: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8878: td div.norm {line-height:normal;}
                   8879: 
                   8880: /*
                   8881:   option passed -y3
                   8882: */
                   8883: 
                   8884: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8885: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8886: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8887: 
1.1230    damieng  8888: /*
                   8889:   sections with roles, for content only
                   8890: */
                   8891: section[class^="role-"] {
                   8892:   padding-left: 10px;
                   8893:   padding-right: 5px;
                   8894:   margin-top: 8px;
                   8895:   margin-bottom: 8px;
                   8896:   border: 1px solid #2A4;
                   8897:   border-radius: 5px;
                   8898:   box-shadow: 0px 1px 1px #BBB;
                   8899: }
                   8900: section[class^="role-"]>h1 {
                   8901:   position: relative;
                   8902:   margin: 0px;
                   8903:   padding-top: 10px;
                   8904:   padding-left: 40px;
                   8905: }
                   8906: section[class^="role-"]>h1:before {
                   8907:   position: absolute;
                   8908:   left: -5px;
                   8909:   top: 5px;
                   8910: }
                   8911: section.role-activity>h1:before {
                   8912:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8913: }
                   8914: section.role-advice>h1:before {
                   8915:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8916: }
                   8917: section.role-bibliography>h1:before {
                   8918:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8919: }
                   8920: section.role-citation>h1:before {
                   8921:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8922: }
                   8923: section.role-conclusion>h1:before {
                   8924:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8925: }
                   8926: section.role-definition>h1:before {
                   8927:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8928: }
                   8929: section.role-demonstration>h1:before {
                   8930:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8931: }
                   8932: section.role-example>h1:before {
                   8933:   content:url('/adm/daxe/images/section_icons/example.png');
                   8934: }
                   8935: section.role-explanation>h1:before {
                   8936:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8937: }
                   8938: section.role-introduction>h1:before {
                   8939:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8940: }
                   8941: section.role-method>h1:before {
                   8942:   content:url('/adm/daxe/images/section_icons/method.png');
                   8943: }
                   8944: section.role-more_information>h1:before {
                   8945:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8946: }
                   8947: section.role-objectives>h1:before {
                   8948:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8949: }
                   8950: section.role-prerequisites>h1:before {
                   8951:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8952: }
                   8953: section.role-remark>h1:before {
                   8954:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8955: }
                   8956: section.role-reminder>h1:before {
                   8957:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8958: }
                   8959: section.role-summary>h1:before {
                   8960:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8961: }
                   8962: section.role-syntax>h1:before {
                   8963:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8964: }
                   8965: section.role-warning>h1:before {
                   8966:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8967: }
                   8968: 
1.1269    raeburn  8969: #LC_minitab_header {
                   8970:   float:left;
                   8971:   width:100%;
                   8972:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8973:   font-size:93%;
                   8974:   line-height:normal;
                   8975:   margin: 0.5em 0 0.5em 0;
                   8976: }
                   8977: #LC_minitab_header ul {
                   8978:   margin:0;
                   8979:   padding:10px 10px 0;
                   8980:   list-style:none;
                   8981: }
                   8982: #LC_minitab_header li {
                   8983:   float:left;
                   8984:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8985:   margin:0;
                   8986:   padding:0 0 0 9px;
                   8987: }
                   8988: #LC_minitab_header a {
                   8989:   display:block;
                   8990:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8991:   padding:5px 15px 4px 6px;
                   8992: }
                   8993: #LC_minitab_header #LC_current_minitab {
                   8994:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8995: }
                   8996: #LC_minitab_header #LC_current_minitab a {
                   8997:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8998:   padding-bottom:5px;
                   8999: }
                   9000: 
                   9001: 
1.343     albertel 9002: END
                   9003: }
                   9004: 
1.306     albertel 9005: =pod
                   9006: 
                   9007: =item * &headtag()
                   9008: 
                   9009: Returns a uniform footer for LON-CAPA web pages.
                   9010: 
1.307     albertel 9011: Inputs: $title - optional title for the head
                   9012:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9013:         $args - optional arguments
1.319     albertel 9014:             force_register - if is true call registerurl so the remote is 
                   9015:                              informed
1.415     albertel 9016:             redirect       -> array ref of
                   9017:                                    1- seconds before redirect occurs
                   9018:                                    2- url to redirect to
                   9019:                                    3- whether the side effect should occur
1.315     albertel 9020:                            (side effect of setting 
                   9021:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9022:                                redirected to)
                   9023:                                    4- whether the redirect target should be
                   9024:                                       the opener of the current (pop-up)
                   9025:                                       window (side effect of setting
                   9026:                                       $env{'internal.head.to_opener'} to
                   9027:                                       1, if true.
1.1388    raeburn  9028:                                    5- whether encrypt check should be skipped
1.352     albertel 9029:             domain         -> force to color decorate a page for a specific
                   9030:                                domain
                   9031:             function       -> force usage of a specific rolish color scheme
                   9032:             bgcolor        -> override the default page bgcolor
1.460     albertel 9033:             no_auto_mt_title
                   9034:                            -> prevent &mt()ing the title arg
1.464     albertel 9035: 
1.306     albertel 9036: =cut
                   9037: 
                   9038: sub headtag {
1.313     albertel 9039:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9040:     
1.363     albertel 9041:     my $function = $args->{'function'} || &get_users_function();
                   9042:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9043:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9044:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9045:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9046: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9047: 		   #time(),
1.418     albertel 9048: 		   $env{'environment.color.timestamp'},
1.363     albertel 9049: 		   $function,$domain,$bgcolor);
                   9050: 
1.369     www      9051:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9052: 
1.308     albertel 9053:     my $result =
                   9054: 	'<head>'.
1.1160    raeburn  9055: 	&font_settings($args);
1.319     albertel 9056: 
1.1188    raeburn  9057:     my $inhibitprint;
                   9058:     if ($args->{'print_suppress'}) {
                   9059:         $inhibitprint = &print_suppression();
                   9060:     }
1.1064    raeburn  9061: 
1.461     albertel 9062:     if (!$args->{'frameset'}) {
                   9063: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9064:     }
1.962     droeschl 9065:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9066:         $result .= Apache::lonxml::display_title();
1.319     albertel 9067:     }
1.436     albertel 9068:     if (!$args->{'no_nav_bar'} 
                   9069: 	&& !$args->{'only_body'}
                   9070: 	&& !$args->{'frameset'}) {
1.1154    raeburn  9071: 	$result .= &help_menu_js($httphost);
1.1032    www      9072:         $result.=&modal_window();
1.1038    www      9073:         $result.=&togglebox_script();
1.1034    www      9074:         $result.=&wishlist_window();
1.1041    www      9075:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9076:     } else {
                   9077:         if ($args->{'add_modal'}) {
                   9078:            $result.=&modal_window();
                   9079:         }
                   9080:         if ($args->{'add_wishlist'}) {
                   9081:            $result.=&wishlist_window();
                   9082:         }
1.1038    www      9083:         if ($args->{'add_togglebox'}) {
                   9084:            $result.=&togglebox_script();
                   9085:         }
1.1041    www      9086:         if ($args->{'add_progressbar'}) {
                   9087:            $result.=&LCprogressbarUpdate_script();
                   9088:         }
1.436     albertel 9089:     }
1.314     albertel 9090:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9091: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9092:         if (!$skip_enc_check) {
                   9093:             $url = &Apache::lonenc::check_encrypt($url);
                   9094:         }
1.414     albertel 9095: 	if (!$inhibit_continue) {
                   9096: 	    $env{'internal.head.redirect'} = $url;
                   9097: 	}
1.1386    raeburn  9098: 	$result.=<<"ADDMETA";
1.313     albertel 9099: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9100: ADDMETA
                   9101:         if ($to_opener) {
                   9102:             $env{'internal.head.to_opener'} = 1;
                   9103:             my $dest = &js_escape($url);
                   9104:             my $timeout = int($time * 1000);
                   9105:             $result .=<<"ENDJS";
                   9106: <script type="text/javascript">
                   9107: // <![CDATA[
                   9108: function LC_To_Opener() {
                   9109:     var dest = '$dest';
                   9110:     if (dest != '') {
                   9111:         if (window.opener != null && !window.opener.closed) {
                   9112:             window.opener.location.href=dest;
                   9113:             window.close();
                   9114:         } else {
                   9115:             window.location.href=dest;
                   9116:         }
                   9117:     }
                   9118: }
                   9119: \$(document).ready(function () {
                   9120:     setTimeout('LC_To_Opener()',$timeout);
                   9121: });
                   9122: // ]]>
                   9123: </script>
                   9124: ENDJS
                   9125:         } else {
                   9126:             $result.=<<"ADDMETA";
1.344     albertel 9127: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9128: ADDMETA
1.1386    raeburn  9129:         }
1.1210    raeburn  9130:     } else {
                   9131:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9132:             my $requrl = $env{'request.uri'};
                   9133:             if ($requrl eq '') {
                   9134:                 $requrl = $ENV{'REQUEST_URI'};
                   9135:                 $requrl =~ s/\?.+$//;
                   9136:             }
                   9137:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9138:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9139:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9140:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9141:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9142:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9143:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9144:                     my ($offload,$offloadoth);
1.1210    raeburn  9145:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9146:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9147:                             $offload = 1;
1.1353    raeburn  9148:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9149:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9150:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9151:                                     $offloadoth = 1;
                   9152:                                     $dom_in_use = $env{'user.domain'};
                   9153:                                 }
                   9154:                             }
1.1340    raeburn  9155:                         }
                   9156:                     }
                   9157:                     unless ($offload) {
                   9158:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9159:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9160:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9161:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9162:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9163:                                         $offload = 1;
1.1352    raeburn  9164:                                         $offloadoth = 1;
1.1340    raeburn  9165:                                         $dom_in_use = $env{'user.domain'};
                   9166:                                     }
1.1210    raeburn  9167:                                 }
1.1340    raeburn  9168:                             }
                   9169:                         }
                   9170:                     }
                   9171:                     if ($offload) {
1.1358    raeburn  9172:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9173:                         if (($newserver eq '') && ($offloadoth)) {
                   9174:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9175:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9176:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9177:                             }
                   9178:                         }
1.1340    raeburn  9179:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9180:                             my $numsec = 5;
                   9181:                             my $timeout = $numsec * 1000;
                   9182:                             my ($newurl,$locknum,%locks,$msg);
                   9183:                             if ($env{'request.role.adv'}) {
                   9184:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9185:                             }
                   9186:                             my $disable_submit = 0;
                   9187:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9188:                                 $disable_submit = 1;
                   9189:                             }
                   9190:                             if ($locknum) {
                   9191:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9192:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9193:                                        join(", ",sort(values(%locks)))."\n";
                   9194:                                 if (&show_course()) {
                   9195:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9196:                                 } else {
                   9197:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9198:                                 }
1.1340    raeburn  9199:                             } else {
                   9200:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9201:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9202:                                 }
                   9203:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9204:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9205:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9206:                                     $newurl .= '&role='.$env{'request.role'};
                   9207:                                 }
                   9208:                                 if ($env{'request.symb'}) {
                   9209:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9210:                                     if ($shownsymb =~ m{^/enc/}) {
                   9211:                                         my $reqdmajor = 2;
                   9212:                                         my $reqdminor = 11;
                   9213:                                         my $reqdsubminor = 3;
                   9214:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9215:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9216:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9217:                                         if (($major eq '' && $minor eq '') ||
                   9218:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9219:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9220:                                              ($reqdsubminor > $subminor))))) {
                   9221:                                             undef($shownsymb);
                   9222:                                         }
1.1210    raeburn  9223:                                     }
1.1340    raeburn  9224:                                     if ($shownsymb) {
                   9225:                                         &js_escape(\$shownsymb);
                   9226:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9227:                                     }
1.1340    raeburn  9228:                                 } else {
                   9229:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9230:                                     &js_escape(\$shownurl);
                   9231:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9232:                                 }
1.1340    raeburn  9233:                             }
                   9234:                             &js_escape(\$msg);
                   9235:                             $result.=<<OFFLOAD
1.1210    raeburn  9236: <meta http-equiv="pragma" content="no-cache" />
                   9237: <script type="text/javascript">
1.1215    raeburn  9238: // <![CDATA[
1.1210    raeburn  9239: function LC_Offload_Now() {
                   9240:     var dest = "$newurl";
                   9241:     if (dest != '') {
                   9242:         window.location.href="$newurl";
                   9243:     }
                   9244: }
1.1214    raeburn  9245: \$(document).ready(function () {
                   9246:     window.alert('$msg');
                   9247:     if ($disable_submit) {
1.1210    raeburn  9248:         \$(".LC_hwk_submit").prop("disabled", true);
                   9249:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9250:     }
                   9251:     setTimeout('LC_Offload_Now()', $timeout);
                   9252: });
1.1215    raeburn  9253: // ]]>
1.1210    raeburn  9254: </script>
                   9255: OFFLOAD
                   9256:                         }
                   9257:                     }
                   9258:                 }
                   9259:             }
                   9260:         }
1.313     albertel 9261:     }
1.306     albertel 9262:     if (!defined($title)) {
                   9263: 	$title = 'The LearningOnline Network with CAPA';
                   9264:     }
1.460     albertel 9265:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9266:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9267: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9268:     if (!$args->{'frameset'}) {
                   9269:         $result .= ' /';
                   9270:     }
                   9271:     $result .= '>' 
1.1064    raeburn  9272:         .$inhibitprint
1.414     albertel 9273: 	.$head_extra;
1.1242    raeburn  9274:     my $clientmobile;
                   9275:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9276:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9277:     } else {
                   9278:         $clientmobile = $env{'browser.mobile'};
                   9279:     }
                   9280:     if ($clientmobile) {
1.1137    raeburn  9281:         $result .= '
                   9282: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9283: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9284:     }
1.1278    raeburn  9285:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9286:     return $result.'</head>';
1.306     albertel 9287: }
                   9288: 
                   9289: =pod
                   9290: 
1.340     albertel 9291: =item * &font_settings()
                   9292: 
                   9293: Returns neccessary <meta> to set the proper encoding
                   9294: 
1.1160    raeburn  9295: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9296: 
                   9297: =cut
                   9298: 
                   9299: sub font_settings {
1.1160    raeburn  9300:     my ($args) = @_;
1.340     albertel 9301:     my $headerstring='';
1.1160    raeburn  9302:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9303:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9304:         $headerstring.=
                   9305:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9306:         if (!$args->{'frameset'}) {
                   9307: 	    $headerstring.= ' /';
                   9308:         }
                   9309: 	$headerstring .= '>'."\n";
1.340     albertel 9310:     }
                   9311:     return $headerstring;
                   9312: }
                   9313: 
1.341     albertel 9314: =pod
                   9315: 
1.1064    raeburn  9316: =item * &print_suppression()
                   9317: 
                   9318: In course context returns css which causes the body to be blank when media="print",
                   9319: if printout generation is unavailable for the current resource.
                   9320: 
                   9321: This could be because:
                   9322: 
                   9323: (a) printstartdate is in the future
                   9324: 
                   9325: (b) printenddate is in the past
                   9326: 
                   9327: (c) there is an active exam block with "printout"
                   9328: functionality blocked
                   9329: 
                   9330: Users with pav, pfo or evb privileges are exempt.
                   9331: 
                   9332: Inputs: none
                   9333: 
                   9334: =cut
                   9335: 
                   9336: 
                   9337: sub print_suppression {
                   9338:     my $noprint;
                   9339:     if ($env{'request.course.id'}) {
                   9340:         my $scope = $env{'request.course.id'};
                   9341:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9342:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9343:             return;
                   9344:         }
                   9345:         if ($env{'request.course.sec'} ne '') {
                   9346:             $scope .= "/$env{'request.course.sec'}";
                   9347:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9348:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9349:                 return;
1.1064    raeburn  9350:             }
                   9351:         }
                   9352:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9353:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9354:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9355:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9356:         if ($blocked) {
                   9357:             my $checkrole = "cm./$cdom/$cnum";
                   9358:             if ($env{'request.course.sec'} ne '') {
                   9359:                 $checkrole .= "/$env{'request.course.sec'}";
                   9360:             }
                   9361:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9362:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9363:                 $noprint = 1;
                   9364:             }
                   9365:         }
                   9366:         unless ($noprint) {
                   9367:             my $symb = &Apache::lonnet::symbread();
                   9368:             if ($symb ne '') {
                   9369:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9370:                 if (ref($navmap)) {
                   9371:                     my $res = $navmap->getBySymb($symb);
                   9372:                     if (ref($res)) {
                   9373:                         if (!$res->resprintable()) {
                   9374:                             $noprint = 1;
                   9375:                         }
                   9376:                     }
                   9377:                 }
                   9378:             }
                   9379:         }
                   9380:         if ($noprint) {
                   9381:             return <<"ENDSTYLE";
                   9382: <style type="text/css" media="print">
                   9383:     body { display:none }
                   9384: </style>
                   9385: ENDSTYLE
                   9386:         }
                   9387:     }
                   9388:     return;
                   9389: }
                   9390: 
                   9391: =pod
                   9392: 
1.341     albertel 9393: =item * &xml_begin()
                   9394: 
                   9395: Returns the needed doctype and <html>
                   9396: 
                   9397: Inputs: none
                   9398: 
                   9399: =cut
                   9400: 
                   9401: sub xml_begin {
1.1168    raeburn  9402:     my ($is_frameset) = @_;
1.341     albertel 9403:     my $output='';
                   9404: 
                   9405:     if ($env{'browser.mathml'}) {
                   9406: 	$output='<?xml version="1.0"?>'
                   9407:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9408: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9409:             
                   9410: #	    .'<!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">] >'
                   9411: 	    .'<!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">'
                   9412:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9413: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9414:     } elsif ($is_frameset) {
                   9415:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9416:                 '<html>'."\n";
1.341     albertel 9417:     } else {
1.1168    raeburn  9418: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9419:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9420:     }
                   9421:     return $output;
                   9422: }
1.340     albertel 9423: 
                   9424: =pod
                   9425: 
1.306     albertel 9426: =item * &start_page()
                   9427: 
                   9428: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9429: 
1.648     raeburn  9430: Inputs:
                   9431: 
                   9432: =over 4
                   9433: 
                   9434: $title - optional title for the page
                   9435: 
                   9436: $head_extra - optional extra HTML to incude inside the <head>
                   9437: 
                   9438: $args - additional optional args supported are:
                   9439: 
                   9440: =over 8
                   9441: 
                   9442:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9443:                                     arg on
1.814     bisitz   9444:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9445:              add_entries    -> additional attributes to add to the  <body>
                   9446:              domain         -> force to color decorate a page for a 
1.317     albertel 9447:                                     specific domain
1.648     raeburn  9448:              function       -> force usage of a specific rolish color
1.317     albertel 9449:                                     scheme
1.648     raeburn  9450:              redirect       -> see &headtag()
                   9451:              bgcolor        -> override the default page bg color
                   9452:              js_ready       -> return a string ready for being used in 
1.317     albertel 9453:                                     a javascript writeln
1.648     raeburn  9454:              html_encode    -> return a string ready for being used in 
1.320     albertel 9455:                                     a html attribute
1.648     raeburn  9456:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9457:                                     $forcereg arg
1.648     raeburn  9458:              frameset       -> if true will start with a <frameset>
1.330     albertel 9459:                                     rather than <body>
1.648     raeburn  9460:              skip_phases    -> hash ref of 
1.338     albertel 9461:                                     head -> skip the <html><head> generation
                   9462:                                     body -> skip all <body> generation
1.648     raeburn  9463:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9464:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9465:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9466:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9467:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9468:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9469:                                specific group
                   9470:              use_absolute   -> for request for external resource or syllabus, this
                   9471:                                will contain https://<hostname> if server uses
                   9472:                                https (as per hosts.tab), but request is for http
                   9473:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9474:              links_disabled -> Links in primary and secondary menus are disabled
                   9475:                                (Can enable them once page has loaded - see lonroles.pm
                   9476:                                for an example).
1.1380    raeburn  9477:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9478: 
1.648     raeburn  9479: =back
1.460     albertel 9480: 
1.648     raeburn  9481: =back
1.562     albertel 9482: 
1.306     albertel 9483: =cut
                   9484: 
                   9485: sub start_page {
1.309     albertel 9486:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9487:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9488: 
1.315     albertel 9489:     $env{'internal.start_page'}++;
1.1359    raeburn  9490:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9491: 
1.338     albertel 9492:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9493:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9494:     }
1.1316    raeburn  9495: 
                   9496:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9497:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9498:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9499:                 $args->{'no_primary_menu'} = 1;
                   9500:             }
                   9501:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9502:                 $args->{'no_inline_menu'} = 1;
                   9503:             }
                   9504:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9505:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9506:             }
                   9507:         } else {
                   9508:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9509:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9510:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9511:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9512:                     $args->{'no_primary_menu'} = 1;
                   9513:                 }
                   9514:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9515:                     $args->{'no_inline_menu'} = 1;
                   9516:                 }
                   9517:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9518:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9519:                 }
                   9520:             }
                   9521:         }
1.1316    raeburn  9522:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9523:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9524:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9525:     } elsif ($env{'request.course.id'}) {
                   9526:         my $expiretime=600;
                   9527:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9528:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9529:         }
                   9530:         my ($deeplinkmenu,$menuref);
                   9531:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9532:         if ($menucoll) {
                   9533:             if (ref($menuref) eq 'HASH') {
                   9534:                 %menu = %{$menuref};
                   9535:             }
                   9536:             if ($menu{'top'} eq 'n') {
                   9537:                 $args->{'no_primary_menu'} = 1;
                   9538:             }
                   9539:             if ($menu{'inline'} eq 'n') {
                   9540:                 unless (&Apache::lonnet::allowed('opa')) {
                   9541:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9542:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9543:                     my $crstype = &course_type();
                   9544:                     my $now = time;
                   9545:                     my $ccrole;
                   9546:                     if ($crstype eq 'Community') {
                   9547:                         $ccrole = 'co';
                   9548:                     } else {
                   9549:                         $ccrole = 'cc';
                   9550:                     }
                   9551:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9552:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9553:                         if ((($start) && ($start<0)) ||
                   9554:                             (($end) && ($end<$now))  ||
                   9555:                             (($start) && ($now<$start))) {
                   9556:                             $args->{'no_inline_menu'} = 1;
                   9557:                         }
                   9558:                     } else {
                   9559:                         $args->{'no_inline_menu'} = 1;
                   9560:                     }
                   9561:                 }
                   9562:             }
                   9563:         }
1.1316    raeburn  9564:     }
1.1359    raeburn  9565: 
1.1385    raeburn  9566:     my $showncrumbs;
1.338     albertel 9567:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9568: 	if ($args->{'frameset'}) {
                   9569: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9570: 						$args->{'add_entries'});
                   9571: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9572:         } else {
                   9573:             $result .=
                   9574:                 &bodytag($title, 
                   9575:                          $args->{'function'},       $args->{'add_entries'},
                   9576:                          $args->{'only_body'},      $args->{'domain'},
                   9577:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9578:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  9579:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   9580:                          \%menu,\$showncrumbs);
1.831     bisitz   9581:         }
1.330     albertel 9582:     }
1.338     albertel 9583: 
1.315     albertel 9584:     if ($args->{'js_ready'}) {
1.713     kaisler  9585: 		$result = &js_ready($result);
1.315     albertel 9586:     }
1.320     albertel 9587:     if ($args->{'html_encode'}) {
1.713     kaisler  9588: 		$result = &html_encode($result);
                   9589:     }
                   9590: 
1.813     bisitz   9591:     # Preparation for new and consistent functionlist at top of screen
                   9592:     # if ($args->{'functionlist'}) {
                   9593:     #            $result .= &build_functionlist();
                   9594:     #}
                   9595: 
1.964     droeschl 9596:     # Don't add anything more if only_body wanted or in const space
                   9597:     return $result if    $args->{'only_body'} 
                   9598:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9599: 
                   9600:     #Breadcrumbs
1.758     kaisler  9601:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  9602:         unless ($showncrumbs) {
1.758     kaisler  9603: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9604: 		#if any br links exists, add them to the breadcrumbs
                   9605: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9606: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9607: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9608: 			}
                   9609: 		}
1.1096    raeburn  9610:                 # if @advtools array contains items add then to the breadcrumbs
                   9611:                 if (@advtools > 0) {
                   9612:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9613:                 }
1.1272    raeburn  9614:                 my $menulink;
                   9615:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9616:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9617:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9618:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9619:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9620:                      (!$env{'request.role.adv'}))) {
                   9621:                     $menulink = 0;
                   9622:                 } else {
                   9623:                     undef($menulink);
                   9624:                 }
1.1385    raeburn  9625:                 my $linkprotout;
                   9626:                 if ($env{'request.deeplink.login'}) {
                   9627:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9628:                     if ($linkprotout) {
                   9629:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9630:                     }
                   9631:                 }
1.758     kaisler  9632: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9633: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9634: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9635:                 } else {
1.1272    raeburn  9636: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9637: 		}
1.1385    raeburn  9638:         }
1.320     albertel 9639:     }
1.315     albertel 9640:     return $result;
1.306     albertel 9641: }
                   9642: 
                   9643: sub end_page {
1.315     albertel 9644:     my ($args) = @_;
                   9645:     $env{'internal.end_page'}++;
1.330     albertel 9646:     my $result;
1.335     albertel 9647:     if ($args->{'discussion'}) {
                   9648: 	my ($target,$parser);
                   9649: 	if (ref($args->{'discussion'})) {
                   9650: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9651: 				$args->{'discussion'}{'parser'});
                   9652: 	}
                   9653: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9654:     }
1.330     albertel 9655:     if ($args->{'frameset'}) {
                   9656: 	$result .= '</frameset>';
                   9657:     } else {
1.635     raeburn  9658: 	$result .= &endbodytag($args);
1.330     albertel 9659:     }
1.1080    raeburn  9660:     unless ($args->{'notbody'}) {
                   9661:         $result .= "\n</html>";
                   9662:     }
1.330     albertel 9663: 
1.315     albertel 9664:     if ($args->{'js_ready'}) {
1.317     albertel 9665: 	$result = &js_ready($result);
1.315     albertel 9666:     }
1.335     albertel 9667: 
1.320     albertel 9668:     if ($args->{'html_encode'}) {
                   9669: 	$result = &html_encode($result);
                   9670:     }
1.335     albertel 9671: 
1.315     albertel 9672:     return $result;
                   9673: }
                   9674: 
1.1359    raeburn  9675: sub menucoll_in_effect {
                   9676:     my ($menucoll,$deeplinkmenu,%menu);
                   9677:     if ($env{'request.course.id'}) {
                   9678:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9679:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9680:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9681:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9682:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9683:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9684:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9685:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9686:                     if (ref($navmap)) {
                   9687:                         $deeplink = $navmap->get_mapparam(undef,
                   9688:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9689:                                                           '0.deeplink');
1.1370    raeburn  9690:                     } else {
                   9691:                         $check_login_symb = 1;
1.1362    raeburn  9692:                     }
                   9693:                 } else {
1.1370    raeburn  9694:                     my $symb = &Apache::lonnet::symbread();
                   9695:                     if ($symb) {
                   9696:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9697:                     } else {
                   9698:                         $check_login_symb = 1;
                   9699:                     }
1.1362    raeburn  9700:                 }
                   9701:             } else {
1.1370    raeburn  9702:                 $check_login_symb = 1;
                   9703:             }
                   9704:             if ($check_login_symb) {
1.1362    raeburn  9705:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9706:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9707:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9708:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9709:                     if (ref($navmap)) {
                   9710:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9711:                     }
                   9712:                 } else {
                   9713:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9714:                 }
                   9715:             }
1.1359    raeburn  9716:             if ($deeplink ne '') {
1.1378    raeburn  9717:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  9718:                 if ($display =~ /^\d+$/) {
                   9719:                     $deeplinkmenu = 1;
                   9720:                     $menucoll = $display;
                   9721:                 }
                   9722:             }
                   9723:         }
                   9724:         if ($menucoll) {
                   9725:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9726:         }
                   9727:     }
                   9728:     return ($menucoll,$deeplinkmenu,\%menu);
                   9729: }
                   9730: 
1.1362    raeburn  9731: sub deeplink_login_symb {
                   9732:     my ($cnum,$cdom) = @_;
                   9733:     my $login_symb;
                   9734:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9735:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9736:     }
                   9737:     return $login_symb;
                   9738: }
                   9739: 
                   9740: sub symb_from_tinyurl {
                   9741:     my ($url,$cnum,$cdom) = @_;
                   9742:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9743:         my $key = $1;
                   9744:         my ($tinyurl,$login);
                   9745:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9746:         if (defined($cached)) {
                   9747:             $tinyurl = $result;
                   9748:         } else {
                   9749:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9750:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9751:             if ($currtiny{$key} ne '') {
                   9752:                 $tinyurl = $currtiny{$key};
                   9753:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9754:             }
1.1364    raeburn  9755:         }
                   9756:         if ($tinyurl ne '') {
                   9757:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9758:             if (wantarray) {
                   9759:                 return ($cnumreq,$symb);
                   9760:             } elsif ($cnumreq eq $cnum) {
                   9761:                 return $symb;
1.1362    raeburn  9762:             }
                   9763:         }
                   9764:     }
1.1364    raeburn  9765:     if (wantarray) {
                   9766:         return ();
                   9767:     } else {
                   9768:         return;
                   9769:     }
1.1362    raeburn  9770: }
                   9771: 
1.1405    raeburn  9772: sub usable_exttools {
                   9773:     my %tooltypes;
                   9774:     if ($env{'request.course.id'}) {
                   9775:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   9776:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   9777:                %tooltypes = (
                   9778:                              crs => 1,
                   9779:                              dom => 1,
                   9780:                             );
                   9781:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   9782:                $tooltypes{'crs'} = 1;
                   9783:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   9784:                $tooltypes{'dom'} = 1;
                   9785:            }
                   9786:         } else {
                   9787:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9788:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9789:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9790:             if ($crstype eq '') {
                   9791:                 $crstype = 'course';
                   9792:             }
                   9793:             if ($crstype eq 'course') {
                   9794:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   9795:                     $crstype = 'official';
                   9796:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   9797:                     $crstype = 'textbook';
                   9798:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   9799:                     $crstype = 'lti';
                   9800:                 } else {
                   9801:                     $crstype = 'unofficial';
                   9802:                 }
                   9803:             }
                   9804:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   9805:             if ($domdefaults{$crstype.'domexttool'}) {
                   9806:                 $tooltypes{'dom'} = 1;
                   9807:             }
                   9808:             if ($domdefaults{$crstype.'exttool'}) {
                   9809:                 $tooltypes{'crs'} = 1;
                   9810:             }
                   9811:         }
                   9812:     }
                   9813:     return %tooltypes;
                   9814: }
                   9815: 
1.1034    www      9816: sub wishlist_window {
                   9817:     return(<<'ENDWISHLIST');
1.1046    raeburn  9818: <script type="text/javascript">
1.1034    www      9819: // <![CDATA[
                   9820: // <!-- BEGIN LON-CAPA Internal
                   9821: function set_wishlistlink(title, path) {
                   9822:     if (!title) {
                   9823:         title = document.title;
                   9824:         title = title.replace(/^LON-CAPA /,'');
                   9825:     }
1.1175    raeburn  9826:     title = encodeURIComponent(title);
1.1203    raeburn  9827:     title = title.replace("'","\\\'");
1.1034    www      9828:     if (!path) {
                   9829:         path = location.pathname;
                   9830:     }
1.1175    raeburn  9831:     path = encodeURIComponent(path);
1.1203    raeburn  9832:     path = path.replace("'","\\\'");
1.1034    www      9833:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9834:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9835: }
                   9836: // END LON-CAPA Internal -->
                   9837: // ]]>
                   9838: </script>
                   9839: ENDWISHLIST
                   9840: }
                   9841: 
1.1030    www      9842: sub modal_window {
                   9843:     return(<<'ENDMODAL');
1.1046    raeburn  9844: <script type="text/javascript">
1.1030    www      9845: // <![CDATA[
                   9846: // <!-- BEGIN LON-CAPA Internal
                   9847: var modalWindow = {
                   9848: 	parent:"body",
                   9849: 	windowId:null,
                   9850: 	content:null,
                   9851: 	width:null,
                   9852: 	height:null,
                   9853: 	close:function()
                   9854: 	{
                   9855: 	        $(".LCmodal-window").remove();
                   9856: 	        $(".LCmodal-overlay").remove();
                   9857: 	},
                   9858: 	open:function()
                   9859: 	{
                   9860: 		var modal = "";
                   9861: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9862: 		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;\">";
                   9863: 		modal += this.content;
                   9864: 		modal += "</div>";	
                   9865: 
                   9866: 		$(this.parent).append(modal);
                   9867: 
                   9868: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9869: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9870: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9871: 	}
                   9872: };
1.1140    raeburn  9873: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9874: 	{
1.1266    raeburn  9875:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9876: 		modalWindow.windowId = "myModal";
                   9877: 		modalWindow.width = width;
                   9878: 		modalWindow.height = height;
1.1196    raeburn  9879: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9880: 		modalWindow.open();
1.1208    raeburn  9881: 	};
1.1030    www      9882: // END LON-CAPA Internal -->
                   9883: // ]]>
                   9884: </script>
                   9885: ENDMODAL
                   9886: }
                   9887: 
                   9888: sub modal_link {
1.1140    raeburn  9889:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9890:     unless ($width) { $width=480; }
                   9891:     unless ($height) { $height=400; }
1.1031    www      9892:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9893:     unless ($transparency) { $transparency='true'; }
                   9894: 
1.1074    raeburn  9895:     my $target_attr;
                   9896:     if (defined($target)) {
                   9897:         $target_attr = 'target="'.$target.'"';
                   9898:     }
                   9899:     return <<"ENDLINK";
1.1336    raeburn  9900: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9901: ENDLINK
1.1030    www      9902: }
                   9903: 
1.1032    www      9904: sub modal_adhoc_script {
1.1365    raeburn  9905:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9906:     my $mathjax;
                   9907:     if ($possmathjax) {
                   9908:         $mathjax = <<'ENDJAX';
                   9909:                if (typeof MathJax == 'object') {
                   9910:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9911:                }
                   9912: ENDJAX
                   9913:     }
1.1032    www      9914:     return (<<ENDADHOC);
1.1046    raeburn  9915: <script type="text/javascript">
1.1032    www      9916: // <![CDATA[
                   9917:         var $funcname = function()
                   9918:         {
                   9919:                 modalWindow.windowId = "myModal";
                   9920:                 modalWindow.width = $width;
                   9921:                 modalWindow.height = $height;
                   9922:                 modalWindow.content = '$content';
                   9923:                 modalWindow.open();
1.1365    raeburn  9924:                 $mathjax
1.1032    www      9925:         };  
                   9926: // ]]>
                   9927: </script>
                   9928: ENDADHOC
                   9929: }
                   9930: 
1.1041    www      9931: sub modal_adhoc_inner {
1.1365    raeburn  9932:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9933:     my $innerwidth=$width-20;
                   9934:     $content=&js_ready(
1.1140    raeburn  9935:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9936:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9937:                  $content.
1.1041    www      9938:                  &end_scrollbox().
1.1140    raeburn  9939:                  &end_page()
1.1041    www      9940:              );
1.1365    raeburn  9941:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9942: }
                   9943: 
                   9944: sub modal_adhoc_window {
1.1365    raeburn  9945:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9946:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9947:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9948: }
                   9949: 
                   9950: sub modal_adhoc_launch {
                   9951:     my ($funcname,$width,$height,$content)=@_;
                   9952:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9953: <script type="text/javascript">
                   9954: // <![CDATA[
                   9955: $funcname();
                   9956: // ]]>
                   9957: </script>
                   9958: ENDLAUNCH
                   9959: }
                   9960: 
                   9961: sub modal_adhoc_close {
                   9962:     return (<<ENDCLOSE);
                   9963: <script type="text/javascript">
                   9964: // <![CDATA[
                   9965: modalWindow.close();
                   9966: // ]]>
                   9967: </script>
                   9968: ENDCLOSE
                   9969: }
                   9970: 
1.1038    www      9971: sub togglebox_script {
                   9972:    return(<<ENDTOGGLE);
                   9973: <script type="text/javascript"> 
                   9974: // <![CDATA[
                   9975: function LCtoggleDisplay(id,hidetext,showtext) {
                   9976:    link = document.getElementById(id + "link").childNodes[0];
                   9977:    with (document.getElementById(id).style) {
                   9978:       if (display == "none" ) {
                   9979:           display = "inline";
                   9980:           link.nodeValue = hidetext;
                   9981:         } else {
                   9982:           display = "none";
                   9983:           link.nodeValue = showtext;
                   9984:        }
                   9985:    }
                   9986: }
                   9987: // ]]>
                   9988: </script>
                   9989: ENDTOGGLE
                   9990: }
                   9991: 
1.1039    www      9992: sub start_togglebox {
                   9993:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9994:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9995:     unless ($showtext) { $showtext=&mt('show'); }
                   9996:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9997:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9998:     return &start_data_table().
                   9999:            &start_data_table_header_row().
                   10000:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10001:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10002:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10003:            &end_data_table_header_row().
                   10004:            '<tr id="'.$id.'" style="display:none""><td>';
                   10005: }
                   10006: 
                   10007: sub end_togglebox {
                   10008:     return '</td></tr>'.&end_data_table();
                   10009: }
                   10010: 
1.1041    www      10011: sub LCprogressbar_script {
1.1302    raeburn  10012:    my ($id,$number_to_do)=@_;
                   10013:    if ($number_to_do) {
                   10014:        return(<<ENDPROGRESS);
1.1041    www      10015: <script type="text/javascript">
                   10016: // <![CDATA[
1.1045    www      10017: \$('#progressbar$id').progressbar({
1.1041    www      10018:   value: 0,
                   10019:   change: function(event, ui) {
                   10020:     var newVal = \$(this).progressbar('option', 'value');
                   10021:     \$('.pblabel', this).text(LCprogressTxt);
                   10022:   }
                   10023: });
                   10024: // ]]>
                   10025: </script>
                   10026: ENDPROGRESS
1.1302    raeburn  10027:    } else {
                   10028:        return(<<ENDPROGRESS);
                   10029: <script type="text/javascript">
                   10030: // <![CDATA[
                   10031: \$('#progressbar$id').progressbar({
                   10032:   value: false,
                   10033:   create: function(event, ui) {
                   10034:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10035:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10036:   }
                   10037: });
                   10038: // ]]>
                   10039: </script>
                   10040: ENDPROGRESS
                   10041:    }
1.1041    www      10042: }
                   10043: 
                   10044: sub LCprogressbarUpdate_script {
                   10045:    return(<<ENDPROGRESSUPDATE);
                   10046: <style type="text/css">
                   10047: .ui-progressbar { position:relative; }
1.1302    raeburn  10048: .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      10049: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10050: </style>
                   10051: <script type="text/javascript">
                   10052: // <![CDATA[
1.1045    www      10053: var LCprogressTxt='---';
                   10054: 
1.1302    raeburn  10055: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10056:    LCprogressTxt=progresstext;
1.1302    raeburn  10057:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10058:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10059:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10060:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10061:    } else {
                   10062:        \$('#progressbar'+id).progressbar('value',percent);
                   10063:    }
1.1041    www      10064: }
                   10065: // ]]>
                   10066: </script>
                   10067: ENDPROGRESSUPDATE
                   10068: }
                   10069: 
1.1042    www      10070: my $LClastpercent;
1.1045    www      10071: my $LCidcnt;
                   10072: my $LCcurrentid;
1.1042    www      10073: 
1.1041    www      10074: sub LCprogressbar {
1.1302    raeburn  10075:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10076:     $LClastpercent=0;
1.1045    www      10077:     $LCidcnt++;
                   10078:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10079:     my ($starting,$content);
                   10080:     if ($number_to_do) {
                   10081:         $starting=&mt('Starting');
                   10082:         $content=(<<ENDPROGBAR);
                   10083: $preamble
1.1045    www      10084:   <div id="progressbar$LCcurrentid">
1.1041    www      10085:     <span class="pblabel">$starting</span>
                   10086:   </div>
                   10087: ENDPROGBAR
1.1302    raeburn  10088:     } else {
                   10089:         $starting=&mt('Loading...');
                   10090:         $LClastpercent='false';
                   10091:         $content=(<<ENDPROGBAR);
                   10092: $preamble
                   10093:   <div id="progressbar$LCcurrentid">
                   10094:       <div class="progress-label">$starting</div>
                   10095:   </div>
                   10096: ENDPROGBAR
                   10097:     }
                   10098:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10099: }
                   10100: 
                   10101: sub LCprogressbarUpdate {
1.1302    raeburn  10102:     my ($r,$val,$text,$number_to_do)=@_;
                   10103:     if ($number_to_do) {
                   10104:         unless ($val) { 
                   10105:             if ($LClastpercent) {
                   10106:                 $val=$LClastpercent;
                   10107:             } else {
                   10108:                 $val=0;
                   10109:             }
                   10110:         }
                   10111:         if ($val<0) { $val=0; }
                   10112:         if ($val>100) { $val=0; }
                   10113:         $LClastpercent=$val;
                   10114:         unless ($text) { $text=$val.'%'; }
                   10115:     } else {
                   10116:         $val = 'false';
1.1042    www      10117:     }
1.1041    www      10118:     $text=&js_ready($text);
1.1044    www      10119:     &r_print($r,<<ENDUPDATE);
1.1041    www      10120: <script type="text/javascript">
                   10121: // <![CDATA[
1.1302    raeburn  10122: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10123: // ]]>
                   10124: </script>
                   10125: ENDUPDATE
1.1035    www      10126: }
                   10127: 
1.1042    www      10128: sub LCprogressbarClose {
                   10129:     my ($r)=@_;
                   10130:     $LClastpercent=0;
1.1044    www      10131:     &r_print($r,<<ENDCLOSE);
1.1042    www      10132: <script type="text/javascript">
                   10133: // <![CDATA[
1.1045    www      10134: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10135: // ]]>
                   10136: </script>
                   10137: ENDCLOSE
1.1044    www      10138: }
                   10139: 
                   10140: sub r_print {
                   10141:     my ($r,$to_print)=@_;
                   10142:     if ($r) {
                   10143:       $r->print($to_print);
                   10144:       $r->rflush();
                   10145:     } else {
                   10146:       print($to_print);
                   10147:     }
1.1042    www      10148: }
                   10149: 
1.320     albertel 10150: sub html_encode {
                   10151:     my ($result) = @_;
                   10152: 
1.322     albertel 10153:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10154:     
                   10155:     return $result;
                   10156: }
1.1044    www      10157: 
1.317     albertel 10158: sub js_ready {
                   10159:     my ($result) = @_;
                   10160: 
1.323     albertel 10161:     $result =~ s/[\n\r]/ /xmsg;
                   10162:     $result =~ s/\\/\\\\/xmsg;
                   10163:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10164:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10165:     
                   10166:     return $result;
                   10167: }
                   10168: 
1.315     albertel 10169: sub validate_page {
                   10170:     if (  exists($env{'internal.start_page'})
1.316     albertel 10171: 	  &&     $env{'internal.start_page'} > 1) {
                   10172: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10173: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10174: 				 $ENV{'request.filename'});
1.315     albertel 10175:     }
                   10176:     if (  exists($env{'internal.end_page'})
1.316     albertel 10177: 	  &&     $env{'internal.end_page'} > 1) {
                   10178: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10179: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10180: 				 $env{'request.filename'});
1.315     albertel 10181:     }
                   10182:     if (     exists($env{'internal.start_page'})
                   10183: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10184: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10185: 				 $env{'request.filename'});
1.315     albertel 10186:     }
                   10187:     if (   ! exists($env{'internal.start_page'})
                   10188: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10189: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10190: 				 $env{'request.filename'});
1.315     albertel 10191:     }
1.306     albertel 10192: }
1.315     albertel 10193: 
1.996     www      10194: 
                   10195: sub start_scrollbox {
1.1140    raeburn  10196:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10197:     unless ($outerwidth) { $outerwidth='520px'; }
                   10198:     unless ($width) { $width='500px'; }
                   10199:     unless ($height) { $height='200px'; }
1.1075    raeburn  10200:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10201:     if ($id ne '') {
1.1140    raeburn  10202:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10203:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10204:     }
1.1075    raeburn  10205:     if ($bgcolor ne '') {
                   10206:         $tdcol = "background-color: $bgcolor;";
                   10207:     }
1.1137    raeburn  10208:     my $nicescroll_js;
                   10209:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10210:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10211:     }
                   10212:     return <<"END";
                   10213: $nicescroll_js
                   10214: 
                   10215: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10216: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10217: END
                   10218: }
                   10219: 
                   10220: sub end_scrollbox {
                   10221:     return '</div></td></tr></table>';
                   10222: }
                   10223: 
                   10224: sub nicescroll_javascript {
                   10225:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10226:     my %options;
                   10227:     if (ref($cursor) eq 'HASH') {
                   10228:         %options = %{$cursor};
                   10229:     }
                   10230:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10231:         $options{'railalign'} = 'left';
                   10232:     }
                   10233:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10234:         my $function  = &get_users_function();
                   10235:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10236:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10237:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10238:         }
1.1140    raeburn  10239:     }
                   10240:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10241:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10242:             $options{'cursoropacity'}='1.0';
                   10243:         }
1.1140    raeburn  10244:     } else {
                   10245:         $options{'cursoropacity'}='1.0';
                   10246:     }
                   10247:     if ($options{'cursorfixedheight'} eq 'none') {
                   10248:         delete($options{'cursorfixedheight'});
                   10249:     } else {
                   10250:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10251:     }
                   10252:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10253:         delete($options{'railoffset'});
                   10254:     }
                   10255:     my @niceoptions;
                   10256:     while (my($key,$value) = each(%options)) {
                   10257:         if ($value =~ /^\{.+\}$/) {
                   10258:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10259:         } else {
1.1140    raeburn  10260:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10261:         }
1.1140    raeburn  10262:     }
                   10263:     my $nicescroll_js = '
1.1137    raeburn  10264: $(document).ready(
1.1140    raeburn  10265:       function() {
                   10266:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10267:       }
1.1137    raeburn  10268: );
                   10269: ';
1.1140    raeburn  10270:     if ($framecheck) {
                   10271:         $nicescroll_js .= '
                   10272: function expand_div(caller) {
                   10273:     if (top === self) {
                   10274:         document.getElementById("'.$id.'").style.width = "auto";
                   10275:         document.getElementById("'.$id.'").style.height = "auto";
                   10276:     } else {
                   10277:         try {
                   10278:             if (parent.frames) {
                   10279:                 if (parent.frames.length > 1) {
                   10280:                     var framesrc = parent.frames[1].location.href;
                   10281:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10282:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10283:                         document.getElementById("'.$id.'").style.width = "auto";
                   10284:                         document.getElementById("'.$id.'").style.height = "auto";
                   10285:                     }
                   10286:                 }
                   10287:             }
                   10288:         } catch (e) {
                   10289:             return;
                   10290:         }
1.1137    raeburn  10291:     }
1.1140    raeburn  10292:     return;
1.996     www      10293: }
1.1140    raeburn  10294: ';
                   10295:     }
                   10296:     if ($needjsready) {
                   10297:         $nicescroll_js = '
                   10298: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10299:     } else {
                   10300:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10301:     }
                   10302:     return $nicescroll_js;
1.996     www      10303: }
                   10304: 
1.318     albertel 10305: sub simple_error_page {
1.1150    bisitz   10306:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10307:     my %displayargs;
1.1151    raeburn  10308:     if (ref($args) eq 'HASH') {
                   10309:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10310:         if ($args->{'only_body'}) {
                   10311:             $displayargs{'only_body'} = 1;
                   10312:         }
                   10313:         if ($args->{'no_nav_bar'}) {
                   10314:             $displayargs{'no_nav_bar'} = 1;
                   10315:         }
1.1151    raeburn  10316:     } else {
                   10317:         $msg = &mt($msg);
                   10318:     }
1.1150    bisitz   10319: 
1.318     albertel 10320:     my $page =
1.1304    raeburn  10321: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10322: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10323: 	&Apache::loncommon::end_page();
                   10324:     if (ref($r)) {
                   10325: 	$r->print($page);
1.327     albertel 10326: 	return;
1.318     albertel 10327:     }
                   10328:     return $page;
                   10329: }
1.347     albertel 10330: 
                   10331: {
1.610     albertel 10332:     my @row_count;
1.961     onken    10333: 
                   10334:     sub start_data_table_count {
                   10335:         unshift(@row_count, 0);
                   10336:         return;
                   10337:     }
                   10338: 
                   10339:     sub end_data_table_count {
                   10340:         shift(@row_count);
                   10341:         return;
                   10342:     }
                   10343: 
1.347     albertel 10344:     sub start_data_table {
1.1018    raeburn  10345: 	my ($add_class,$id) = @_;
1.422     albertel 10346: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10347:         my $table_id;
                   10348:         if (defined($id)) {
                   10349:             $table_id = ' id="'.$id.'"';
                   10350:         }
1.961     onken    10351: 	&start_data_table_count();
1.1018    raeburn  10352: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10353:     }
                   10354: 
                   10355:     sub end_data_table {
1.961     onken    10356: 	&end_data_table_count();
1.389     albertel 10357: 	return '</table>'."\n";;
1.347     albertel 10358:     }
                   10359: 
                   10360:     sub start_data_table_row {
1.974     wenzelju 10361: 	my ($add_class, $id) = @_;
1.610     albertel 10362: 	$row_count[0]++;
                   10363: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10364: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10365:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10366:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10367:     }
1.471     banghart 10368:     
                   10369:     sub continue_data_table_row {
1.974     wenzelju 10370: 	my ($add_class, $id) = @_;
1.610     albertel 10371: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10372: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10373:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10374:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10375:     }
1.347     albertel 10376: 
                   10377:     sub end_data_table_row {
1.389     albertel 10378: 	return '</tr>'."\n";;
1.347     albertel 10379:     }
1.367     www      10380: 
1.421     albertel 10381:     sub start_data_table_empty_row {
1.707     bisitz   10382: #	$row_count[0]++;
1.421     albertel 10383: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10384:     }
                   10385: 
                   10386:     sub end_data_table_empty_row {
                   10387: 	return '</tr>'."\n";;
                   10388:     }
                   10389: 
1.367     www      10390:     sub start_data_table_header_row {
1.389     albertel 10391: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10392:     }
                   10393: 
                   10394:     sub end_data_table_header_row {
1.389     albertel 10395: 	return '</tr>'."\n";;
1.367     www      10396:     }
1.890     droeschl 10397: 
                   10398:     sub data_table_caption {
                   10399:         my $caption = shift;
                   10400:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10401:     }
1.347     albertel 10402: }
                   10403: 
1.548     albertel 10404: =pod
                   10405: 
                   10406: =item * &inhibit_menu_check($arg)
                   10407: 
                   10408: Checks for a inhibitmenu state and generates output to preserve it
                   10409: 
                   10410: Inputs:         $arg - can be any of
                   10411:                      - undef - in which case the return value is a string 
                   10412:                                to add  into arguments list of a uri
                   10413:                      - 'input' - in which case the return value is a HTML
                   10414:                                  <form> <input> field of type hidden to
                   10415:                                  preserve the value
                   10416:                      - a url - in which case the return value is the url with
                   10417:                                the neccesary cgi args added to preserve the
                   10418:                                inhibitmenu state
                   10419:                      - a ref to a url - no return value, but the string is
                   10420:                                         updated to include the neccessary cgi
                   10421:                                         args to preserve the inhibitmenu state
                   10422: 
                   10423: =cut
                   10424: 
                   10425: sub inhibit_menu_check {
                   10426:     my ($arg) = @_;
                   10427:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10428:     if ($arg eq 'input') {
                   10429: 	if ($env{'form.inhibitmenu'}) {
                   10430: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10431: 	} else {
                   10432: 	    return
                   10433: 	}
                   10434:     }
                   10435:     if ($env{'form.inhibitmenu'}) {
                   10436: 	if (ref($arg)) {
                   10437: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10438: 	} elsif ($arg eq '') {
                   10439: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10440: 	} else {
                   10441: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10442: 	}
                   10443:     }
                   10444:     if (!ref($arg)) {
                   10445: 	return $arg;
                   10446:     }
                   10447: }
                   10448: 
1.251     albertel 10449: ###############################################
1.182     matthew  10450: 
                   10451: =pod
                   10452: 
1.549     albertel 10453: =back
                   10454: 
                   10455: =head1 User Information Routines
                   10456: 
                   10457: =over 4
                   10458: 
1.405     albertel 10459: =item * &get_users_function()
1.182     matthew  10460: 
                   10461: Used by &bodytag to determine the current users primary role.
                   10462: Returns either 'student','coordinator','admin', or 'author'.
                   10463: 
                   10464: =cut
                   10465: 
                   10466: ###############################################
                   10467: sub get_users_function {
1.815     tempelho 10468:     my $function = 'norole';
1.818     tempelho 10469:     if ($env{'request.role'}=~/^(st)/) {
                   10470:         $function='student';
                   10471:     }
1.907     raeburn  10472:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10473:         $function='coordinator';
                   10474:     }
1.258     albertel 10475:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10476:         $function='admin';
                   10477:     }
1.826     bisitz   10478:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10479:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10480:         $function='author';
                   10481:     }
                   10482:     return $function;
1.54      www      10483: }
1.99      www      10484: 
                   10485: ###############################################
                   10486: 
1.233     raeburn  10487: =pod
                   10488: 
1.821     raeburn  10489: =item * &show_course()
                   10490: 
                   10491: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10492: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10493: 
                   10494: Inputs:
                   10495: None
                   10496: 
                   10497: Outputs:
                   10498: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10499: 
                   10500: =cut
                   10501: 
                   10502: ###############################################
                   10503: sub show_course {
1.1408    raeburn  10504:     my ($udom,$uname) = @_;
                   10505:     if (($udom ne '') && ($uname ne '')) {
                   10506:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
                   10507:             if (&Apache::lonnet::is_advanced($udom,$uname)) {
                   10508:                 return 0;
                   10509:             } else {
                   10510:                 return 1;
                   10511:             }
                   10512:         }
                   10513:     }
1.821     raeburn  10514:     my $course = !$env{'user.adv'};
                   10515:     if (!$env{'user.adv'}) {
                   10516:         foreach my $env (keys(%env)) {
                   10517:             next if ($env !~ m/^user\.priv\./);
                   10518:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10519:                 $course = 0;
                   10520:                 last;
                   10521:             }
                   10522:         }
                   10523:     }
                   10524:     return $course;
                   10525: }
                   10526: 
                   10527: ###############################################
                   10528: 
                   10529: =pod
                   10530: 
1.542     raeburn  10531: =item * &check_user_status()
1.274     raeburn  10532: 
                   10533: Determines current status of supplied role for a
                   10534: specific user. Roles can be active, previous or future.
                   10535: 
                   10536: Inputs: 
                   10537: user's domain, user's username, course's domain,
1.375     raeburn  10538: course's number, optional section ID.
1.274     raeburn  10539: 
                   10540: Outputs:
                   10541: role status: active, previous or future. 
                   10542: 
                   10543: =cut
                   10544: 
                   10545: sub check_user_status {
1.412     raeburn  10546:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10547:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10548:     my @uroles = keys(%userinfo);
1.274     raeburn  10549:     my $srchstr;
                   10550:     my $active_chk = 'none';
1.412     raeburn  10551:     my $now = time;
1.274     raeburn  10552:     if (@uroles > 0) {
1.908     raeburn  10553:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10554:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10555:         } else {
1.412     raeburn  10556:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10557:         }
                   10558:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10559:             my $role_end = 0;
                   10560:             my $role_start = 0;
                   10561:             $active_chk = 'active';
1.412     raeburn  10562:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10563:                 $role_end = $1;
                   10564:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10565:                     $role_start = $1;
1.274     raeburn  10566:                 }
                   10567:             }
                   10568:             if ($role_start > 0) {
1.412     raeburn  10569:                 if ($now < $role_start) {
1.274     raeburn  10570:                     $active_chk = 'future';
                   10571:                 }
                   10572:             }
                   10573:             if ($role_end > 0) {
1.412     raeburn  10574:                 if ($now > $role_end) {
1.274     raeburn  10575:                     $active_chk = 'previous';
                   10576:                 }
                   10577:             }
                   10578:         }
                   10579:     }
                   10580:     return $active_chk;
                   10581: }
                   10582: 
                   10583: ###############################################
                   10584: 
                   10585: =pod
                   10586: 
1.405     albertel 10587: =item * &get_sections()
1.233     raeburn  10588: 
                   10589: Determines all the sections for a course including
                   10590: sections with students and sections containing other roles.
1.419     raeburn  10591: Incoming parameters: 
                   10592: 
                   10593: 1. domain
                   10594: 2. course number 
                   10595: 3. reference to array containing roles for which sections should 
                   10596: be gathered (optional).
                   10597: 4. reference to array containing status types for which sections 
                   10598: should be gathered (optional).
                   10599: 
                   10600: If the third argument is undefined, sections are gathered for any role. 
                   10601: If the fourth argument is undefined, sections are gathered for any status.
                   10602: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10603:  
1.374     raeburn  10604: Returns section hash (keys are section IDs, values are
                   10605: number of users in each section), subject to the
1.419     raeburn  10606: optional roles filter, optional status filter 
1.233     raeburn  10607: 
                   10608: =cut
                   10609: 
                   10610: ###############################################
                   10611: sub get_sections {
1.419     raeburn  10612:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10613:     if (!defined($cdom) || !defined($cnum)) {
                   10614:         my $cid =  $env{'request.course.id'};
                   10615: 
                   10616: 	return if (!defined($cid));
                   10617: 
                   10618:         $cdom = $env{'course.'.$cid.'.domain'};
                   10619:         $cnum = $env{'course.'.$cid.'.num'};
                   10620:     }
                   10621: 
                   10622:     my %sectioncount;
1.419     raeburn  10623:     my $now = time;
1.240     albertel 10624: 
1.1118    raeburn  10625:     my $check_students = 1;
                   10626:     my $only_students = 0;
                   10627:     if (ref($possible_roles) eq 'ARRAY') {
                   10628:         if (grep(/^st$/,@{$possible_roles})) {
                   10629:             if (@{$possible_roles} == 1) {
                   10630:                 $only_students = 1;
                   10631:             }
                   10632:         } else {
                   10633:             $check_students = 0;
                   10634:         }
                   10635:     }
                   10636: 
                   10637:     if ($check_students) { 
1.276     albertel 10638: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10639: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10640: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10641:         my $start_index = &Apache::loncoursedata::CL_START();
                   10642:         my $end_index = &Apache::loncoursedata::CL_END();
                   10643:         my $status;
1.366     albertel 10644: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10645: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10646: 				                     $data->[$status_index],
                   10647:                                                      $data->[$start_index],
                   10648:                                                      $data->[$end_index]);
                   10649:             if ($stu_status eq 'Active') {
                   10650:                 $status = 'active';
                   10651:             } elsif ($end < $now) {
                   10652:                 $status = 'previous';
                   10653:             } elsif ($start > $now) {
                   10654:                 $status = 'future';
                   10655:             } 
                   10656: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10657:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10658:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10659: 		    $sectioncount{$section}++;
                   10660:                 }
1.240     albertel 10661: 	    }
                   10662: 	}
                   10663:     }
1.1118    raeburn  10664:     if ($only_students) {
                   10665:         return %sectioncount;
                   10666:     }
1.240     albertel 10667:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10668:     foreach my $user (sort(keys(%courseroles))) {
                   10669: 	if ($user !~ /^(\w{2})/) { next; }
                   10670: 	my ($role) = ($user =~ /^(\w{2})/);
                   10671: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10672: 	my ($section,$status);
1.240     albertel 10673: 	if ($role eq 'cr' &&
                   10674: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10675: 	    $section=$1;
                   10676: 	}
                   10677: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10678: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10679:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10680:         if ($end == -1 && $start == -1) {
                   10681:             next; #deleted role
                   10682:         }
                   10683:         if (!defined($possible_status)) { 
                   10684:             $sectioncount{$section}++;
                   10685:         } else {
                   10686:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10687:                 $status = 'active';
                   10688:             } elsif ($end < $now) {
                   10689:                 $status = 'future';
                   10690:             } elsif ($start > $now) {
                   10691:                 $status = 'previous';
                   10692:             }
                   10693:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10694:                 $sectioncount{$section}++;
                   10695:             }
                   10696:         }
1.233     raeburn  10697:     }
1.366     albertel 10698:     return %sectioncount;
1.233     raeburn  10699: }
                   10700: 
1.274     raeburn  10701: ###############################################
1.294     raeburn  10702: 
                   10703: =pod
1.405     albertel 10704: 
                   10705: =item * &get_course_users()
                   10706: 
1.275     raeburn  10707: Retrieves usernames:domains for users in the specified course
                   10708: with specific role(s), and access status. 
                   10709: 
                   10710: Incoming parameters:
1.277     albertel 10711: 1. course domain
                   10712: 2. course number
                   10713: 3. access status: users must have - either active, 
1.275     raeburn  10714: previous, future, or all.
1.277     albertel 10715: 4. reference to array of permissible roles
1.288     raeburn  10716: 5. reference to array of section restrictions (optional)
                   10717: 6. reference to results object (hash of hashes).
                   10718: 7. reference to optional userdata hash
1.609     raeburn  10719: 8. reference to optional statushash
1.630     raeburn  10720: 9. flag if privileged users (except those set to unhide in
                   10721:    course settings) should be excluded    
1.609     raeburn  10722: Keys of top level results hash are roles.
1.275     raeburn  10723: Keys of inner hashes are username:domain, with 
                   10724: values set to access type.
1.288     raeburn  10725: Optional userdata hash returns an array with arguments in the 
                   10726: same order as loncoursedata::get_classlist() for student data.
                   10727: 
1.609     raeburn  10728: Optional statushash returns
                   10729: 
1.288     raeburn  10730: Entries for end, start, section and status are blank because
                   10731: of the possibility of multiple values for non-student roles.
                   10732: 
1.275     raeburn  10733: =cut
1.405     albertel 10734: 
1.275     raeburn  10735: ###############################################
1.405     albertel 10736: 
1.275     raeburn  10737: sub get_course_users {
1.630     raeburn  10738:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10739:     my %idx = ();
1.419     raeburn  10740:     my %seclists;
1.288     raeburn  10741: 
                   10742:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10743:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10744:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10745:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10746:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10747:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10748:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10749:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10750: 
1.290     albertel 10751:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10752:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10753:         my $now = time;
1.277     albertel 10754:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10755:             my $match = 0;
1.412     raeburn  10756:             my $secmatch = 0;
1.419     raeburn  10757:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10758:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10759:             if ($section eq '') {
                   10760:                 $section = 'none';
                   10761:             }
1.291     albertel 10762:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10763:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10764:                     $secmatch = 1;
                   10765:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10766:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10767:                         $secmatch = 1;
                   10768:                     }
                   10769:                 } else {  
1.419     raeburn  10770: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10771: 		        $secmatch = 1;
                   10772:                     }
1.290     albertel 10773: 		}
1.412     raeburn  10774:                 if (!$secmatch) {
                   10775:                     next;
                   10776:                 }
1.419     raeburn  10777:             }
1.275     raeburn  10778:             if (defined($$types{'active'})) {
1.288     raeburn  10779:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10780:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10781:                     $match = 1;
1.275     raeburn  10782:                 }
                   10783:             }
                   10784:             if (defined($$types{'previous'})) {
1.609     raeburn  10785:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10786:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10787:                     $match = 1;
1.275     raeburn  10788:                 }
                   10789:             }
                   10790:             if (defined($$types{'future'})) {
1.609     raeburn  10791:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10792:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10793:                     $match = 1;
1.275     raeburn  10794:                 }
                   10795:             }
1.609     raeburn  10796:             if ($match) {
                   10797:                 push(@{$seclists{$student}},$section);
                   10798:                 if (ref($userdata) eq 'HASH') {
                   10799:                     $$userdata{$student} = $$classlist{$student};
                   10800:                 }
                   10801:                 if (ref($statushash) eq 'HASH') {
                   10802:                     $statushash->{$student}{'st'}{$section} = $status;
                   10803:                 }
1.288     raeburn  10804:             }
1.275     raeburn  10805:         }
                   10806:     }
1.412     raeburn  10807:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10808:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10809:         my $now = time;
1.609     raeburn  10810:         my %displaystatus = ( previous => 'Expired',
                   10811:                               active   => 'Active',
                   10812:                               future   => 'Future',
                   10813:                             );
1.1121    raeburn  10814:         my (%nothide,@possdoms);
1.630     raeburn  10815:         if ($hidepriv) {
                   10816:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10817:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10818:                 if ($user !~ /:/) {
                   10819:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10820:                 } else {
                   10821:                     $nothide{$user} = 1;
                   10822:                 }
                   10823:             }
1.1121    raeburn  10824:             my @possdoms = ($cdom);
                   10825:             if ($coursehash{'checkforpriv'}) {
                   10826:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10827:             }
1.630     raeburn  10828:         }
1.439     raeburn  10829:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10830:             my $match = 0;
1.412     raeburn  10831:             my $secmatch = 0;
1.439     raeburn  10832:             my $status;
1.412     raeburn  10833:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10834:             $user =~ s/:$//;
1.439     raeburn  10835:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10836:             if ($end == -1 || $start == -1) {
                   10837:                 next;
                   10838:             }
                   10839:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10840:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10841:                 my ($uname,$udom) = split(/:/,$user);
                   10842:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10843:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10844:                         $secmatch = 1;
                   10845:                     } elsif ($usec eq '') {
1.420     albertel 10846:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10847:                             $secmatch = 1;
                   10848:                         }
                   10849:                     } else {
                   10850:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10851:                             $secmatch = 1;
                   10852:                         }
                   10853:                     }
                   10854:                     if (!$secmatch) {
                   10855:                         next;
                   10856:                     }
1.288     raeburn  10857:                 }
1.419     raeburn  10858:                 if ($usec eq '') {
                   10859:                     $usec = 'none';
                   10860:                 }
1.275     raeburn  10861:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10862:                     if ($hidepriv) {
1.1121    raeburn  10863:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10864:                             (!$nothide{$uname.':'.$udom})) {
                   10865:                             next;
                   10866:                         }
                   10867:                     }
1.503     raeburn  10868:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10869:                         $status = 'previous';
                   10870:                     } elsif ($start > $now) {
                   10871:                         $status = 'future';
                   10872:                     } else {
                   10873:                         $status = 'active';
                   10874:                     }
1.277     albertel 10875:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10876:                         if ($status eq $type) {
1.420     albertel 10877:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10878:                                 push(@{$$users{$role}{$user}},$type);
                   10879:                             }
1.288     raeburn  10880:                             $match = 1;
                   10881:                         }
                   10882:                     }
1.419     raeburn  10883:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10884:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10885: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10886:                         }
1.420     albertel 10887:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10888:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10889:                         }
1.609     raeburn  10890:                         if (ref($statushash) eq 'HASH') {
                   10891:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10892:                         }
1.275     raeburn  10893:                     }
                   10894:                 }
                   10895:             }
                   10896:         }
1.290     albertel 10897:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10898:             if ((defined($cdom)) && (defined($cnum))) {
                   10899:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10900:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10901:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10902:                     next if ($owner eq '');
                   10903:                     my ($ownername,$ownerdom);
                   10904:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10905:                         $ownername = $1;
                   10906:                         $ownerdom = $2;
                   10907:                     } else {
                   10908:                         $ownername = $owner;
                   10909:                         $ownerdom = $cdom;
                   10910:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10911:                     }
                   10912:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10913:                     if (defined($userdata) && 
1.609     raeburn  10914: 			!exists($$userdata{$owner})) {
                   10915: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10916:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10917:                             push(@{$seclists{$owner}},'none');
                   10918:                         }
                   10919:                         if (ref($statushash) eq 'HASH') {
                   10920:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10921:                         }
1.290     albertel 10922: 		    }
1.279     raeburn  10923:                 }
                   10924:             }
                   10925:         }
1.419     raeburn  10926:         foreach my $user (keys(%seclists)) {
                   10927:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10928:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10929:         }
1.275     raeburn  10930:     }
                   10931:     return;
                   10932: }
                   10933: 
1.288     raeburn  10934: sub get_user_info {
                   10935:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10936:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10937: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10938:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10939:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10940:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10941:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10942:     return;
                   10943: }
1.275     raeburn  10944: 
1.472     raeburn  10945: ###############################################
                   10946: 
                   10947: =pod
                   10948: 
                   10949: =item * &get_user_quota()
                   10950: 
1.1134    raeburn  10951: Retrieves quota assigned for storage of user files.
                   10952: Default is to report quota for portfolio files.
1.472     raeburn  10953: 
                   10954: Incoming parameters:
                   10955: 1. user's username
                   10956: 2. user's domain
1.1134    raeburn  10957: 3. quota name - portfolio, author, or course
1.1136    raeburn  10958:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10959: 4. crstype - official, unofficial, textbook, placement or community, 
                   10960:    if quota name is course
1.472     raeburn  10961: 
                   10962: Returns:
1.1163    raeburn  10963: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10964: 2. (Optional) Type of setting: custom or default
                   10965:    (individually assigned or default for user's 
                   10966:    institutional status).
                   10967: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10968:    or student - types as defined in localenroll::inst_usertypes 
                   10969:    for user's domain, which determines default quota for user.
                   10970: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10971: 
                   10972: If a value has been stored in the user's environment, 
1.536     raeburn  10973: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10974: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10975: 
                   10976: =cut
                   10977: 
                   10978: ###############################################
                   10979: 
                   10980: 
                   10981: sub get_user_quota {
1.1136    raeburn  10982:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10983:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10984:     if (!defined($udom)) {
                   10985:         $udom = $env{'user.domain'};
                   10986:     }
                   10987:     if (!defined($uname)) {
                   10988:         $uname = $env{'user.name'};
                   10989:     }
                   10990:     if (($udom eq '' || $uname eq '') ||
                   10991:         ($udom eq 'public') && ($uname eq 'public')) {
                   10992:         $quota = 0;
1.536     raeburn  10993:         $quotatype = 'default';
                   10994:         $defquota = 0; 
1.472     raeburn  10995:     } else {
1.536     raeburn  10996:         my $inststatus;
1.1134    raeburn  10997:         if ($quotaname eq 'course') {
                   10998:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10999:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11000:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11001:             } else {
                   11002:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11003:                 $quota = $cenv{'internal.uploadquota'};
                   11004:             }
1.536     raeburn  11005:         } else {
1.1134    raeburn  11006:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11007:                 if ($quotaname eq 'author') {
                   11008:                     $quota = $env{'environment.authorquota'};
                   11009:                 } else {
                   11010:                     $quota = $env{'environment.portfolioquota'};
                   11011:                 }
                   11012:                 $inststatus = $env{'environment.inststatus'};
                   11013:             } else {
                   11014:                 my %userenv = 
                   11015:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11016:                                          'authorquota','inststatus'],$udom,$uname);
                   11017:                 my ($tmp) = keys(%userenv);
                   11018:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11019:                     if ($quotaname eq 'author') {
                   11020:                         $quota = $userenv{'authorquota'};
                   11021:                     } else {
                   11022:                         $quota = $userenv{'portfolioquota'};
                   11023:                     }
                   11024:                     $inststatus = $userenv{'inststatus'};
                   11025:                 } else {
                   11026:                     undef(%userenv);
                   11027:                 }
                   11028:             }
                   11029:         }
                   11030:         if ($quota eq '' || wantarray) {
                   11031:             if ($quotaname eq 'course') {
                   11032:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11033:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11034:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11035:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11036:                     $defquota = $domdefs{$crstype.'quota'};
                   11037:                 }
                   11038:                 if ($defquota eq '') {
                   11039:                     $defquota = 500;
                   11040:                 }
1.1134    raeburn  11041:             } else {
                   11042:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11043:             }
                   11044:             if ($quota eq '') {
                   11045:                 $quota = $defquota;
                   11046:                 $quotatype = 'default';
                   11047:             } else {
                   11048:                 $quotatype = 'custom';
                   11049:             }
1.472     raeburn  11050:         }
                   11051:     }
1.536     raeburn  11052:     if (wantarray) {
                   11053:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11054:     } else {
                   11055:         return $quota;
                   11056:     }
1.472     raeburn  11057: }
                   11058: 
                   11059: ###############################################
                   11060: 
                   11061: =pod
                   11062: 
                   11063: =item * &default_quota()
                   11064: 
1.536     raeburn  11065: Retrieves default quota assigned for storage of user portfolio files,
                   11066: given an (optional) user's institutional status.
1.472     raeburn  11067: 
                   11068: Incoming parameters:
1.1142    raeburn  11069: 
1.472     raeburn  11070: 1. domain
1.536     raeburn  11071: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11072:    status types (e.g., faculty, staff, student etc.)
                   11073:    which apply to the user for whom the default is being retrieved.
                   11074:    If the institutional status string in undefined, the domain
1.1134    raeburn  11075:    default quota will be returned.
                   11076: 3.  quota name - portfolio, author, or course
                   11077:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11078: 
                   11079: Returns:
1.1142    raeburn  11080: 
1.1163    raeburn  11081: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11082: 2. (Optional) institutional type which determined the value of the
                   11083:    default quota.
1.472     raeburn  11084: 
                   11085: If a value has been stored in the domain's configuration db,
                   11086: it will return that, otherwise it returns 20 (for backwards 
                   11087: compatibility with domains which have not set up a configuration
1.1163    raeburn  11088: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11089: 
1.536     raeburn  11090: If the user's status includes multiple types (e.g., staff and student),
                   11091: the largest default quota which applies to the user determines the
                   11092: default quota returned.
                   11093: 
1.472     raeburn  11094: =cut
                   11095: 
                   11096: ###############################################
                   11097: 
                   11098: 
                   11099: sub default_quota {
1.1134    raeburn  11100:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11101:     my ($defquota,$settingstatus);
                   11102:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11103:                                             ['quotas'],$udom);
1.1134    raeburn  11104:     my $key = 'defaultquota';
                   11105:     if ($quotaname eq 'author') {
                   11106:         $key = 'authorquota';
                   11107:     }
1.622     raeburn  11108:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11109:         if ($inststatus ne '') {
1.765     raeburn  11110:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11111:             foreach my $item (@statuses) {
1.1134    raeburn  11112:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11113:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11114:                         if ($defquota eq '') {
1.1134    raeburn  11115:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11116:                             $settingstatus = $item;
1.1134    raeburn  11117:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11118:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11119:                             $settingstatus = $item;
                   11120:                         }
                   11121:                     }
1.1134    raeburn  11122:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11123:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11124:                         if ($defquota eq '') {
                   11125:                             $defquota = $quotahash{'quotas'}{$item};
                   11126:                             $settingstatus = $item;
                   11127:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11128:                             $defquota = $quotahash{'quotas'}{$item};
                   11129:                             $settingstatus = $item;
                   11130:                         }
1.536     raeburn  11131:                     }
                   11132:                 }
                   11133:             }
                   11134:         }
                   11135:         if ($defquota eq '') {
1.1134    raeburn  11136:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11137:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11138:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11139:                 $defquota = $quotahash{'quotas'}{'default'};
                   11140:             }
1.536     raeburn  11141:             $settingstatus = 'default';
1.1139    raeburn  11142:             if ($defquota eq '') {
                   11143:                 if ($quotaname eq 'author') {
                   11144:                     $defquota = 500;
                   11145:                 }
                   11146:             }
1.536     raeburn  11147:         }
                   11148:     } else {
                   11149:         $settingstatus = 'default';
1.1134    raeburn  11150:         if ($quotaname eq 'author') {
                   11151:             $defquota = 500;
                   11152:         } else {
                   11153:             $defquota = 20;
                   11154:         }
1.536     raeburn  11155:     }
                   11156:     if (wantarray) {
                   11157:         return ($defquota,$settingstatus);
1.472     raeburn  11158:     } else {
1.536     raeburn  11159:         return $defquota;
1.472     raeburn  11160:     }
                   11161: }
                   11162: 
1.1135    raeburn  11163: ###############################################
                   11164: 
                   11165: =pod
                   11166: 
1.1136    raeburn  11167: =item * &excess_filesize_warning()
1.1135    raeburn  11168: 
                   11169: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11170: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11171: space to be exceeded.
1.1136    raeburn  11172: 
                   11173: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11174: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11175: 
1.1165    raeburn  11176: Inputs: 7 
1.1136    raeburn  11177: 1. username or coursenum
1.1135    raeburn  11178: 2. domain
1.1136    raeburn  11179: 3. context ('author' or 'course')
1.1135    raeburn  11180: 4. filename of file for which action is being requested
                   11181: 5. filesize (kB) of file
                   11182: 6. action being taken: copy or upload.
1.1237    raeburn  11183: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11184: 
                   11185: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11186:          otherwise return null.
                   11187: 
                   11188: =back
1.1135    raeburn  11189: 
                   11190: =cut
                   11191: 
1.1136    raeburn  11192: sub excess_filesize_warning {
1.1165    raeburn  11193:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11194:     my $current_disk_usage = 0;
1.1165    raeburn  11195:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11196:     if ($context eq 'author') {
                   11197:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11198:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11199:     } else {
                   11200:         foreach my $subdir ('docs','supplemental') {
                   11201:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11202:         }
                   11203:     }
1.1135    raeburn  11204:     $disk_quota = int($disk_quota * 1000);
                   11205:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11206:         return '<p class="LC_warning">'.
1.1135    raeburn  11207:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11208:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11209:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11210:                             $disk_quota,$current_disk_usage).
                   11211:                '</p>';
                   11212:     }
                   11213:     return;
                   11214: }
                   11215: 
                   11216: ###############################################
                   11217: 
                   11218: 
1.1136    raeburn  11219: 
                   11220: 
1.384     raeburn  11221: sub get_secgrprole_info {
                   11222:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11223:     my %sections_count = &get_sections($cdom,$cnum);
                   11224:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11225:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11226:     my @groups = sort(keys(%curr_groups));
                   11227:     my $allroles = [];
                   11228:     my $rolehash;
                   11229:     my $accesshash = {
                   11230:                      active => 'Currently has access',
                   11231:                      future => 'Will have future access',
                   11232:                      previous => 'Previously had access',
                   11233:                   };
                   11234:     if ($needroles) {
                   11235:         $rolehash = {'all' => 'all'};
1.385     albertel 11236:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11237: 	if (&Apache::lonnet::error(%user_roles)) {
                   11238: 	    undef(%user_roles);
                   11239: 	}
                   11240:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11241:             my ($role)=split(/\:/,$item,2);
                   11242:             if ($role eq 'cr') { next; }
                   11243:             if ($role =~ /^cr/) {
                   11244:                 $$rolehash{$role} = (split('/',$role))[3];
                   11245:             } else {
                   11246:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11247:             }
                   11248:         }
                   11249:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11250:             push(@{$allroles},$key);
                   11251:         }
                   11252:         push (@{$allroles},'st');
                   11253:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11254:     }
                   11255:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11256: }
                   11257: 
1.555     raeburn  11258: sub user_picker {
1.1279    raeburn  11259:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11260:     my $currdom = $dom;
1.1253    raeburn  11261:     my @alldoms = &Apache::lonnet::all_domains();
                   11262:     if (@alldoms == 1) {
                   11263:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11264:                                                ['directorysrch'],$alldoms[0]);
                   11265:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11266:         my $showdom = $domdesc;
                   11267:         if ($showdom eq '') {
                   11268:             $showdom = $dom;
                   11269:         }
                   11270:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11271:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11272:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11273:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11274:             }
                   11275:         }
                   11276:     }
1.555     raeburn  11277:     my %curr_selected = (
                   11278:                         srchin => 'dom',
1.580     raeburn  11279:                         srchby => 'lastname',
1.555     raeburn  11280:                       );
                   11281:     my $srchterm;
1.625     raeburn  11282:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11283:         if ($srch->{'srchby'} ne '') {
                   11284:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11285:         }
                   11286:         if ($srch->{'srchin'} ne '') {
                   11287:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11288:         }
                   11289:         if ($srch->{'srchtype'} ne '') {
                   11290:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11291:         }
                   11292:         if ($srch->{'srchdomain'} ne '') {
                   11293:             $currdom = $srch->{'srchdomain'};
                   11294:         }
                   11295:         $srchterm = $srch->{'srchterm'};
                   11296:     }
1.1222    damieng  11297:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11298:                     'usr'       => 'Search criteria',
1.563     raeburn  11299:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11300:                     'uname'     => 'username',
                   11301:                     'lastname'  => 'last name',
1.555     raeburn  11302:                     'lastfirst' => 'last name, first name',
1.558     albertel 11303:                     'crs'       => 'in this course',
1.576     raeburn  11304:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11305:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11306:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11307:                     'exact'     => 'is',
                   11308:                     'contains'  => 'contains',
1.569     raeburn  11309:                     'begins'    => 'begins with',
1.1222    damieng  11310:                                        );
                   11311:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11312:                     'youm'      => "You must include some text to search for.",
                   11313:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11314:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11315:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11316:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11317:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11318:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11319:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11320:                                        );
1.1222    damieng  11321:     &html_escape(\%html_lt);
                   11322:     &js_escape(\%js_lt);
1.1255    raeburn  11323:     my $domform;
1.1277    raeburn  11324:     my $allow_blank = 1;
1.1255    raeburn  11325:     if ($fixeddom) {
1.1277    raeburn  11326:         $allow_blank = 0;
                   11327:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11328:     } else {
1.1287    raeburn  11329:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11330:         my ($trusted,$untrusted);
1.1287    raeburn  11331:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11332:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11333:         } elsif ($context eq 'author') {
1.1288    raeburn  11334:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11335:         } elsif ($context eq 'domain') {
1.1288    raeburn  11336:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11337:         }
1.1288    raeburn  11338:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11339:     }
1.563     raeburn  11340:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11341: 
                   11342:     my @srchins = ('crs','dom','alc','instd');
                   11343: 
                   11344:     foreach my $option (@srchins) {
                   11345:         # FIXME 'alc' option unavailable until 
                   11346:         #       loncreateuser::print_user_query_page()
                   11347:         #       has been completed.
                   11348:         next if ($option eq 'alc');
1.880     raeburn  11349:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11350:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11351:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11352:         if ($curr_selected{'srchin'} eq $option) {
                   11353:             $srchinsel .= ' 
1.1222    damieng  11354:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11355:         } else {
                   11356:             $srchinsel .= '
1.1222    damieng  11357:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11358:         }
1.555     raeburn  11359:     }
1.563     raeburn  11360:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11361: 
                   11362:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11363:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11364:         if ($curr_selected{'srchby'} eq $option) {
                   11365:             $srchbysel .= '
1.1222    damieng  11366:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11367:         } else {
                   11368:             $srchbysel .= '
1.1222    damieng  11369:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11370:          }
                   11371:     }
                   11372:     $srchbysel .= "\n  </select>\n";
                   11373: 
                   11374:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11375:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11376:         if ($curr_selected{'srchtype'} eq $option) {
                   11377:             $srchtypesel .= '
1.1222    damieng  11378:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11379:         } else {
                   11380:             $srchtypesel .= '
1.1222    damieng  11381:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11382:         }
                   11383:     }
                   11384:     $srchtypesel .= "\n  </select>\n";
                   11385: 
1.558     albertel 11386:     my ($newuserscript,$new_user_create);
1.994     raeburn  11387:     my $context_dom = $env{'request.role.domain'};
                   11388:     if ($context eq 'requestcrs') {
                   11389:         if ($env{'form.coursedom'} ne '') { 
                   11390:             $context_dom = $env{'form.coursedom'};
                   11391:         }
                   11392:     }
1.556     raeburn  11393:     if ($forcenewuser) {
1.576     raeburn  11394:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11395:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11396:                 if ($cancreate) {
                   11397:                     $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>';
                   11398:                 } else {
1.799     bisitz   11399:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11400:                     my %usertypetext = (
                   11401:                         official   => 'institutional',
                   11402:                         unofficial => 'non-institutional',
                   11403:                     );
1.799     bisitz   11404:                     $new_user_create = '<p class="LC_warning">'
                   11405:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11406:                                       .' '
                   11407:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11408:                                           ,'<a href="'.$helplink.'">','</a>')
                   11409:                                       .'</p><br />';
1.627     raeburn  11410:                 }
1.576     raeburn  11411:             }
                   11412:         }
                   11413: 
1.556     raeburn  11414:         $newuserscript = <<"ENDSCRIPT";
                   11415: 
1.570     raeburn  11416: function setSearch(createnew,callingForm) {
1.556     raeburn  11417:     if (createnew == 1) {
1.570     raeburn  11418:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11419:             if (callingForm.srchby.options[i].value == 'uname') {
                   11420:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11421:             }
                   11422:         }
1.570     raeburn  11423:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11424:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11425: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11426:             }
                   11427:         }
1.570     raeburn  11428:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11429:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11430:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11431:             }
                   11432:         }
1.570     raeburn  11433:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11434:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11435:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11436:             }
                   11437:         }
                   11438:     }
                   11439: }
                   11440: ENDSCRIPT
1.558     albertel 11441: 
1.556     raeburn  11442:     }
                   11443: 
1.555     raeburn  11444:     my $output = <<"END_BLOCK";
1.556     raeburn  11445: <script type="text/javascript">
1.824     bisitz   11446: // <![CDATA[
1.570     raeburn  11447: function validateEntry(callingForm) {
1.558     albertel 11448: 
1.556     raeburn  11449:     var checkok = 1;
1.558     albertel 11450:     var srchin;
1.570     raeburn  11451:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11452: 	if ( callingForm.srchin[i].checked ) {
                   11453: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11454: 	}
                   11455:     }
                   11456: 
1.570     raeburn  11457:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11458:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11459:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11460:     var srchterm =  callingForm.srchterm.value;
                   11461:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11462:     var msg = "";
                   11463: 
                   11464:     if (srchterm == "") {
                   11465:         checkok = 0;
1.1222    damieng  11466:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11467:     }
                   11468: 
1.569     raeburn  11469:     if (srchtype== 'begins') {
                   11470:         if (srchterm.length < 2) {
                   11471:             checkok = 0;
1.1222    damieng  11472:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11473:         }
                   11474:     }
                   11475: 
1.556     raeburn  11476:     if (srchtype== 'contains') {
                   11477:         if (srchterm.length < 3) {
                   11478:             checkok = 0;
1.1222    damieng  11479:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11480:         }
                   11481:     }
                   11482:     if (srchin == 'instd') {
                   11483:         if (srchdomain == '') {
                   11484:             checkok = 0;
1.1222    damieng  11485:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11486:         }
                   11487:     }
                   11488:     if (srchin == 'dom') {
                   11489:         if (srchdomain == '') {
                   11490:             checkok = 0;
1.1222    damieng  11491:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11492:         }
                   11493:     }
                   11494:     if (srchby == 'lastfirst') {
                   11495:         if (srchterm.indexOf(",") == -1) {
                   11496:             checkok = 0;
1.1222    damieng  11497:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11498:         }
                   11499:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11500:             checkok = 0;
1.1222    damieng  11501:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11502:         }
                   11503:     }
                   11504:     if (checkok == 0) {
1.1222    damieng  11505:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11506:         return;
                   11507:     }
                   11508:     if (checkok == 1) {
1.570     raeburn  11509:         callingForm.submit();
1.556     raeburn  11510:     }
                   11511: }
                   11512: 
                   11513: $newuserscript
                   11514: 
1.824     bisitz   11515: // ]]>
1.556     raeburn  11516: </script>
1.558     albertel 11517: 
                   11518: $new_user_create
                   11519: 
1.555     raeburn  11520: END_BLOCK
1.558     albertel 11521: 
1.876     raeburn  11522:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11523:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11524:                $domform.
                   11525:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11526:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11527:                $srchbysel.
                   11528:                $srchtypesel. 
                   11529:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11530:                $srchinsel.
                   11531:                &Apache::lonhtmlcommon::row_closure(1). 
                   11532:                &Apache::lonhtmlcommon::end_pick_box().
                   11533:                '<br />';
1.1253    raeburn  11534:     return ($output,1);
1.555     raeburn  11535: }
                   11536: 
1.612     raeburn  11537: sub user_rule_check {
1.615     raeburn  11538:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11539:     my ($response,%inst_response);
1.612     raeburn  11540:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11541:         if (keys(%{$usershash}) > 1) {
                   11542:             my (%by_username,%by_id,%userdoms);
                   11543:             my $checkid; 
                   11544:             if (ref($checks) eq 'HASH') {
                   11545:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11546:                     $checkid = 1;
                   11547:                 }
                   11548:             }
                   11549:             foreach my $user (keys(%{$usershash})) {
                   11550:                 my ($uname,$udom) = split(/:/,$user);
                   11551:                 if ($checkid) {
                   11552:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11553:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11554:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11555:                             $userdoms{$udom} = 1;
1.1227    raeburn  11556:                             if (ref($inst_results) eq 'HASH') {
                   11557:                                 $inst_results->{$uname.':'.$udom} = {};
                   11558:                             }
1.1226    raeburn  11559:                         }
                   11560:                     }
                   11561:                 } else {
                   11562:                     $by_username{$udom}{$uname} = 1;
                   11563:                     $userdoms{$udom} = 1;
1.1227    raeburn  11564:                     if (ref($inst_results) eq 'HASH') {
                   11565:                         $inst_results->{$uname.':'.$udom} = {};
                   11566:                     }
1.1226    raeburn  11567:                 }
                   11568:             }
                   11569:             foreach my $udom (keys(%userdoms)) {
                   11570:                 if (!$got_rules->{$udom}) {
                   11571:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11572:                                                              ['usercreation'],$udom);
                   11573:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11574:                         foreach my $item ('username','id') {
                   11575:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11576:                                 $$curr_rules{$udom}{$item} =
                   11577:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11578:                             }
                   11579:                         }
                   11580:                     }
                   11581:                     $got_rules->{$udom} = 1;
                   11582:                 }
1.612     raeburn  11583:             }
1.1226    raeburn  11584:             if ($checkid) {
                   11585:                 foreach my $udom (keys(%by_id)) {
                   11586:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11587:                     if ($outcome eq 'ok') {
1.1227    raeburn  11588:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11589:                             my $uname = $by_id{$udom}{$id};
                   11590:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11591:                         }
1.1226    raeburn  11592:                         if (ref($results) eq 'HASH') {
                   11593:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11594:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11595:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11596:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11597:                                 }
1.1226    raeburn  11598:                             }
                   11599:                         }
                   11600:                     }
1.612     raeburn  11601:                 }
1.615     raeburn  11602:             } else {
1.1226    raeburn  11603:                 foreach my $udom (keys(%by_username)) {
                   11604:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11605:                     if ($outcome eq 'ok') {
1.1227    raeburn  11606:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11607:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11608:                         }
1.1226    raeburn  11609:                         if (ref($results) eq 'HASH') {
                   11610:                             foreach my $uname (keys(%{$results})) {
                   11611:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11612:                             }
                   11613:                         }
                   11614:                     }
                   11615:                 }
1.612     raeburn  11616:             }
1.1226    raeburn  11617:         } elsif (keys(%{$usershash}) == 1) {
                   11618:             my $user = (keys(%{$usershash}))[0];
                   11619:             my ($uname,$udom) = split(/:/,$user);
                   11620:             if (($udom ne '') && ($uname ne '')) {
                   11621:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11622:                     if (ref($checks) eq 'HASH') {
                   11623:                         if (defined($checks->{'username'})) {
                   11624:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11625:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11626:                         } elsif (defined($checks->{'id'})) {
                   11627:                             if ($usershash->{$user}->{'id'} ne '') {
                   11628:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11629:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11630:                                                                   $usershash->{$user}->{'id'});
                   11631:                             } else {
                   11632:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11633:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11634:                             }
1.585     raeburn  11635:                         }
1.1226    raeburn  11636:                     } else {
                   11637:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11638:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11639:                        return;
                   11640:                     }
                   11641:                     if (!$got_rules->{$udom}) {
                   11642:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11643:                                                                  ['usercreation'],$udom);
                   11644:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11645:                             foreach my $item ('username','id') {
                   11646:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11647:                                    $$curr_rules{$udom}{$item} = 
                   11648:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11649:                                 }
                   11650:                             }
                   11651:                         }
                   11652:                         $got_rules->{$udom} = 1;
1.585     raeburn  11653:                     }
                   11654:                 }
1.1226    raeburn  11655:             } else {
                   11656:                 return;
                   11657:             }
                   11658:         } else {
                   11659:             return;
                   11660:         }
                   11661:         foreach my $user (keys(%{$usershash})) {
                   11662:             my ($uname,$udom) = split(/:/,$user);
                   11663:             next if (($udom eq '') || ($uname eq ''));
                   11664:             my $id;
1.1227    raeburn  11665:             if (ref($inst_results) eq 'HASH') {
                   11666:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11667:                     $id = $inst_results->{$user}->{'id'};
                   11668:                 }
                   11669:             }
                   11670:             if ($id eq '') { 
                   11671:                 if (ref($usershash->{$user})) {
                   11672:                     $id = $usershash->{$user}->{'id'};
                   11673:                 }
1.585     raeburn  11674:             }
1.612     raeburn  11675:             foreach my $item (keys(%{$checks})) {
                   11676:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11677:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11678:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11679:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11680:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11681:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11682:                                 if ($rule_check{$rule}) {
                   11683:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11684:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11685:                                         if (ref($inst_results) eq 'HASH') {
                   11686:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11687:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11688:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11689:                                                 } elsif ($item eq 'id') {
                   11690:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11691:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11692:                                                     }
1.615     raeburn  11693:                                                 }
1.612     raeburn  11694:                                             }
                   11695:                                         }
1.615     raeburn  11696:                                     }
                   11697:                                     last;
1.585     raeburn  11698:                                 }
                   11699:                             }
                   11700:                         }
                   11701:                     }
                   11702:                 }
                   11703:             }
                   11704:         }
                   11705:     }
1.612     raeburn  11706:     return;
                   11707: }
                   11708: 
                   11709: sub user_rule_formats {
                   11710:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11711:     my %text = ( 
                   11712:                  'username' => 'Usernames',
                   11713:                  'id'       => 'IDs',
                   11714:                );
                   11715:     my $output;
                   11716:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11717:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11718:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11719:             $output = '<br />'.
                   11720:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11721:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11722:                       ' <ul>';
1.612     raeburn  11723:             foreach my $rule (@{$ruleorder}) {
                   11724:                 if (ref($curr_rules) eq 'ARRAY') {
                   11725:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11726:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11727:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11728:                                         $rules->{$rule}{'desc'}.'</li>';
                   11729:                         }
                   11730:                     }
                   11731:                 }
                   11732:             }
                   11733:             $output .= '</ul>';
                   11734:         }
                   11735:     }
                   11736:     return $output;
                   11737: }
                   11738: 
                   11739: sub instrule_disallow_msg {
1.615     raeburn  11740:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11741:     my $response;
                   11742:     my %text = (
                   11743:                   item   => 'username',
                   11744:                   items  => 'usernames',
                   11745:                   match  => 'matches',
                   11746:                   do     => 'does',
                   11747:                   action => 'a username',
                   11748:                   one    => 'one',
                   11749:                );
                   11750:     if ($count > 1) {
                   11751:         $text{'item'} = 'usernames';
                   11752:         $text{'match'} ='match';
                   11753:         $text{'do'} = 'do';
                   11754:         $text{'action'} = 'usernames',
                   11755:         $text{'one'} = 'ones';
                   11756:     }
                   11757:     if ($checkitem eq 'id') {
                   11758:         $text{'items'} = 'IDs';
                   11759:         $text{'item'} = 'ID';
                   11760:         $text{'action'} = 'an ID';
1.615     raeburn  11761:         if ($count > 1) {
                   11762:             $text{'item'} = 'IDs';
                   11763:             $text{'action'} = 'IDs';
                   11764:         }
1.612     raeburn  11765:     }
1.674     bisitz   11766:     $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  11767:     if ($mode eq 'upload') {
                   11768:         if ($checkitem eq 'username') {
                   11769:             $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'}.");
                   11770:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11771:             $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  11772:         }
1.669     raeburn  11773:     } elsif ($mode eq 'selfcreate') {
                   11774:         if ($checkitem eq 'id') {
                   11775:             $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.");
                   11776:         }
1.615     raeburn  11777:     } else {
                   11778:         if ($checkitem eq 'username') {
                   11779:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11780:         } elsif ($checkitem eq 'id') {
                   11781:             $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.");
                   11782:         }
1.612     raeburn  11783:     }
                   11784:     return $response;
1.585     raeburn  11785: }
                   11786: 
1.624     raeburn  11787: sub personal_data_fieldtitles {
                   11788:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11789:                         id => 'Student/Employee ID',
                   11790:                         permanentemail => 'E-mail address',
                   11791:                         lastname => 'Last Name',
                   11792:                         firstname => 'First Name',
                   11793:                         middlename => 'Middle Name',
                   11794:                         generation => 'Generation',
                   11795:                         gen => 'Generation',
1.765     raeburn  11796:                         inststatus => 'Affiliation',
1.624     raeburn  11797:                    );
                   11798:     return %fieldtitles;
                   11799: }
                   11800: 
1.642     raeburn  11801: sub sorted_inst_types {
                   11802:     my ($dom) = @_;
1.1185    raeburn  11803:     my ($usertypes,$order);
                   11804:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11805:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11806:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11807:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11808:     } else {
                   11809:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11810:     }
1.642     raeburn  11811:     my $othertitle = &mt('All users');
                   11812:     if ($env{'request.course.id'}) {
1.668     raeburn  11813:         $othertitle  = &mt('Any users');
1.642     raeburn  11814:     }
                   11815:     my @types;
                   11816:     if (ref($order) eq 'ARRAY') {
                   11817:         @types = @{$order};
                   11818:     }
                   11819:     if (@types == 0) {
                   11820:         if (ref($usertypes) eq 'HASH') {
                   11821:             @types = sort(keys(%{$usertypes}));
                   11822:         }
                   11823:     }
                   11824:     if (keys(%{$usertypes}) > 0) {
                   11825:         $othertitle = &mt('Other users');
                   11826:     }
                   11827:     return ($othertitle,$usertypes,\@types);
                   11828: }
                   11829: 
1.645     raeburn  11830: sub get_institutional_codes {
1.1361    raeburn  11831:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11832: # Get complete list of course sections to update
                   11833:     my @currsections = ();
                   11834:     my @currxlists = ();
1.1361    raeburn  11835:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11836:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11837:     my $crskey = $crs.':'.$coursecode;
                   11838:     @{$unclutteredsec{$crskey}} = ();
                   11839:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11840: 
                   11841:     if ($$settings{'internal.sectionnums'} ne '') {
                   11842:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11843:     }
                   11844: 
                   11845:     if ($$settings{'internal.crosslistings'} ne '') {
                   11846:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11847:     }
                   11848: 
                   11849:     if (@currxlists > 0) {
1.1361    raeburn  11850:         foreach my $xl (@currxlists) {
                   11851:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11852:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11853:                     push(@{$allcourses},$1);
1.645     raeburn  11854:                     $$LC_code{$1} = $2;
                   11855:                 }
                   11856:             }
                   11857:         }
                   11858:     }
1.1361    raeburn  11859: 
1.645     raeburn  11860:     if (@currsections > 0) {
1.1361    raeburn  11861:         foreach my $sec (@currsections) {
                   11862:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11863:                 my $instsec = $1;
1.645     raeburn  11864:                 my $lc_sec = $2;
1.1361    raeburn  11865:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11866:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11867:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11868:                 }
                   11869:             }
                   11870:         }
                   11871:     }
                   11872: 
                   11873:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11874:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11875:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11876:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11877:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11878:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11879:                     push(@{$allcourses},$sec);
1.1361    raeburn  11880:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11881:                 }
                   11882:             }
                   11883:         }
                   11884:     }
                   11885:     return;
                   11886: }
                   11887: 
1.971     raeburn  11888: sub get_standard_codeitems {
                   11889:     return ('Year','Semester','Department','Number','Section');
                   11890: }
                   11891: 
1.112     bowersj2 11892: =pod
                   11893: 
1.780     raeburn  11894: =head1 Slot Helpers
                   11895: 
                   11896: =over 4
                   11897: 
                   11898: =item * sorted_slots()
                   11899: 
1.1040    raeburn  11900: Sorts an array of slot names in order of an optional sort key,
                   11901: default sort is by slot start time (earliest first). 
1.780     raeburn  11902: 
                   11903: Inputs:
                   11904: 
                   11905: =over 4
                   11906: 
                   11907: slotsarr  - Reference to array of unsorted slot names.
                   11908: 
                   11909: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11910: 
1.1040    raeburn  11911: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11912: 
1.549     albertel 11913: =back
                   11914: 
1.780     raeburn  11915: Returns:
                   11916: 
                   11917: =over 4
                   11918: 
1.1040    raeburn  11919: sorted   - An array of slot names sorted by a specified sort key 
                   11920:            (default sort key is start time of the slot).
1.780     raeburn  11921: 
                   11922: =back
                   11923: 
                   11924: =cut
                   11925: 
                   11926: 
                   11927: sub sorted_slots {
1.1040    raeburn  11928:     my ($slotsarr,$slots,$sortkey) = @_;
                   11929:     if ($sortkey eq '') {
                   11930:         $sortkey = 'starttime';
                   11931:     }
1.780     raeburn  11932:     my @sorted;
                   11933:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11934:         @sorted =
                   11935:             sort {
                   11936:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11937:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11938:                      }
                   11939:                      if (ref($slots->{$a})) { return -1;}
                   11940:                      if (ref($slots->{$b})) { return 1;}
                   11941:                      return 0;
                   11942:                  } @{$slotsarr};
                   11943:     }
                   11944:     return @sorted;
                   11945: }
                   11946: 
1.1040    raeburn  11947: =pod
                   11948: 
                   11949: =item * get_future_slots()
                   11950: 
                   11951: Inputs:
                   11952: 
                   11953: =over 4
                   11954: 
                   11955: cnum - course number
                   11956: 
                   11957: cdom - course domain
                   11958: 
                   11959: now - current UNIX time
                   11960: 
                   11961: symb - optional symb
                   11962: 
                   11963: =back
                   11964: 
                   11965: Returns:
                   11966: 
                   11967: =over 4
                   11968: 
                   11969: sorted_reservable - ref to array of student_schedulable slots currently 
                   11970:                     reservable, ordered by end date of reservation period.
                   11971: 
                   11972: reservable_now - ref to hash of student_schedulable slots currently
                   11973:                  reservable.
                   11974: 
                   11975:     Keys in inner hash are:
                   11976:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11977:     (b) endreserve: end date of reservation period.
                   11978:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11979:         selected.
1.1040    raeburn  11980: 
                   11981: sorted_future - ref to array of student_schedulable slots reservable in
                   11982:                 the future, ordered by start date of reservation period.
                   11983: 
                   11984: future_reservable - ref to hash of student_schedulable slots reservable
                   11985:                     in the future.
                   11986: 
                   11987:     Keys in inner hash are:
                   11988:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11989:     (b) startreserve: start date of reservation period.
                   11990:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11991:         selected.
1.1040    raeburn  11992: 
                   11993: =back
                   11994: 
                   11995: =cut
                   11996: 
                   11997: sub get_future_slots {
                   11998:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11999:     my $map;
                   12000:     if ($symb) {
                   12001:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12002:     }
1.1040    raeburn  12003:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12004:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12005:     foreach my $slot (keys(%slots)) {
                   12006:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12007:         if ($symb) {
1.1229    raeburn  12008:             if ($slots{$slot}->{'symb'} ne '') {
                   12009:                 my $canuse;
                   12010:                 my %oksymbs;
                   12011:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12012:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12013:                 if ($oksymbs{$symb}) {
                   12014:                     $canuse = 1;
                   12015:                 } else {
                   12016:                     foreach my $item (@slotsymbs) {
                   12017:                         if ($item =~ /\.(page|sequence)$/) {
                   12018:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12019:                             if (($map ne '') && ($map eq $sloturl)) {
                   12020:                                 $canuse = 1;
                   12021:                                 last;
                   12022:                             }
                   12023:                         }
                   12024:                     }
                   12025:                 }
                   12026:                 next unless ($canuse);
                   12027:             }
1.1040    raeburn  12028:         }
                   12029:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12030:             ($slots{$slot}->{'endtime'} > $now)) {
                   12031:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12032:                 my $userallowed = 0;
                   12033:                 if ($slots{$slot}->{'allowedsections'}) {
                   12034:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12035:                     if (!defined($env{'request.role.sec'})
                   12036:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12037:                         $userallowed=1;
                   12038:                     } else {
                   12039:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12040:                             $userallowed=1;
                   12041:                         }
                   12042:                     }
                   12043:                     unless ($userallowed) {
                   12044:                         if (defined($env{'request.course.groups'})) {
                   12045:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12046:                             foreach my $group (@groups) {
                   12047:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12048:                                     $userallowed=1;
                   12049:                                     last;
                   12050:                                 }
                   12051:                             }
                   12052:                         }
                   12053:                     }
                   12054:                 }
                   12055:                 if ($slots{$slot}->{'allowedusers'}) {
                   12056:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12057:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12058:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12059:                         $userallowed = 1;
                   12060:                     }
                   12061:                 }
                   12062:                 next unless($userallowed);
                   12063:             }
                   12064:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12065:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12066:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12067:             my $uniqueperiod;
                   12068:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12069:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12070:             }
1.1040    raeburn  12071:             if (($startreserve < $now) &&
                   12072:                 (!$endreserve || $endreserve > $now)) {
                   12073:                 my $lastres = $endreserve;
                   12074:                 if (!$lastres) {
                   12075:                     $lastres = $slots{$slot}->{'starttime'};
                   12076:                 }
                   12077:                 $reservable_now{$slot} = {
                   12078:                                            symb       => $symb,
1.1250    raeburn  12079:                                            endreserve => $lastres,
                   12080:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12081:                                          };
                   12082:             } elsif (($startreserve > $now) &&
                   12083:                      (!$endreserve || $endreserve > $startreserve)) {
                   12084:                 $future_reservable{$slot} = {
                   12085:                                               symb         => $symb,
1.1250    raeburn  12086:                                               startreserve => $startreserve,
                   12087:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12088:                                             };
                   12089:             }
                   12090:         }
                   12091:     }
                   12092:     my @unsorted_reservable = keys(%reservable_now);
                   12093:     if (@unsorted_reservable > 0) {
                   12094:         @sorted_reservable = 
                   12095:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12096:     }
                   12097:     my @unsorted_future = keys(%future_reservable);
                   12098:     if (@unsorted_future > 0) {
                   12099:         @sorted_future =
                   12100:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12101:     }
                   12102:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12103: }
1.780     raeburn  12104: 
                   12105: =pod
                   12106: 
1.1057    foxr     12107: =back
                   12108: 
1.549     albertel 12109: =head1 HTTP Helpers
                   12110: 
                   12111: =over 4
                   12112: 
1.648     raeburn  12113: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12114: 
1.258     albertel 12115: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12116: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12117: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12118: 
                   12119: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12120: $possible_names is an ref to an array of form element names.  As an example:
                   12121: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12122: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12123: 
                   12124: =cut
1.1       albertel 12125: 
1.6       albertel 12126: sub get_unprocessed_cgi {
1.25      albertel 12127:   my ($query,$possible_names)= @_;
1.26      matthew  12128:   # $Apache::lonxml::debug=1;
1.356     albertel 12129:   foreach my $pair (split(/&/,$query)) {
                   12130:     my ($name, $value) = split(/=/,$pair);
1.369     www      12131:     $name = &unescape($name);
1.25      albertel 12132:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12133:       $value =~ tr/+/ /;
                   12134:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12135:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12136:     }
1.16      harris41 12137:   }
1.6       albertel 12138: }
                   12139: 
1.112     bowersj2 12140: =pod
                   12141: 
1.648     raeburn  12142: =item * &cacheheader() 
1.112     bowersj2 12143: 
                   12144: returns cache-controlling header code
                   12145: 
                   12146: =cut
                   12147: 
1.7       albertel 12148: sub cacheheader {
1.258     albertel 12149:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12150:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12151:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12152:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12153:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12154:     return $output;
1.7       albertel 12155: }
                   12156: 
1.112     bowersj2 12157: =pod
                   12158: 
1.648     raeburn  12159: =item * &no_cache($r) 
1.112     bowersj2 12160: 
                   12161: specifies header code to not have cache
                   12162: 
                   12163: =cut
                   12164: 
1.9       albertel 12165: sub no_cache {
1.216     albertel 12166:     my ($r) = @_;
                   12167:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12168: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12169:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12170:     $r->no_cache(1);
                   12171:     $r->header_out("Expires" => $date);
                   12172:     $r->header_out("Pragma" => "no-cache");
1.123     www      12173: }
                   12174: 
                   12175: sub content_type {
1.181     albertel 12176:     my ($r,$type,$charset) = @_;
1.299     foxr     12177:     if ($r) {
                   12178: 	#  Note that printout.pl calls this with undef for $r.
                   12179: 	&no_cache($r);
                   12180:     }
1.258     albertel 12181:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12182:     unless ($charset) {
                   12183: 	$charset=&Apache::lonlocal::current_encoding;
                   12184:     }
                   12185:     if ($charset) { $type.='; charset='.$charset; }
                   12186:     if ($r) {
                   12187: 	$r->content_type($type);
                   12188:     } else {
                   12189: 	print("Content-type: $type\n\n");
                   12190:     }
1.9       albertel 12191: }
1.25      albertel 12192: 
1.112     bowersj2 12193: =pod
                   12194: 
1.648     raeburn  12195: =item * &add_to_env($name,$value) 
1.112     bowersj2 12196: 
1.258     albertel 12197: adds $name to the %env hash with value
1.112     bowersj2 12198: $value, if $name already exists, the entry is converted to an array
                   12199: reference and $value is added to the array.
                   12200: 
                   12201: =cut
                   12202: 
1.25      albertel 12203: sub add_to_env {
                   12204:   my ($name,$value)=@_;
1.258     albertel 12205:   if (defined($env{$name})) {
                   12206:     if (ref($env{$name})) {
1.25      albertel 12207:       #already have multiple values
1.258     albertel 12208:       push(@{ $env{$name} },$value);
1.25      albertel 12209:     } else {
                   12210:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12211:       my $first=$env{$name};
                   12212:       undef($env{$name});
                   12213:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12214:     }
                   12215:   } else {
1.258     albertel 12216:     $env{$name}=$value;
1.25      albertel 12217:   }
1.31      albertel 12218: }
1.149     albertel 12219: 
                   12220: =pod
                   12221: 
1.648     raeburn  12222: =item * &get_env_multiple($name) 
1.149     albertel 12223: 
1.258     albertel 12224: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12225: values may be defined and end up as an array ref.
                   12226: 
                   12227: returns an array of values
                   12228: 
                   12229: =cut
                   12230: 
                   12231: sub get_env_multiple {
                   12232:     my ($name) = @_;
                   12233:     my @values;
1.258     albertel 12234:     if (defined($env{$name})) {
1.149     albertel 12235:         # exists is it an array
1.258     albertel 12236:         if (ref($env{$name})) {
                   12237:             @values=@{ $env{$name} };
1.149     albertel 12238:         } else {
1.258     albertel 12239:             $values[0]=$env{$name};
1.149     albertel 12240:         }
                   12241:     }
                   12242:     return(@values);
                   12243: }
                   12244: 
1.1249    damieng  12245: # Looks at given dependencies, and returns something depending on the context.
                   12246: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12247: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12248: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12249: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12250: # $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.
                   12251: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12252: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12253: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12254: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12255: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12256: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12257: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12258: # @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)
                   12259: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12260: sub ask_for_embedded_content {
1.1249    damieng  12261:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12262:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12263:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12264:         %currsubfile,%unused,$rem);
1.1071    raeburn  12265:     my $counter = 0;
                   12266:     my $numnew = 0;
1.987     raeburn  12267:     my $numremref = 0;
                   12268:     my $numinvalid = 0;
                   12269:     my $numpathchg = 0;
                   12270:     my $numexisting = 0;
1.1071    raeburn  12271:     my $numunused = 0;
                   12272:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12273:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12274:     my $heading = &mt('Upload embedded files');
                   12275:     my $buttontext = &mt('Upload');
                   12276: 
1.1249    damieng  12277:     # fills these variables based on the context:
                   12278:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12279:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12280:     if ($env{'request.course.id'}) {
1.1123    raeburn  12281:         if ($actionurl eq '/adm/dependencies') {
                   12282:             $navmap = Apache::lonnavmaps::navmap->new();
                   12283:         }
                   12284:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12285:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12286:     }
1.1123    raeburn  12287:     if (($actionurl eq '/adm/portfolio') || 
                   12288:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12289:         my $current_path='/';
                   12290:         if ($env{'form.currentpath'}) {
                   12291:             $current_path = $env{'form.currentpath'};
                   12292:         }
                   12293:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12294:             $udom = $cdom;
                   12295:             $uname = $cnum;
1.984     raeburn  12296:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12297:         } else {
                   12298:             $udom = $env{'user.domain'};
                   12299:             $uname = $env{'user.name'};
                   12300:             $url = '/userfiles/portfolio';
                   12301:         }
1.987     raeburn  12302:         $toplevel = $url.'/';
1.984     raeburn  12303:         $url .= $current_path;
                   12304:         $getpropath = 1;
1.987     raeburn  12305:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12306:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12307:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12308:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12309:         $toplevel = $url;
1.984     raeburn  12310:         if ($rest ne '') {
1.987     raeburn  12311:             $url .= $rest;
                   12312:         }
                   12313:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12314:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12315:             $url = $args->{'docs_url'};
                   12316:             $toplevel = $url;
1.1084    raeburn  12317:             if ($args->{'context'} eq 'paste') {
                   12318:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12319:                 ($path) = 
                   12320:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12321:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12322:                 $fileloc =~ s{^/}{};
                   12323:             }
1.1071    raeburn  12324:         }
1.1084    raeburn  12325:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12326:         if ($env{'request.course.id'} ne '') {
                   12327:             if (ref($args) eq 'HASH') {
                   12328:                 $url = $args->{'docs_url'};
                   12329:                 $title = $args->{'docs_title'};
1.1126    raeburn  12330:                 $toplevel = $url; 
                   12331:                 unless ($toplevel =~ m{^/}) {
                   12332:                     $toplevel = "/$url";
                   12333:                 }
1.1085    raeburn  12334:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12335:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12336:                     $path = $1;
                   12337:                 } else {
                   12338:                     ($path) =
                   12339:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12340:                 }
1.1195    raeburn  12341:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12342:                     $fileloc = $toplevel;
                   12343:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12344:                     my ($udom,$uname,$fname) =
                   12345:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12346:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12347:                 } else {
                   12348:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12349:                 }
1.1071    raeburn  12350:                 $fileloc =~ s{^/}{};
                   12351:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12352:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12353:             }
1.987     raeburn  12354:         }
1.1123    raeburn  12355:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12356:         $udom = $cdom;
                   12357:         $uname = $cnum;
                   12358:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12359:         $toplevel = $url;
                   12360:         $path = $url;
                   12361:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12362:         $fileloc =~ s{^/}{};
1.987     raeburn  12363:     }
1.1249    damieng  12364:     
                   12365:     # parses the dependency paths to get some info
                   12366:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12367:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12368:     # (will be completed later)
                   12369:     # $mapping:
                   12370:     #   for external URLs: external URL -> external URL
                   12371:     #   for relative paths: clean path -> original path
                   12372:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12373:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12374:     foreach my $file (keys(%{$allfiles})) {
                   12375:         my $embed_file;
                   12376:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12377:             $embed_file = $1;
                   12378:         } else {
                   12379:             $embed_file = $file;
                   12380:         }
1.1158    raeburn  12381:         my ($absolutepath,$cleaned_file);
                   12382:         if ($embed_file =~ m{^\w+://}) {
                   12383:             $cleaned_file = $embed_file;
1.1147    raeburn  12384:             $newfiles{$cleaned_file} = 1;
                   12385:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12386:         } else {
1.1158    raeburn  12387:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12388:             if ($embed_file =~ m{^/}) {
                   12389:                 $absolutepath = $embed_file;
                   12390:             }
1.1147    raeburn  12391:             if ($cleaned_file =~ m{/}) {
                   12392:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12393:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12394:                 my $item = $fname;
                   12395:                 if ($path ne '') {
                   12396:                     $item = $path.'/'.$fname;
                   12397:                     $subdependencies{$path}{$fname} = 1;
                   12398:                 } else {
                   12399:                     $dependencies{$item} = 1;
                   12400:                 }
                   12401:                 if ($absolutepath) {
                   12402:                     $mapping{$item} = $absolutepath;
                   12403:                 } else {
                   12404:                     $mapping{$item} = $embed_file;
                   12405:                 }
                   12406:             } else {
                   12407:                 $dependencies{$embed_file} = 1;
                   12408:                 if ($absolutepath) {
1.1147    raeburn  12409:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12410:                 } else {
1.1147    raeburn  12411:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12412:                 }
                   12413:             }
1.984     raeburn  12414:         }
                   12415:     }
1.1249    damieng  12416:     
                   12417:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12418:     # and lists
                   12419:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12420:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12421:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12422:     #                                    the path had to be cleaned up
                   12423:     # $existing: hash clean path -> 1 if the file exists
                   12424:     # $numexisting: number of keys in $existing
                   12425:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12426:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12427:     #                                      dependency subdirectories that are
                   12428:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12429:     my $dirptr = 16384;
1.984     raeburn  12430:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12431:         $currsubfile{$path} = {};
1.1123    raeburn  12432:         if (($actionurl eq '/adm/portfolio') || 
                   12433:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12434:             my ($sublistref,$listerror) =
                   12435:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12436:             if (ref($sublistref) eq 'ARRAY') {
                   12437:                 foreach my $line (@{$sublistref}) {
                   12438:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12439:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12440:                 }
1.984     raeburn  12441:             }
1.987     raeburn  12442:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12443:             if (opendir(my $dir,$url.'/'.$path)) {
                   12444:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12445:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12446:             }
1.1084    raeburn  12447:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12448:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12449:                   ($args->{'context'} eq 'paste')) ||
                   12450:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12451:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12452:                 my $dir;
                   12453:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12454:                     $dir = $fileloc;
                   12455:                 } else {
                   12456:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12457:                 }
1.1071    raeburn  12458:                 if ($dir ne '') {
                   12459:                     my ($sublistref,$listerror) =
                   12460:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12461:                     if (ref($sublistref) eq 'ARRAY') {
                   12462:                         foreach my $line (@{$sublistref}) {
                   12463:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12464:                                 undef,$mtime)=split(/\&/,$line,12);
                   12465:                             unless (($testdir&$dirptr) ||
                   12466:                                     ($file_name =~ /^\.\.?$/)) {
                   12467:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12468:                             }
                   12469:                         }
                   12470:                     }
                   12471:                 }
1.984     raeburn  12472:             }
                   12473:         }
                   12474:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12475:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12476:                 my $item = $path.'/'.$file;
                   12477:                 unless ($mapping{$item} eq $item) {
                   12478:                     $pathchanges{$item} = 1;
                   12479:                 }
                   12480:                 $existing{$item} = 1;
                   12481:                 $numexisting ++;
                   12482:             } else {
                   12483:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12484:             }
                   12485:         }
1.1071    raeburn  12486:         if ($actionurl eq '/adm/dependencies') {
                   12487:             foreach my $path (keys(%currsubfile)) {
                   12488:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12489:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12490:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12491:                              next if (($rem ne '') &&
                   12492:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12493:                                        (ref($navmap) &&
                   12494:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12495:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12496:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12497:                              $unused{$path.'/'.$file} = 1; 
                   12498:                          }
                   12499:                     }
                   12500:                 }
                   12501:             }
                   12502:         }
1.984     raeburn  12503:     }
1.1249    damieng  12504:     
                   12505:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12506:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12507:     my %currfile;
1.1123    raeburn  12508:     if (($actionurl eq '/adm/portfolio') ||
                   12509:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12510:         my ($dirlistref,$listerror) =
                   12511:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12512:         if (ref($dirlistref) eq 'ARRAY') {
                   12513:             foreach my $line (@{$dirlistref}) {
                   12514:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12515:                 $currfile{$file_name} = 1;
                   12516:             }
1.984     raeburn  12517:         }
1.987     raeburn  12518:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12519:         if (opendir(my $dir,$url)) {
1.987     raeburn  12520:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12521:             map {$currfile{$_} = 1;} @dir_list;
                   12522:         }
1.1084    raeburn  12523:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12524:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12525:               ($args->{'context'} eq 'paste')) ||
                   12526:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12527:         if ($env{'request.course.id'} ne '') {
                   12528:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12529:             if ($dir ne '') {
                   12530:                 my ($dirlistref,$listerror) =
                   12531:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12532:                 if (ref($dirlistref) eq 'ARRAY') {
                   12533:                     foreach my $line (@{$dirlistref}) {
                   12534:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12535:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12536:                         unless (($testdir&$dirptr) ||
                   12537:                                 ($file_name =~ /^\.\.?$/)) {
                   12538:                             $currfile{$file_name} = [$size,$mtime];
                   12539:                         }
                   12540:                     }
                   12541:                 }
                   12542:             }
                   12543:         }
1.984     raeburn  12544:     }
1.1249    damieng  12545:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12546:     # are not in subdirectories, using $currfile
1.984     raeburn  12547:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12548:         if (exists($currfile{$file})) {
1.987     raeburn  12549:             unless ($mapping{$file} eq $file) {
                   12550:                 $pathchanges{$file} = 1;
                   12551:             }
                   12552:             $existing{$file} = 1;
                   12553:             $numexisting ++;
                   12554:         } else {
1.984     raeburn  12555:             $newfiles{$file} = 1;
                   12556:         }
                   12557:     }
1.1071    raeburn  12558:     foreach my $file (keys(%currfile)) {
                   12559:         unless (($file eq $filename) ||
                   12560:                 ($file eq $filename.'.bak') ||
                   12561:                 ($dependencies{$file})) {
1.1085    raeburn  12562:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12563:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12564:                     next if (($rem ne '') &&
                   12565:                              (($env{"httpref.$rem".$file} ne '') ||
                   12566:                               (ref($navmap) &&
                   12567:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12568:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12569:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12570:                 }
1.1085    raeburn  12571:             }
1.1071    raeburn  12572:             $unused{$file} = 1;
                   12573:         }
                   12574:     }
1.1249    damieng  12575:     
                   12576:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12577:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12578:         ($args->{'context'} eq 'paste')) {
                   12579:         $counter = scalar(keys(%existing));
                   12580:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12581:         return ($output,$counter,$numpathchg,\%existing);
                   12582:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12583:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12584:         $counter = scalar(keys(%existing));
                   12585:         $numpathchg = scalar(keys(%pathchanges));
                   12586:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12587:     }
1.1249    damieng  12588:     
                   12589:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12590:     
                   12591:     # $upload_output: missing dependencies (with upload form)
                   12592:     # $modify_output: uploaded dependencies (in use)
                   12593:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12594:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12595:         if ($actionurl eq '/adm/dependencies') {
                   12596:             next if ($embed_file =~ m{^\w+://});
                   12597:         }
1.660     raeburn  12598:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12599:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12600:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12601:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12602:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12603:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12604:         }
1.1123    raeburn  12605:         $upload_output .= '</td>';
1.1071    raeburn  12606:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12607:             $upload_output.='<td align="right">'.
                   12608:                             '<span class="LC_info LC_fontsize_medium">'.
                   12609:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12610:             $numremref++;
1.660     raeburn  12611:         } elsif ($args->{'error_on_invalid_names'}
                   12612:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12613:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12614:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12615:             $numinvalid++;
1.660     raeburn  12616:         } else {
1.1123    raeburn  12617:             $upload_output .= '<td>'.
                   12618:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12619:                                                      $embed_file,\%mapping,
1.1071    raeburn  12620:                                                      $allfiles,$codebase,'upload');
                   12621:             $counter ++;
                   12622:             $numnew ++;
1.987     raeburn  12623:         }
                   12624:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12625:     }
                   12626:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12627:         if ($actionurl eq '/adm/dependencies') {
                   12628:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12629:             $modify_output .= &start_data_table_row().
                   12630:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12631:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12632:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12633:                               '<td>'.$size.'</td>'.
                   12634:                               '<td>'.$mtime.'</td>'.
                   12635:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12636:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12637:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12638:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12639:                               &embedded_file_element('upload_embedded',$counter,
                   12640:                                                      $embed_file,\%mapping,
                   12641:                                                      $allfiles,$codebase,'modify').
                   12642:                               '</div></td>'.
                   12643:                               &end_data_table_row()."\n";
                   12644:             $counter ++;
                   12645:         } else {
                   12646:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12647:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12648:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12649:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12650:                               &Apache::loncommon::end_data_table_row()."\n";
                   12651:         }
                   12652:     }
                   12653:     my $delidx = $counter;
                   12654:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12655:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12656:         $delete_output .= &start_data_table_row().
                   12657:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12658:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12659:                           '<td>'.$size.'</td>'.
                   12660:                           '<td>'.$mtime.'</td>'.
                   12661:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12662:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12663:                           &embedded_file_element('upload_embedded',$delidx,
                   12664:                                                  $oldfile,\%mapping,$allfiles,
                   12665:                                                  $codebase,'delete').'</td>'.
                   12666:                           &end_data_table_row()."\n"; 
                   12667:         $numunused ++;
                   12668:         $delidx ++;
1.987     raeburn  12669:     }
                   12670:     if ($upload_output) {
                   12671:         $upload_output = &start_data_table().
                   12672:                          $upload_output.
                   12673:                          &end_data_table()."\n";
                   12674:     }
1.1071    raeburn  12675:     if ($modify_output) {
                   12676:         $modify_output = &start_data_table().
                   12677:                          &start_data_table_header_row().
                   12678:                          '<th>'.&mt('File').'</th>'.
                   12679:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12680:                          '<th>'.&mt('Modified').'</th>'.
                   12681:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12682:                          &end_data_table_header_row().
                   12683:                          $modify_output.
                   12684:                          &end_data_table()."\n";
                   12685:     }
                   12686:     if ($delete_output) {
                   12687:         $delete_output = &start_data_table().
                   12688:                          &start_data_table_header_row().
                   12689:                          '<th>'.&mt('File').'</th>'.
                   12690:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12691:                          '<th>'.&mt('Modified').'</th>'.
                   12692:                          '<th>'.&mt('Delete?').'</th>'.
                   12693:                          &end_data_table_header_row().
                   12694:                          $delete_output.
                   12695:                          &end_data_table()."\n";
                   12696:     }
1.987     raeburn  12697:     my $applies = 0;
                   12698:     if ($numremref) {
                   12699:         $applies ++;
                   12700:     }
                   12701:     if ($numinvalid) {
                   12702:         $applies ++;
                   12703:     }
                   12704:     if ($numexisting) {
                   12705:         $applies ++;
                   12706:     }
1.1071    raeburn  12707:     if ($counter || $numunused) {
1.987     raeburn  12708:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12709:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12710:                   $state.'<h3>'.$heading.'</h3>'; 
                   12711:         if ($actionurl eq '/adm/dependencies') {
                   12712:             if ($numnew) {
                   12713:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12714:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12715:                            $upload_output.'<br />'."\n";
                   12716:             }
                   12717:             if ($numexisting) {
                   12718:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12719:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12720:                            $modify_output.'<br />'."\n";
                   12721:                            $buttontext = &mt('Save changes');
                   12722:             }
                   12723:             if ($numunused) {
                   12724:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12725:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12726:                            $delete_output.'<br />'."\n";
                   12727:                            $buttontext = &mt('Save changes');
                   12728:             }
                   12729:         } else {
                   12730:             $output .= $upload_output.'<br />'."\n";
                   12731:         }
                   12732:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12733:                    $counter.'" />'."\n";
                   12734:         if ($actionurl eq '/adm/dependencies') { 
                   12735:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12736:                        $numnew.'" />'."\n";
                   12737:         } elsif ($actionurl eq '') {
1.987     raeburn  12738:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12739:         }
                   12740:     } elsif ($applies) {
                   12741:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12742:         if ($applies > 1) {
                   12743:             $output .=  
1.1123    raeburn  12744:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12745:             if ($numremref) {
                   12746:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12747:             }
                   12748:             if ($numinvalid) {
                   12749:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12750:             }
                   12751:             if ($numexisting) {
                   12752:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12753:             }
                   12754:             $output .= '</ul><br />';
                   12755:         } elsif ($numremref) {
                   12756:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12757:         } elsif ($numinvalid) {
                   12758:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12759:         } elsif ($numexisting) {
                   12760:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12761:         }
                   12762:         $output .= $upload_output.'<br />';
                   12763:     }
                   12764:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12765:     $chgcount = $counter;
1.987     raeburn  12766:     if (keys(%pathchanges) > 0) {
                   12767:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12768:             if ($counter) {
1.987     raeburn  12769:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12770:                                                   $embed_file,\%mapping,
1.1071    raeburn  12771:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12772:             } else {
                   12773:                 $pathchange_output .= 
                   12774:                     &start_data_table_row().
                   12775:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12776:                     $chgcount.'" checked="checked" /></td>'.
                   12777:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12778:                     '<td>'.$embed_file.
                   12779:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12780:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12781:                     '</td>'.&end_data_table_row();
1.660     raeburn  12782:             }
1.987     raeburn  12783:             $numpathchg ++;
                   12784:             $chgcount ++;
1.660     raeburn  12785:         }
                   12786:     }
1.1127    raeburn  12787:     if (($counter) || ($numunused)) {
1.987     raeburn  12788:         if ($numpathchg) {
                   12789:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12790:                        $numpathchg.'" />'."\n";
                   12791:         }
                   12792:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12793:             ($actionurl eq '/adm/imsimport')) {
                   12794:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12795:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12796:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12797:         } elsif ($actionurl eq '/adm/dependencies') {
                   12798:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12799:         }
1.1123    raeburn  12800:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12801:     } elsif ($numpathchg) {
                   12802:         my %pathchange = ();
                   12803:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12804:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12805:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12806:         }
1.987     raeburn  12807:     }
1.1071    raeburn  12808:     return ($output,$counter,$numpathchg);
1.987     raeburn  12809: }
                   12810: 
1.1147    raeburn  12811: =pod
                   12812: 
                   12813: =item * clean_path($name)
                   12814: 
                   12815: Performs clean-up of directories, subdirectories and filename in an
                   12816: embedded object, referenced in an HTML file which is being uploaded
                   12817: to a course or portfolio, where 
                   12818: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12819: checked.
                   12820: 
                   12821: Clean-up is similar to replacements in lonnet::clean_filename()
                   12822: except each / between sub-directory and next level is preserved.
                   12823: 
                   12824: =cut
                   12825: 
                   12826: sub clean_path {
                   12827:     my ($embed_file) = @_;
                   12828:     $embed_file =~s{^/+}{};
                   12829:     my @contents;
                   12830:     if ($embed_file =~ m{/}) {
                   12831:         @contents = split(/\//,$embed_file);
                   12832:     } else {
                   12833:         @contents = ($embed_file);
                   12834:     }
                   12835:     my $lastidx = scalar(@contents)-1;
                   12836:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12837:         $contents[$i]=~s{\\}{/}g;
                   12838:         $contents[$i]=~s/\s+/\_/g;
                   12839:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12840:         if ($i == $lastidx) {
                   12841:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12842:         }
                   12843:     }
                   12844:     if ($lastidx > 0) {
                   12845:         return join('/',@contents);
                   12846:     } else {
                   12847:         return $contents[0];
                   12848:     }
                   12849: }
                   12850: 
1.987     raeburn  12851: sub embedded_file_element {
1.1071    raeburn  12852:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12853:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12854:                    (ref($codebase) eq 'HASH'));
                   12855:     my $output;
1.1071    raeburn  12856:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12857:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12858:     }
                   12859:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12860:                &escape($embed_file).'" />';
                   12861:     unless (($context eq 'upload_embedded') && 
                   12862:             ($mapping->{$embed_file} eq $embed_file)) {
                   12863:         $output .='
                   12864:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12865:     }
                   12866:     my $attrib;
                   12867:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12868:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12869:     }
                   12870:     $output .=
                   12871:         "\n\t\t".
                   12872:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12873:         $attrib.'" />';
                   12874:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12875:         $output .=
                   12876:             "\n\t\t".
                   12877:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12878:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12879:     }
1.987     raeburn  12880:     return $output;
1.660     raeburn  12881: }
                   12882: 
1.1071    raeburn  12883: sub get_dependency_details {
                   12884:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12885:     my ($size,$mtime,$showsize,$showmtime);
                   12886:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12887:         if ($embed_file =~ m{/}) {
                   12888:             my ($path,$fname) = split(/\//,$embed_file);
                   12889:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12890:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12891:             }
                   12892:         } else {
                   12893:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12894:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12895:             }
                   12896:         }
                   12897:         $showsize = $size/1024.0;
                   12898:         $showsize = sprintf("%.1f",$showsize);
                   12899:         if ($mtime > 0) {
                   12900:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12901:         }
                   12902:     }
                   12903:     return ($showsize,$showmtime);
                   12904: }
                   12905: 
                   12906: sub ask_embedded_js {
                   12907:     return <<"END";
                   12908: <script type="text/javascript"">
                   12909: // <![CDATA[
                   12910: function toggleBrowse(counter) {
                   12911:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12912:     var fileid = document.getElementById('embedded_item_'+counter);
                   12913:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12914:     if (chkboxid.checked == true) {
                   12915:         uploaddivid.style.display='block';
                   12916:     } else {
                   12917:         uploaddivid.style.display='none';
                   12918:         fileid.value = '';
                   12919:     }
                   12920: }
                   12921: // ]]>
                   12922: </script>
                   12923: 
                   12924: END
                   12925: }
                   12926: 
1.661     raeburn  12927: sub upload_embedded {
                   12928:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12929:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12930:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12931:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12932:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12933:         my $orig_uploaded_filename =
                   12934:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12935:         foreach my $type ('orig','ref','attrib','codebase') {
                   12936:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12937:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12938:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12939:             }
                   12940:         }
1.661     raeburn  12941:         my ($path,$fname) =
                   12942:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12943:         # no path, whole string is fname
                   12944:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12945:         $fname = &Apache::lonnet::clean_filename($fname);
                   12946:         # See if there is anything left
                   12947:         next if ($fname eq '');
                   12948: 
                   12949:         # Check if file already exists as a file or directory.
                   12950:         my ($state,$msg);
                   12951:         if ($context eq 'portfolio') {
                   12952:             my $port_path = $dirpath;
                   12953:             if ($group ne '') {
                   12954:                 $port_path = "groups/$group/$port_path";
                   12955:             }
1.987     raeburn  12956:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12957:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12958:                                               $dir_root,$port_path,$disk_quota,
                   12959:                                               $current_disk_usage,$uname,$udom);
                   12960:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12961:                 || $state eq 'file_locked') {
1.661     raeburn  12962:                 $output .= $msg;
                   12963:                 next;
                   12964:             }
                   12965:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12966:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12967:             if ($state eq 'exists') {
                   12968:                 $output .= $msg;
                   12969:                 next;
                   12970:             }
                   12971:         }
                   12972:         # Check if extension is valid
                   12973:         if (($fname =~ /\.(\w+)$/) &&
                   12974:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12975:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12976:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12977:             next;
                   12978:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12979:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12980:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12981:             next;
                   12982:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12983:             $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  12984:             next;
                   12985:         }
                   12986:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12987:         my $subdir = $path;
                   12988:         $subdir =~ s{/+$}{};
1.661     raeburn  12989:         if ($context eq 'portfolio') {
1.984     raeburn  12990:             my $result;
                   12991:             if ($state eq 'existingfile') {
                   12992:                 $result=
                   12993:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12994:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12995:             } else {
1.984     raeburn  12996:                 $result=
                   12997:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12998:                                                     $dirpath.
1.1123    raeburn  12999:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13000:                 if ($result !~ m|^/uploaded/|) {
                   13001:                     $output .= '<span class="LC_error">'
                   13002:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13003:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13004:                                .'</span><br />';
                   13005:                     next;
                   13006:                 } else {
1.987     raeburn  13007:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13008:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13009:                 }
1.661     raeburn  13010:             }
1.1123    raeburn  13011:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13012:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13013:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13014:             my $result =
1.1126    raeburn  13015:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13016:             if ($result !~ m|^/uploaded/|) {
                   13017:                 $output .= '<span class="LC_error">'
                   13018:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13019:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13020:                            .'</span><br />';
                   13021:                     next;
                   13022:             } else {
                   13023:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13024:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13025:                 if ($context eq 'syllabus') {
                   13026:                     &Apache::lonnet::make_public_indefinitely($result);
                   13027:                 }
1.987     raeburn  13028:             }
1.661     raeburn  13029:         } else {
                   13030: # Save the file
                   13031:             my $target = $env{'form.embedded_item_'.$i};
                   13032:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13033:             my $dest = $fullpath.$fname;
                   13034:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13035:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13036:             my $count;
                   13037:             my $filepath = $dir_root;
1.1027    raeburn  13038:             foreach my $subdir (@parts) {
                   13039:                 $filepath .= "/$subdir";
                   13040:                 if (!-e $filepath) {
1.661     raeburn  13041:                     mkdir($filepath,0770);
                   13042:                 }
                   13043:             }
                   13044:             my $fh;
                   13045:             if (!open($fh,'>'.$dest)) {
                   13046:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13047:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13048:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13049:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13050:                            '</span><br />';
                   13051:             } else {
                   13052:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13053:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13054:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13055:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13056:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13057:                               '</span><br />';
                   13058:                 } else {
1.987     raeburn  13059:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13060:                                $url.'</span>').'<br />';
                   13061:                     unless ($context eq 'testbank') {
                   13062:                         $footer .= &mt('View embedded file: [_1]',
                   13063:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13064:                     }
                   13065:                 }
                   13066:                 close($fh);
                   13067:             }
                   13068:         }
                   13069:         if ($env{'form.embedded_ref_'.$i}) {
                   13070:             $pathchange{$i} = 1;
                   13071:         }
                   13072:     }
                   13073:     if ($output) {
                   13074:         $output = '<p>'.$output.'</p>';
                   13075:     }
                   13076:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13077:     $returnflag = 'ok';
1.1071    raeburn  13078:     my $numpathchgs = scalar(keys(%pathchange));
                   13079:     if ($numpathchgs > 0) {
1.987     raeburn  13080:         if ($context eq 'portfolio') {
                   13081:             $output .= '<p>'.&mt('or').'</p>';
                   13082:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13083:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13084:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13085:             $returnflag = 'modify_orightml';
                   13086:         }
                   13087:     }
1.1071    raeburn  13088:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13089: }
                   13090: 
                   13091: sub modify_html_form {
                   13092:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13093:     my $end = 0;
                   13094:     my $modifyform;
                   13095:     if ($context eq 'upload_embedded') {
                   13096:         return unless (ref($pathchange) eq 'HASH');
                   13097:         if ($env{'form.number_embedded_items'}) {
                   13098:             $end += $env{'form.number_embedded_items'};
                   13099:         }
                   13100:         if ($env{'form.number_pathchange_items'}) {
                   13101:             $end += $env{'form.number_pathchange_items'};
                   13102:         }
                   13103:         if ($end) {
                   13104:             for (my $i=0; $i<$end; $i++) {
                   13105:                 if ($i < $env{'form.number_embedded_items'}) {
                   13106:                     next unless($pathchange->{$i});
                   13107:                 }
                   13108:                 $modifyform .=
                   13109:                     &start_data_table_row().
                   13110:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13111:                     'checked="checked" /></td>'.
                   13112:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13113:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13114:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13115:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13116:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13117:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13118:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13119:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13120:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13121:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13122:                     &end_data_table_row();
1.1071    raeburn  13123:             }
1.987     raeburn  13124:         }
                   13125:     } else {
                   13126:         $modifyform = $pathchgtable;
                   13127:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13128:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13129:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13130:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13131:         }
                   13132:     }
                   13133:     if ($modifyform) {
1.1071    raeburn  13134:         if ($actionurl eq '/adm/dependencies') {
                   13135:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13136:         }
1.987     raeburn  13137:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13138:                '<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".
                   13139:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13140:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13141:                '</ol></p>'."\n".'<p>'.
                   13142:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13143:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13144:                &start_data_table()."\n".
                   13145:                &start_data_table_header_row().
                   13146:                '<th>'.&mt('Change?').'</th>'.
                   13147:                '<th>'.&mt('Current reference').'</th>'.
                   13148:                '<th>'.&mt('Required reference').'</th>'.
                   13149:                &end_data_table_header_row()."\n".
                   13150:                $modifyform.
                   13151:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13152:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13153:                '</form>'."\n";
                   13154:     }
                   13155:     return;
                   13156: }
                   13157: 
                   13158: sub modify_html_refs {
1.1123    raeburn  13159:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13160:     my $container;
                   13161:     if ($context eq 'portfolio') {
                   13162:         $container = $env{'form.container'};
                   13163:     } elsif ($context eq 'coursedoc') {
                   13164:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13165:     } elsif ($context eq 'manage_dependencies') {
                   13166:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13167:         $container = "/$container";
1.1123    raeburn  13168:     } elsif ($context eq 'syllabus') {
                   13169:         $container = $url;
1.987     raeburn  13170:     } else {
1.1027    raeburn  13171:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13172:     }
                   13173:     my (%allfiles,%codebase,$output,$content);
                   13174:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13175:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13176:         if (wantarray) {
                   13177:             return ('',0,0); 
                   13178:         } else {
                   13179:             return;
                   13180:         }
                   13181:     }
                   13182:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13183:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13184:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13185:             if (wantarray) {
                   13186:                 return ('',0,0);
                   13187:             } else {
                   13188:                 return;
                   13189:             }
                   13190:         } 
1.987     raeburn  13191:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13192:         if ($content eq '-1') {
                   13193:             if (wantarray) {
                   13194:                 return ('',0,0);
                   13195:             } else {
                   13196:                 return;
                   13197:             }
                   13198:         }
1.987     raeburn  13199:     } else {
1.1071    raeburn  13200:         unless ($container =~ /^\Q$dir_root\E/) {
                   13201:             if (wantarray) {
                   13202:                 return ('',0,0);
                   13203:             } else {
                   13204:                 return;
                   13205:             }
                   13206:         } 
1.1317    raeburn  13207:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13208:             $content = join('', <$fh>);
                   13209:             close($fh);
                   13210:         } else {
1.1071    raeburn  13211:             if (wantarray) {
                   13212:                 return ('',0,0);
                   13213:             } else {
                   13214:                 return;
                   13215:             }
1.987     raeburn  13216:         }
                   13217:     }
                   13218:     my ($count,$codebasecount) = (0,0);
                   13219:     my $mm = new File::MMagic;
                   13220:     my $mime_type = $mm->checktype_contents($content);
                   13221:     if ($mime_type eq 'text/html') {
                   13222:         my $parse_result = 
                   13223:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13224:                                                     \%codebase,\$content);
                   13225:         if ($parse_result eq 'ok') {
                   13226:             foreach my $i (@changes) {
                   13227:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13228:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13229:                 if ($allfiles{$ref}) {
                   13230:                     my $newname =  $orig;
                   13231:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13232:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13233:                     if ($attrib_regexp =~ /:/) {
                   13234:                         $attrib_regexp =~ s/\:/|/g;
                   13235:                     }
                   13236:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13237:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13238:                         $count += $numchg;
1.1123    raeburn  13239:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13240:                         delete($allfiles{$ref});
1.987     raeburn  13241:                     }
                   13242:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13243:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13244:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13245:                         $codebasecount ++;
                   13246:                     }
                   13247:                 }
                   13248:             }
1.1123    raeburn  13249:             my $skiprewrites;
1.987     raeburn  13250:             if ($count || $codebasecount) {
                   13251:                 my $saveresult;
1.1071    raeburn  13252:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13253:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13254:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13255:                     if ($url eq $container) {
                   13256:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13257:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13258:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13259:                                             $fname.'</span>').'</p>';
1.987     raeburn  13260:                     } else {
                   13261:                          $output = '<p class="LC_error">'.
                   13262:                                    &mt('Error: update failed for: [_1].',
                   13263:                                    '<span class="LC_filename">'.
                   13264:                                    $container.'</span>').'</p>';
                   13265:                     }
1.1123    raeburn  13266:                     if ($context eq 'syllabus') {
                   13267:                         unless ($saveresult eq 'ok') {
                   13268:                             $skiprewrites = 1;
                   13269:                         }
                   13270:                     }
1.987     raeburn  13271:                 } else {
1.1317    raeburn  13272:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13273:                         print $fh $content;
                   13274:                         close($fh);
                   13275:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13276:                                   $count,'<span class="LC_filename">'.
                   13277:                                   $container.'</span>').'</p>';
1.661     raeburn  13278:                     } else {
1.987     raeburn  13279:                          $output = '<p class="LC_error">'.
                   13280:                                    &mt('Error: could not update [_1].',
                   13281:                                    '<span class="LC_filename">'.
                   13282:                                    $container.'</span>').'</p>';
1.661     raeburn  13283:                     }
                   13284:                 }
                   13285:             }
1.1123    raeburn  13286:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13287:                 my ($actionurl,$state);
                   13288:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13289:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13290:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13291:                                               \%codebase,
                   13292:                                               {'context' => 'rewrites',
                   13293:                                                'ignore_remote_references' => 1,});
                   13294:                 if (ref($mapping) eq 'HASH') {
                   13295:                     my $rewrites = 0;
                   13296:                     foreach my $key (keys(%{$mapping})) {
                   13297:                         next if ($key =~ m{^https?://});
                   13298:                         my $ref = $mapping->{$key};
                   13299:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13300:                         my $attrib;
                   13301:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13302:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13303:                         }
                   13304:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13305:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13306:                             $rewrites += $numchg;
                   13307:                         }
                   13308:                     }
                   13309:                     if ($rewrites) {
                   13310:                         my $saveresult; 
                   13311:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13312:                         if ($url eq $container) {
                   13313:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13314:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13315:                                             $count,'<span class="LC_filename">'.
                   13316:                                             $fname.'</span>').'</p>';
                   13317:                         } else {
                   13318:                             $output .= '<p class="LC_error">'.
                   13319:                                        &mt('Error: could not update links in [_1].',
                   13320:                                        '<span class="LC_filename">'.
                   13321:                                        $container.'</span>').'</p>';
                   13322: 
                   13323:                         }
                   13324:                     }
                   13325:                 }
                   13326:             }
1.987     raeburn  13327:         } else {
                   13328:             &logthis('Failed to parse '.$container.
                   13329:                      ' to modify references: '.$parse_result);
1.661     raeburn  13330:         }
                   13331:     }
1.1071    raeburn  13332:     if (wantarray) {
                   13333:         return ($output,$count,$codebasecount);
                   13334:     } else {
                   13335:         return $output;
                   13336:     }
1.661     raeburn  13337: }
                   13338: 
                   13339: sub check_for_existing {
                   13340:     my ($path,$fname,$element) = @_;
                   13341:     my ($state,$msg);
                   13342:     if (-d $path.'/'.$fname) {
                   13343:         $state = 'exists';
                   13344:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13345:     } elsif (-e $path.'/'.$fname) {
                   13346:         $state = 'exists';
                   13347:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13348:     }
                   13349:     if ($state eq 'exists') {
                   13350:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13351:     }
                   13352:     return ($state,$msg);
                   13353: }
                   13354: 
                   13355: sub check_for_upload {
                   13356:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13357:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13358:     my $filesize = length($env{'form.'.$element});
                   13359:     if (!$filesize) {
                   13360:         my $msg = '<span class="LC_error">'.
                   13361:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13362:                       '<span class="LC_filename">'.$fname.'</span>',
                   13363:                       $filesize).'<br />'.
1.1007    raeburn  13364:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13365:                   '</span>';
                   13366:         return ('zero_bytes',$msg);
                   13367:     }
                   13368:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13369:     my $getpropath = 1;
1.1021    raeburn  13370:     my ($dirlistref,$listerror) =
                   13371:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13372:     my $found_file = 0;
                   13373:     my $locked_file = 0;
1.991     raeburn  13374:     my @lockers;
                   13375:     my $navmap;
                   13376:     if ($env{'request.course.id'}) {
                   13377:         $navmap = Apache::lonnavmaps::navmap->new();
                   13378:     }
1.1021    raeburn  13379:     if (ref($dirlistref) eq 'ARRAY') {
                   13380:         foreach my $line (@{$dirlistref}) {
                   13381:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13382:             if ($file_name eq $fname){
                   13383:                 $file_name = $path.$file_name;
                   13384:                 if ($group ne '') {
                   13385:                     $file_name = $group.$file_name;
                   13386:                 }
                   13387:                 $found_file = 1;
                   13388:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13389:                     foreach my $lock (@lockers) {
                   13390:                         if (ref($lock) eq 'ARRAY') {
                   13391:                             my ($symb,$crsid) = @{$lock};
                   13392:                             if ($crsid eq $env{'request.course.id'}) {
                   13393:                                 if (ref($navmap)) {
                   13394:                                     my $res = $navmap->getBySymb($symb);
                   13395:                                     foreach my $part (@{$res->parts()}) { 
                   13396:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13397:                                         unless (($slot_status == $res->RESERVED) ||
                   13398:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13399:                                             $locked_file = 1;
                   13400:                                         }
1.991     raeburn  13401:                                     }
1.1021    raeburn  13402:                                 } else {
                   13403:                                     $locked_file = 1;
1.991     raeburn  13404:                                 }
                   13405:                             } else {
                   13406:                                 $locked_file = 1;
                   13407:                             }
                   13408:                         }
1.1021    raeburn  13409:                    }
                   13410:                 } else {
                   13411:                     my @info = split(/\&/,$rest);
                   13412:                     my $currsize = $info[6]/1000;
                   13413:                     if ($currsize < $filesize) {
                   13414:                         my $extra = $filesize - $currsize;
                   13415:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13416:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13417:                                       &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   13418:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13419:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13420:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13421:                             return ('will_exceed_quota',$msg);
                   13422:                         }
1.984     raeburn  13423:                     }
                   13424:                 }
1.661     raeburn  13425:             }
                   13426:         }
                   13427:     }
                   13428:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13429:         my $msg = '<p class="LC_warning">'.
                   13430:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13431:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13432:         return ('will_exceed_quota',$msg);
                   13433:     } elsif ($found_file) {
                   13434:         if ($locked_file) {
1.1179    bisitz   13435:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13436:             $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   13437:             $msg .= '</p>';
1.661     raeburn  13438:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13439:             return ('file_locked',$msg);
                   13440:         } else {
1.1179    bisitz   13441:             my $msg = '<p class="LC_error">';
1.984     raeburn  13442:             $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   13443:             $msg .= '</p>';
1.984     raeburn  13444:             return ('existingfile',$msg);
1.661     raeburn  13445:         }
                   13446:     }
                   13447: }
                   13448: 
1.987     raeburn  13449: sub check_for_traversal {
                   13450:     my ($path,$url,$toplevel) = @_;
                   13451:     my @parts=split(/\//,$path);
                   13452:     my $cleanpath;
                   13453:     my $fullpath = $url;
                   13454:     for (my $i=0;$i<@parts;$i++) {
                   13455:         next if ($parts[$i] eq '.');
                   13456:         if ($parts[$i] eq '..') {
                   13457:             $fullpath =~ s{([^/]+/)$}{};
                   13458:         } else {
                   13459:             $fullpath .= $parts[$i].'/';
                   13460:         }
                   13461:     }
                   13462:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13463:         $cleanpath = $1;
                   13464:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13465:         my $curr_toprel = $1;
                   13466:         my @parts = split(/\//,$curr_toprel);
                   13467:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13468:         my @urlparts = split(/\//,$url_toprel);
                   13469:         my $doubledots;
                   13470:         my $startdiff = -1;
                   13471:         for (my $i=0; $i<@urlparts; $i++) {
                   13472:             if ($startdiff == -1) {
                   13473:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13474:                     $startdiff = $i;
                   13475:                     $doubledots .= '../';
                   13476:                 }
                   13477:             } else {
                   13478:                 $doubledots .= '../';
                   13479:             }
                   13480:         }
                   13481:         if ($startdiff > -1) {
                   13482:             $cleanpath = $doubledots;
                   13483:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13484:                 $cleanpath .= $parts[$i].'/';
                   13485:             }
                   13486:         }
                   13487:     }
                   13488:     $cleanpath =~ s{(/)$}{};
                   13489:     return $cleanpath;
                   13490: }
1.31      albertel 13491: 
1.1053    raeburn  13492: sub is_archive_file {
                   13493:     my ($mimetype) = @_;
                   13494:     if (($mimetype eq 'application/octet-stream') ||
                   13495:         ($mimetype eq 'application/x-stuffit') ||
                   13496:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13497:         return 1;
                   13498:     }
                   13499:     return;
                   13500: }
                   13501: 
                   13502: sub decompress_form {
1.1065    raeburn  13503:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13504:     my %lt = &Apache::lonlocal::texthash (
                   13505:         this => 'This file is an archive file.',
1.1067    raeburn  13506:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13507:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13508:         youm => 'You may wish to extract its contents.',
                   13509:         extr => 'Extract contents',
1.1067    raeburn  13510:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13511:         proa => 'Process automatically?',
1.1053    raeburn  13512:         yes  => 'Yes',
                   13513:         no   => 'No',
1.1067    raeburn  13514:         fold => 'Title for folder containing movie',
                   13515:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13516:     );
1.1065    raeburn  13517:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13518:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13519:     my $info = &list_archive_contents($fileloc,\@paths);
                   13520:     if (@paths) {
                   13521:         foreach my $path (@paths) {
                   13522:             $path =~ s{^/}{};
1.1067    raeburn  13523:             if ($path =~ m{^([^/]+)/$}) {
                   13524:                 $topdir = $1;
                   13525:             }
1.1065    raeburn  13526:             if ($path =~ m{^([^/]+)/}) {
                   13527:                 $toplevel{$1} = $path;
                   13528:             } else {
                   13529:                 $toplevel{$path} = $path;
                   13530:             }
                   13531:         }
                   13532:     }
1.1067    raeburn  13533:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13534:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13535:                         "$topdir/media/",
                   13536:                         "$topdir/media/$topdir.mp4",
                   13537:                         "$topdir/media/FirstFrame.png",
                   13538:                         "$topdir/media/player.swf",
                   13539:                         "$topdir/media/swfobject.js",
                   13540:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13541:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13542:                          "$topdir/$topdir.mp4",
                   13543:                          "$topdir/$topdir\_config.xml",
                   13544:                          "$topdir/$topdir\_controller.swf",
                   13545:                          "$topdir/$topdir\_embed.css",
                   13546:                          "$topdir/$topdir\_First_Frame.png",
                   13547:                          "$topdir/$topdir\_player.html",
                   13548:                          "$topdir/$topdir\_Thumbnails.png",
                   13549:                          "$topdir/playerProductInstall.swf",
                   13550:                          "$topdir/scripts/",
                   13551:                          "$topdir/scripts/config_xml.js",
                   13552:                          "$topdir/scripts/handlebars.js",
                   13553:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13554:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13555:                          "$topdir/scripts/modernizr.js",
                   13556:                          "$topdir/scripts/player-min.js",
                   13557:                          "$topdir/scripts/swfobject.js",
                   13558:                          "$topdir/skins/",
                   13559:                          "$topdir/skins/configuration_express.xml",
                   13560:                          "$topdir/skins/express_show/",
                   13561:                          "$topdir/skins/express_show/player-min.css",
                   13562:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13563:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13564:                          "$topdir/$topdir.mp4",
                   13565:                          "$topdir/$topdir\_config.xml",
                   13566:                          "$topdir/$topdir\_controller.swf",
                   13567:                          "$topdir/$topdir\_embed.css",
                   13568:                          "$topdir/$topdir\_First_Frame.png",
                   13569:                          "$topdir/$topdir\_player.html",
                   13570:                          "$topdir/$topdir\_Thumbnails.png",
                   13571:                          "$topdir/playerProductInstall.swf",
                   13572:                          "$topdir/scripts/",
                   13573:                          "$topdir/scripts/config_xml.js",
                   13574:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13575:                          "$topdir/skins/",
                   13576:                          "$topdir/skins/configuration_express.xml",
                   13577:                          "$topdir/skins/express_show/",
                   13578:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13579:                          "$topdir/skins/express_show/spritesheet.png",
                   13580:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13581:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13582:         if (@diffs == 0) {
1.1164    raeburn  13583:             $is_camtasia = 6;
                   13584:         } else {
1.1197    raeburn  13585:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13586:             if (@diffs == 0) {
                   13587:                 $is_camtasia = 8;
1.1197    raeburn  13588:             } else {
                   13589:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13590:                 if (@diffs == 0) {
                   13591:                     $is_camtasia = 8;
                   13592:                 }
1.1164    raeburn  13593:             }
1.1067    raeburn  13594:         }
                   13595:     }
                   13596:     my $output;
                   13597:     if ($is_camtasia) {
                   13598:         $output = <<"ENDCAM";
                   13599: <script type="text/javascript" language="Javascript">
                   13600: // <![CDATA[
                   13601: 
                   13602: function camtasiaToggle() {
                   13603:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13604:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13605:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13606:                 document.getElementById('camtasia_titles').style.display='block';
                   13607:             } else {
                   13608:                 document.getElementById('camtasia_titles').style.display='none';
                   13609:             }
                   13610:         }
                   13611:     }
                   13612:     return;
                   13613: }
                   13614: 
                   13615: // ]]>
                   13616: </script>
                   13617: <p>$lt{'camt'}</p>
                   13618: ENDCAM
1.1065    raeburn  13619:     } else {
1.1067    raeburn  13620:         $output = '<p>'.$lt{'this'};
                   13621:         if ($info eq '') {
                   13622:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13623:         } else {
                   13624:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13625:                        '<div><pre>'.$info.'</pre></div>';
                   13626:         }
1.1065    raeburn  13627:     }
1.1067    raeburn  13628:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13629:     my $duplicates;
                   13630:     my $num = 0;
                   13631:     if (ref($dirlist) eq 'ARRAY') {
                   13632:         foreach my $item (@{$dirlist}) {
                   13633:             if (ref($item) eq 'ARRAY') {
                   13634:                 if (exists($toplevel{$item->[0]})) {
                   13635:                     $duplicates .= 
                   13636:                         &start_data_table_row().
                   13637:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13638:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13639:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13640:                         'value="1" />'.&mt('Yes').'</label>'.
                   13641:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13642:                         '<td>'.$item->[0].'</td>';
                   13643:                     if ($item->[2]) {
                   13644:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13645:                     } else {
                   13646:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13647:                     }
                   13648:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13649:                                    '<td>'.
                   13650:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13651:                                    '</td>'.
                   13652:                                    &end_data_table_row();
                   13653:                     $num ++;
                   13654:                 }
                   13655:             }
                   13656:         }
                   13657:     }
                   13658:     my $itemcount;
                   13659:     if (@paths > 0) {
                   13660:         $itemcount = scalar(@paths);
                   13661:     } else {
                   13662:         $itemcount = 1;
                   13663:     }
1.1067    raeburn  13664:     if ($is_camtasia) {
                   13665:         $output .= $lt{'auto'}.'<br />'.
                   13666:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13667:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13668:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13669:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13670:                    $lt{'no'}.'</label></span><br />'.
                   13671:                    '<div id="camtasia_titles" style="display:block">'.
                   13672:                    &Apache::lonhtmlcommon::start_pick_box().
                   13673:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13674:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13675:                    &Apache::lonhtmlcommon::row_closure().
                   13676:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13677:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13678:                    &Apache::lonhtmlcommon::row_closure(1).
                   13679:                    &Apache::lonhtmlcommon::end_pick_box().
                   13680:                    '</div>';
                   13681:     }
1.1065    raeburn  13682:     $output .= 
                   13683:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13684:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13685:         "\n";
1.1065    raeburn  13686:     if ($duplicates ne '') {
                   13687:         $output .= '<p><span class="LC_warning">'.
                   13688:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13689:                    &start_data_table().
                   13690:                    &start_data_table_header_row().
                   13691:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13692:                    '<th>'.&mt('Name').'</th>'.
                   13693:                    '<th>'.&mt('Type').'</th>'.
                   13694:                    '<th>'.&mt('Size').'</th>'.
                   13695:                    '<th>'.&mt('Last modified').'</th>'.
                   13696:                    &end_data_table_header_row().
                   13697:                    $duplicates.
                   13698:                    &end_data_table().
                   13699:                    '</p>';
                   13700:     }
1.1067    raeburn  13701:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13702:     if (ref($hiddenelements) eq 'HASH') {
                   13703:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13704:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13705:         }
                   13706:     }
                   13707:     $output .= <<"END";
1.1067    raeburn  13708: <br />
1.1053    raeburn  13709: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13710: </form>
                   13711: $noextract
                   13712: END
                   13713:     return $output;
                   13714: }
                   13715: 
1.1065    raeburn  13716: sub decompression_utility {
                   13717:     my ($program) = @_;
                   13718:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13719:     my $location;
                   13720:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13721:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13722:                          '/usr/sbin/') {
                   13723:             if (-x $dir.$program) {
                   13724:                 $location = $dir.$program;
                   13725:                 last;
                   13726:             }
                   13727:         }
                   13728:     }
                   13729:     return $location;
                   13730: }
                   13731: 
                   13732: sub list_archive_contents {
                   13733:     my ($file,$pathsref) = @_;
                   13734:     my (@cmd,$output);
                   13735:     my $needsregexp;
                   13736:     if ($file =~ /\.zip$/) {
                   13737:         @cmd = (&decompression_utility('unzip'),"-l");
                   13738:         $needsregexp = 1;
                   13739:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13740:              ($file =~ /\.tgz$/)) {
                   13741:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13742:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13743:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13744:     } elsif ($file =~ m|\.tar$|) {
                   13745:         @cmd = (&decompression_utility('tar'),"-tf");
                   13746:     }
                   13747:     if (@cmd) {
                   13748:         undef($!);
                   13749:         undef($@);
                   13750:         if (open(my $fh,"-|", @cmd, $file)) {
                   13751:             while (my $line = <$fh>) {
                   13752:                 $output .= $line;
                   13753:                 chomp($line);
                   13754:                 my $item;
                   13755:                 if ($needsregexp) {
                   13756:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13757:                 } else {
                   13758:                     $item = $line;
                   13759:                 }
                   13760:                 if ($item ne '') {
                   13761:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13762:                         push(@{$pathsref},$item);
                   13763:                     } 
                   13764:                 }
                   13765:             }
                   13766:             close($fh);
                   13767:         }
                   13768:     }
                   13769:     return $output;
                   13770: }
                   13771: 
1.1053    raeburn  13772: sub decompress_uploaded_file {
                   13773:     my ($file,$dir) = @_;
                   13774:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13775:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13776:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13777:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13778:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13779:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13780:     my $decompressed = $env{'cgi.decompressed'};
                   13781:     &Apache::lonnet::delenv('cgi.file');
                   13782:     &Apache::lonnet::delenv('cgi.dir');
                   13783:     &Apache::lonnet::delenv('cgi.decompressed');
                   13784:     return ($decompressed,$result);
                   13785: }
                   13786: 
1.1055    raeburn  13787: sub process_decompression {
                   13788:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13789:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13790:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13791:                &mt('Unexpected file path.').'</p>'."\n";
                   13792:     }
                   13793:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13794:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13795:                &mt('Unexpected course context.').'</p>'."\n";
                   13796:     }
1.1293    raeburn  13797:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13798:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13799:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13800:     }
1.1055    raeburn  13801:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13802:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13803:         $error = &mt('Filename not a supported archive file type.').
                   13804:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13805:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13806:     } else {
                   13807:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13808:         if ($docuhome eq 'no_host') {
                   13809:             $error = &mt('Could not determine home server for course.');
                   13810:         } else {
                   13811:             my @ids=&Apache::lonnet::current_machine_ids();
                   13812:             my $currdir = "$dir_root/$destination";
                   13813:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13814:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13815:                        "$dir_root/$destination";
                   13816:             } else {
                   13817:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13818:                        "$dir_root/$docudom/$docuname/$destination";
                   13819:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13820:                     $error = &mt('Archive file not found.');
                   13821:                 }
                   13822:             }
1.1065    raeburn  13823:             my (@to_overwrite,@to_skip);
                   13824:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13825:                 my $total = $env{'form.archive_overwrite_total'};
                   13826:                 for (my $i=0; $i<$total; $i++) {
                   13827:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13828:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13829:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13830:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13831:                     }
                   13832:                 }
                   13833:             }
                   13834:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13835:             my $numoverwrite = scalar(@to_overwrite);
                   13836:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13837:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13838:             } elsif ($dir eq '') {
1.1055    raeburn  13839:                 $error = &mt('Directory containing archive file unavailable.');
                   13840:             } elsif (!$error) {
1.1065    raeburn  13841:                 my ($decompressed,$display);
1.1292    raeburn  13842:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13843:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13844:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13845:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13846:                         ($decompressed,$display) = 
                   13847:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13848:                         foreach my $item (@to_skip) {
                   13849:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13850:                                 if (-f "$dir/$tempdir/$item") { 
                   13851:                                     unlink("$dir/$tempdir/$item");
                   13852:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13853:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13854:                                 }
                   13855:                             }
                   13856:                         }
                   13857:                         foreach my $item (@to_overwrite) {
                   13858:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13859:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13860:                                     if (-f "$dir/$item") {
                   13861:                                         unlink("$dir/$item");
                   13862:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13863:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13864:                                     }
                   13865:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13866:                                 }
1.1065    raeburn  13867:                             }
                   13868:                         }
1.1292    raeburn  13869:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13870:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13871:                         }
1.1065    raeburn  13872:                     }
                   13873:                 } else {
                   13874:                     ($decompressed,$display) = 
                   13875:                         &decompress_uploaded_file($file,$dir);
                   13876:                 }
1.1055    raeburn  13877:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13878:                     $output = '<p class="LC_info">'.
                   13879:                               &mt('Files extracted successfully from archive.').
                   13880:                               '</p>'."\n";
1.1055    raeburn  13881:                     my ($warning,$result,@contents);
                   13882:                     my ($newdirlistref,$newlisterror) =
                   13883:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13884:                                                  $docuname,1);
                   13885:                     my (%is_dir,%changes,@newitems);
                   13886:                     my $dirptr = 16384;
1.1065    raeburn  13887:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13888:                         foreach my $dir_line (@{$newdirlistref}) {
                   13889:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13890:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13891:                                 push(@newitems,$item);
                   13892:                                 if ($dirptr&$testdir) {
                   13893:                                     $is_dir{$item} = 1;
                   13894:                                 }
                   13895:                                 $changes{$item} = 1;
                   13896:                             }
                   13897:                         }
                   13898:                     }
                   13899:                     if (keys(%changes) > 0) {
                   13900:                         foreach my $item (sort(@newitems)) {
                   13901:                             if ($changes{$item}) {
                   13902:                                 push(@contents,$item);
                   13903:                             }
                   13904:                         }
                   13905:                     }
                   13906:                     if (@contents > 0) {
1.1067    raeburn  13907:                         my $wantform;
                   13908:                         unless ($env{'form.autoextract_camtasia'}) {
                   13909:                             $wantform = 1;
                   13910:                         }
1.1056    raeburn  13911:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13912:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13913:                                                                 $currdir,\%is_dir,
                   13914:                                                                 \%children,\%parent,
1.1056    raeburn  13915:                                                                 \@contents,\%dirorder,
                   13916:                                                                 \%titles,$wantform);
1.1055    raeburn  13917:                         if ($datatable ne '') {
                   13918:                             $output .= &archive_options_form('decompressed',$datatable,
                   13919:                                                              $count,$hiddenelem);
1.1065    raeburn  13920:                             my $startcount = 6;
1.1055    raeburn  13921:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13922:                                                            \%titles,\%children);
1.1055    raeburn  13923:                         }
1.1067    raeburn  13924:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13925:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13926:                             my %displayed;
                   13927:                             my $total = 1;
                   13928:                             $env{'form.archive_directory'} = [];
                   13929:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13930:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13931:                                 $path =~ s{/$}{};
                   13932:                                 my $item;
                   13933:                                 if ($path ne '') {
                   13934:                                     $item = "$path/$titles{$i}";
                   13935:                                 } else {
                   13936:                                     $item = $titles{$i};
                   13937:                                 }
                   13938:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13939:                                 if ($item eq $contents[0]) {
                   13940:                                     push(@{$env{'form.archive_directory'}},$i);
                   13941:                                     $env{'form.archive_'.$i} = 'display';
                   13942:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13943:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13944:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13945:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13946:                                     $env{'form.archive_'.$i} = 'display';
                   13947:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13948:                                     $displayed{'web'} = $i;
                   13949:                                 } else {
1.1164    raeburn  13950:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13951:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13952:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13953:                                         push(@{$env{'form.archive_directory'}},$i);
                   13954:                                     }
                   13955:                                     $env{'form.archive_'.$i} = 'dependency';
                   13956:                                 }
                   13957:                                 $total ++;
                   13958:                             }
                   13959:                             for (my $i=1; $i<$total; $i++) {
                   13960:                                 next if ($i == $displayed{'web'});
                   13961:                                 next if ($i == $displayed{'folder'});
                   13962:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13963:                             }
                   13964:                             $env{'form.phase'} = 'decompress_cleanup';
                   13965:                             $env{'form.archivedelete'} = 1;
                   13966:                             $env{'form.archive_count'} = $total-1;
                   13967:                             $output .=
                   13968:                                 &process_extracted_files('coursedocs',$docudom,
                   13969:                                                          $docuname,$destination,
                   13970:                                                          $dir_root,$hiddenelem);
                   13971:                         }
1.1055    raeburn  13972:                     } else {
                   13973:                         $warning = &mt('No new items extracted from archive file.');
                   13974:                     }
                   13975:                 } else {
                   13976:                     $output = $display;
                   13977:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13978:                 }
                   13979:             }
                   13980:         }
                   13981:     }
                   13982:     if ($error) {
                   13983:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13984:                    $error.'</p>'."\n";
                   13985:     }
                   13986:     if ($warning) {
                   13987:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13988:     }
                   13989:     return $output;
                   13990: }
                   13991: 
                   13992: sub get_extracted {
1.1056    raeburn  13993:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13994:         $titles,$wantform) = @_;
1.1055    raeburn  13995:     my $count = 0;
                   13996:     my $depth = 0;
                   13997:     my $datatable;
1.1056    raeburn  13998:     my @hierarchy;
1.1055    raeburn  13999:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14000:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14001:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14002:     foreach my $item (@{$contents}) {
                   14003:         $count ++;
1.1056    raeburn  14004:         @{$dirorder->{$count}} = @hierarchy;
                   14005:         $titles->{$count} = $item;
1.1055    raeburn  14006:         &archive_hierarchy($depth,$count,$parent,$children);
                   14007:         if ($wantform) {
                   14008:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14009:                                        $currdir,$depth,$count);
                   14010:         }
                   14011:         if ($is_dir->{$item}) {
                   14012:             $depth ++;
1.1056    raeburn  14013:             push(@hierarchy,$count);
                   14014:             $parent->{$depth} = $count;
1.1055    raeburn  14015:             $datatable .=
                   14016:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14017:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14018:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14019:             $depth --;
1.1056    raeburn  14020:             pop(@hierarchy);
1.1055    raeburn  14021:         }
                   14022:     }
                   14023:     return ($count,$datatable);
                   14024: }
                   14025: 
                   14026: sub recurse_extracted_archive {
1.1056    raeburn  14027:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14028:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14029:     my $result='';
1.1056    raeburn  14030:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14031:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14032:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14033:         return $result;
                   14034:     }
                   14035:     my $dirptr = 16384;
                   14036:     my ($newdirlistref,$newlisterror) =
                   14037:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14038:     if (ref($newdirlistref) eq 'ARRAY') {
                   14039:         foreach my $dir_line (@{$newdirlistref}) {
                   14040:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14041:             unless ($item =~ /^\.+$/) {
                   14042:                 $$count ++;
1.1056    raeburn  14043:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14044:                 $titles->{$$count} = $item;
1.1055    raeburn  14045:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14046: 
1.1055    raeburn  14047:                 my $is_dir;
                   14048:                 if ($dirptr&$testdir) {
                   14049:                     $is_dir = 1;
                   14050:                 }
                   14051:                 if ($wantform) {
                   14052:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14053:                 }
                   14054:                 if ($is_dir) {
                   14055:                     $$depth ++;
1.1056    raeburn  14056:                     push(@{$hierarchy},$$count);
                   14057:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14058:                     $result .=
                   14059:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14060:                                                    $docuname,$depth,$count,
1.1056    raeburn  14061:                                                    $hierarchy,$dirorder,$children,
                   14062:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14063:                     $$depth --;
1.1056    raeburn  14064:                     pop(@{$hierarchy});
1.1055    raeburn  14065:                 }
                   14066:             }
                   14067:         }
                   14068:     }
                   14069:     return $result;
                   14070: }
                   14071: 
                   14072: sub archive_hierarchy {
                   14073:     my ($depth,$count,$parent,$children) =@_;
                   14074:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14075:         if (exists($parent->{$depth})) {
                   14076:              $children->{$parent->{$depth}} .= $count.':';
                   14077:         }
                   14078:     }
                   14079:     return;
                   14080: }
                   14081: 
                   14082: sub archive_row {
                   14083:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14084:     my ($name) = ($item =~ m{([^/]+)$});
                   14085:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14086:                                        'display'    => 'Add as file',
1.1055    raeburn  14087:                                        'dependency' => 'Include as dependency',
                   14088:                                        'discard'    => 'Discard',
                   14089:                                       );
                   14090:     if ($is_dir) {
1.1059    raeburn  14091:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14092:     }
1.1056    raeburn  14093:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14094:     my $offset = 0;
1.1055    raeburn  14095:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14096:         $offset ++;
1.1065    raeburn  14097:         if ($action ne 'display') {
                   14098:             $offset ++;
                   14099:         }  
1.1055    raeburn  14100:         $output .= '<td><span class="LC_nobreak">'.
                   14101:                    '<label><input type="radio" name="archive_'.$count.
                   14102:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14103:         my $text = $choices{$action};
                   14104:         if ($is_dir) {
                   14105:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14106:             if ($action eq 'display') {
1.1059    raeburn  14107:                 $text = &mt('Add as folder');
1.1055    raeburn  14108:             }
1.1056    raeburn  14109:         } else {
                   14110:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14111: 
                   14112:         }
                   14113:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14114:         if ($action eq 'dependency') {
                   14115:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14116:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14117:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14118:                        '<option value=""></option>'."\n".
                   14119:                        '</select>'."\n".
                   14120:                        '</div>';
1.1059    raeburn  14121:         } elsif ($action eq 'display') {
                   14122:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14123:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14124:                        '</div>';
1.1055    raeburn  14125:         }
1.1056    raeburn  14126:         $output .= '</td>';
1.1055    raeburn  14127:     }
                   14128:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14129:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14130:     for (my $i=0; $i<$depth; $i++) {
                   14131:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14132:     }
                   14133:     if ($is_dir) {
                   14134:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14135:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14136:     } else {
                   14137:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14138:     }
                   14139:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14140:                &end_data_table_row();
                   14141:     return $output;
                   14142: }
                   14143: 
                   14144: sub archive_options_form {
1.1065    raeburn  14145:     my ($form,$display,$count,$hiddenelem) = @_;
                   14146:     my %lt = &Apache::lonlocal::texthash(
                   14147:                perm => 'Permanently remove archive file?',
                   14148:                hows => 'How should each extracted item be incorporated in the course?',
                   14149:                cont => 'Content actions for all',
                   14150:                addf => 'Add as folder/file',
                   14151:                incd => 'Include as dependency for a displayed file',
                   14152:                disc => 'Discard',
                   14153:                no   => 'No',
                   14154:                yes  => 'Yes',
                   14155:                save => 'Save',
                   14156:     );
                   14157:     my $output = <<"END";
                   14158: <form name="$form" method="post" action="">
                   14159: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14160: <label>
                   14161:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14162: </label>
                   14163: &nbsp;
                   14164: <label>
                   14165:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14166: </span>
                   14167: </p>
                   14168: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14169: <br />$lt{'hows'}
                   14170: <div class="LC_columnSection">
                   14171:   <fieldset>
                   14172:     <legend>$lt{'cont'}</legend>
                   14173:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14174:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14175:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14176:   </fieldset>
                   14177: </div>
                   14178: END
                   14179:     return $output.
1.1055    raeburn  14180:            &start_data_table()."\n".
1.1065    raeburn  14181:            $display."\n".
1.1055    raeburn  14182:            &end_data_table()."\n".
                   14183:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14184:            $hiddenelem.
1.1065    raeburn  14185:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14186:            '</form>';
                   14187: }
                   14188: 
                   14189: sub archive_javascript {
1.1056    raeburn  14190:     my ($startcount,$numitems,$titles,$children) = @_;
                   14191:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14192:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14193:     my $scripttag = <<START;
                   14194: <script type="text/javascript">
                   14195: // <![CDATA[
                   14196: 
                   14197: function checkAll(form,prefix) {
                   14198:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14199:     for (var i=0; i < form.elements.length; i++) {
                   14200:         var id = form.elements[i].id;
                   14201:         if ((id != '') && (id != undefined)) {
                   14202:             if (idstr.test(id)) {
                   14203:                 if (form.elements[i].type == 'radio') {
                   14204:                     form.elements[i].checked = true;
1.1056    raeburn  14205:                     var nostart = i-$startcount;
1.1059    raeburn  14206:                     var offset = nostart%7;
                   14207:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14208:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14209:                 }
                   14210:             }
                   14211:         }
                   14212:     }
                   14213: }
                   14214: 
                   14215: function propagateCheck(form,count) {
                   14216:     if (count > 0) {
1.1059    raeburn  14217:         var startelement = $startcount + ((count-1) * 7);
                   14218:         for (var j=1; j<6; j++) {
                   14219:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14220:                 var item = startelement + j; 
                   14221:                 if (form.elements[item].type == 'radio') {
                   14222:                     if (form.elements[item].checked) {
                   14223:                         containerCheck(form,count,j);
                   14224:                         break;
                   14225:                     }
1.1055    raeburn  14226:                 }
                   14227:             }
                   14228:         }
                   14229:     }
                   14230: }
                   14231: 
                   14232: numitems = $numitems
1.1056    raeburn  14233: var titles = new Array(numitems);
                   14234: var parents = new Array(numitems);
1.1055    raeburn  14235: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14236:     parents[i] = new Array;
1.1055    raeburn  14237: }
1.1059    raeburn  14238: var maintitle = '$maintitle';
1.1055    raeburn  14239: 
                   14240: START
                   14241: 
1.1056    raeburn  14242:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14243:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14244:         for (my $i=0; $i<@contents; $i ++) {
                   14245:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14246:         }
                   14247:     }
                   14248: 
1.1056    raeburn  14249:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14250:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14251:     }
                   14252: 
1.1055    raeburn  14253:     $scripttag .= <<END;
                   14254: 
                   14255: function containerCheck(form,count,offset) {
                   14256:     if (count > 0) {
1.1056    raeburn  14257:         dependencyCheck(form,count,offset);
1.1059    raeburn  14258:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14259:         form.elements[item].checked = true;
                   14260:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14261:             if (parents[count].length > 0) {
                   14262:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14263:                     containerCheck(form,parents[count][j],offset);
                   14264:                 }
                   14265:             }
                   14266:         }
                   14267:     }
                   14268: }
                   14269: 
                   14270: function dependencyCheck(form,count,offset) {
                   14271:     if (count > 0) {
1.1059    raeburn  14272:         var chosen = (offset+$startcount)+7*(count-1);
                   14273:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14274:         var currtype = form.elements[depitem].type;
                   14275:         if (form.elements[chosen].value == 'dependency') {
                   14276:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14277:             form.elements[depitem].options.length = 0;
                   14278:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14279:             for (var i=1; i<=numitems; i++) {
                   14280:                 if (i == count) {
                   14281:                     continue;
                   14282:                 }
1.1059    raeburn  14283:                 var startelement = $startcount + (i-1) * 7;
                   14284:                 for (var j=1; j<6; j++) {
                   14285:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14286:                         var item = startelement + j;
                   14287:                         if (form.elements[item].type == 'radio') {
                   14288:                             if (form.elements[item].checked) {
                   14289:                                 if (form.elements[item].value == 'display') {
                   14290:                                     var n = form.elements[depitem].options.length;
                   14291:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14292:                                 }
                   14293:                             }
                   14294:                         }
                   14295:                     }
                   14296:                 }
                   14297:             }
                   14298:         } else {
                   14299:             document.getElementById('arc_depon_'+count).style.display='none';
                   14300:             form.elements[depitem].options.length = 0;
                   14301:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14302:         }
1.1059    raeburn  14303:         titleCheck(form,count,offset);
1.1056    raeburn  14304:     }
                   14305: }
                   14306: 
                   14307: function propagateSelect(form,count,offset) {
                   14308:     if (count > 0) {
1.1065    raeburn  14309:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14310:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14311:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14312:             if (parents[count].length > 0) {
                   14313:                 for (var j=0; j<parents[count].length; j++) {
                   14314:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14315:                 }
                   14316:             }
                   14317:         }
                   14318:     }
                   14319: }
1.1056    raeburn  14320: 
                   14321: function containerSelect(form,count,offset,picked) {
                   14322:     if (count > 0) {
1.1065    raeburn  14323:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14324:         if (form.elements[item].type == 'radio') {
                   14325:             if (form.elements[item].value == 'dependency') {
                   14326:                 if (form.elements[item+1].type == 'select-one') {
                   14327:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14328:                         if (form.elements[item+1].options[i].value == picked) {
                   14329:                             form.elements[item+1].selectedIndex = i;
                   14330:                             break;
                   14331:                         }
                   14332:                     }
                   14333:                 }
                   14334:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14335:                     if (parents[count].length > 0) {
                   14336:                         for (var j=0; j<parents[count].length; j++) {
                   14337:                             containerSelect(form,parents[count][j],offset,picked);
                   14338:                         }
                   14339:                     }
                   14340:                 }
                   14341:             }
                   14342:         }
                   14343:     }
                   14344: }
                   14345: 
1.1059    raeburn  14346: function titleCheck(form,count,offset) {
                   14347:     if (count > 0) {
                   14348:         var chosen = (offset+$startcount)+7*(count-1);
                   14349:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14350:         var currtype = form.elements[depitem].type;
                   14351:         if (form.elements[chosen].value == 'display') {
                   14352:             document.getElementById('arc_title_'+count).style.display='block';
                   14353:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14354:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14355:             }
                   14356:         } else {
                   14357:             document.getElementById('arc_title_'+count).style.display='none';
                   14358:             if (currtype == 'text') { 
                   14359:                 document.getElementById('archive_title_'+count).value='';
                   14360:             }
                   14361:         }
                   14362:     }
                   14363:     return;
                   14364: }
                   14365: 
1.1055    raeburn  14366: // ]]>
                   14367: </script>
                   14368: END
                   14369:     return $scripttag;
                   14370: }
                   14371: 
                   14372: sub process_extracted_files {
1.1067    raeburn  14373:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14374:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14375:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14376:     my @ids=&Apache::lonnet::current_machine_ids();
                   14377:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14378:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14379:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14380:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14381:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14382:         $pathtocheck = "$dir_root/$destination";
                   14383:         $dir = $dir_root;
                   14384:         $ishome = 1;
                   14385:     } else {
                   14386:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14387:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14388:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14389:     }
                   14390:     my $currdir = "$dir_root/$destination";
                   14391:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14392:     if ($env{'form.folderpath'}) {
                   14393:         my @items = split('&',$env{'form.folderpath'});
                   14394:         $folders{'0'} = $items[-2];
1.1099    raeburn  14395:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14396:             $containers{'0'}='page';
                   14397:         } else {  
                   14398:             $containers{'0'}='sequence';
                   14399:         }
1.1055    raeburn  14400:     }
                   14401:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14402:     if ($numitems) {
                   14403:         for (my $i=1; $i<=$numitems; $i++) {
                   14404:             my $path = $env{'form.archive_content_'.$i};
                   14405:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14406:                 my $item = $1;
                   14407:                 $toplevelitems{$item} = $i;
                   14408:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14409:                     $is_dir{$item} = 1;
                   14410:                 }
                   14411:             }
                   14412:         }
                   14413:     }
1.1067    raeburn  14414:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14415:     if (keys(%toplevelitems) > 0) {
                   14416:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14417:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14418:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14419:     }
1.1066    raeburn  14420:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14421:     if ($numitems) {
                   14422:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14423:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14424:             my $path = $env{'form.archive_content_'.$i};
                   14425:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14426:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14427:                     if ($prefix ne '' && $path ne '') {
                   14428:                         if (-e $prefix.$path) {
1.1066    raeburn  14429:                             if ((@archdirs > 0) && 
                   14430:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14431:                                 $todeletedir{$prefix.$path} = 1;
                   14432:                             } else {
                   14433:                                 $todelete{$prefix.$path} = 1;
                   14434:                             }
1.1055    raeburn  14435:                         }
                   14436:                     }
                   14437:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14438:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14439:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14440:                     $docstitle = $env{'form.archive_title_'.$i};
                   14441:                     if ($docstitle eq '') {
                   14442:                         $docstitle = $title;
                   14443:                     }
1.1055    raeburn  14444:                     $outer = 0;
1.1056    raeburn  14445:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14446:                         if (@{$dirorder{$i}} > 0) {
                   14447:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14448:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14449:                                     $outer = $item;
                   14450:                                     last;
                   14451:                                 }
                   14452:                             }
                   14453:                         }
                   14454:                     }
                   14455:                     my ($errtext,$fatal) = 
                   14456:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14457:                                                '/'.$folders{$outer}.'.'.
                   14458:                                                $containers{$outer});
                   14459:                     next if ($fatal);
                   14460:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14461:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14462:                             $mapinner{$i} = time;
1.1055    raeburn  14463:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14464:                             $containers{$i} = 'sequence';
                   14465:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14466:                                       $folders{$i}.'.'.$containers{$i};
                   14467:                             my $newidx = &LONCAPA::map::getresidx();
                   14468:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14469:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14470:                             push(@LONCAPA::map::order,$newidx);
                   14471:                             my ($outtext,$errtext) =
                   14472:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14473:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14474:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14475:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14476:                             unless ($errtext) {
1.1294    raeburn  14477:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14478:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14479:                                             '</li>'."\n";
1.1067    raeburn  14480:                             }
1.1055    raeburn  14481:                         }
                   14482:                     } else {
                   14483:                         if ($context eq 'coursedocs') {
                   14484:                             my $newidx=&LONCAPA::map::getresidx();
                   14485:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14486:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14487:                                       $title;
1.1392    raeburn  14488:                             if (($outer !~ /\D/) &&
                   14489:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14490:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14491:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14492:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14493:                                 }
                   14494:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14495:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14496:                                 }
                   14497:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14498:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14499:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14500:                                         unless ($ishome) {
                   14501:                                             my $fetch = "$newdest{$i}/$title";
                   14502:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14503:                                             $prompttofetch{$fetch} = 1;
                   14504:                                         }
1.1292    raeburn  14505:                                     }
1.1067    raeburn  14506:                                 }
1.1294    raeburn  14507:                                 $LONCAPA::map::resources[$newidx]=
                   14508:                                     $docstitle.':'.$url.':false:normal:res';
                   14509:                                 push(@LONCAPA::map::order, $newidx);
                   14510:                                 my ($outtext,$errtext)=
                   14511:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14512:                                                             $docuname.'/'.$folders{$outer}.
                   14513:                                                             '.'.$containers{$outer},1,1);
                   14514:                                 unless ($errtext) {
                   14515:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14516:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14517:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14518:                                                    '</li>'."\n";
                   14519:                                     }
1.1067    raeburn  14520:                                 }
1.1294    raeburn  14521:                             } else {
                   14522:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14523:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14524:                             }
1.1055    raeburn  14525:                         }
                   14526:                     }
1.1086    raeburn  14527:                 }
                   14528:             } else {
1.1294    raeburn  14529:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14530:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14531:             }
                   14532:         }
                   14533:         for (my $i=1; $i<=$numitems; $i++) {
                   14534:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14535:             my $path = $env{'form.archive_content_'.$i};
                   14536:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14537:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14538:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14539:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14540:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14541:                         my ($itemidx,$fullpath,$relpath);
                   14542:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14543:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14544:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14545:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14546:                                     $itemidx = $j;
1.1056    raeburn  14547:                                 }
                   14548:                             }
1.1086    raeburn  14549:                         }
                   14550:                         if ($itemidx eq '') {
                   14551:                             $itemidx =  0;
                   14552:                         } 
                   14553:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14554:                             if ($mapinner{$referrer{$i}}) {
                   14555:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14556:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14557:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14558:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14559:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14560:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14561:                                             if (!-e $fullpath) {
                   14562:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14563:                                             }
                   14564:                                         }
1.1086    raeburn  14565:                                     } else {
                   14566:                                         last;
1.1056    raeburn  14567:                                     }
1.1086    raeburn  14568:                                 }
                   14569:                             }
                   14570:                         } elsif ($newdest{$referrer{$i}}) {
                   14571:                             $fullpath = $newdest{$referrer{$i}};
                   14572:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14573:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14574:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14575:                                     last;
                   14576:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14577:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14578:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14579:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14580:                                         if (!-e $fullpath) {
                   14581:                                             mkdir($fullpath,0755);
1.1056    raeburn  14582:                                         }
                   14583:                                     }
1.1086    raeburn  14584:                                 } else {
                   14585:                                     last;
1.1056    raeburn  14586:                                 }
1.1055    raeburn  14587:                             }
                   14588:                         }
1.1086    raeburn  14589:                         if ($fullpath ne '') {
                   14590:                             if (-e "$prefix$path") {
1.1292    raeburn  14591:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14592:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14593:                                 }
1.1086    raeburn  14594:                             }
                   14595:                             if (-e "$fullpath/$title") {
                   14596:                                 my $showpath;
                   14597:                                 if ($relpath ne '') {
                   14598:                                     $showpath = "$relpath/$title";
                   14599:                                 } else {
                   14600:                                     $showpath = "/$title";
                   14601:                                 } 
1.1294    raeburn  14602:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14603:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14604:                                            '</li>'."\n";
1.1292    raeburn  14605:                                 unless ($ishome) {
                   14606:                                     my $fetch = "$fullpath/$title";
                   14607:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14608:                                     $prompttofetch{$fetch} = 1;
                   14609:                                 }
1.1086    raeburn  14610:                             }
                   14611:                         }
1.1055    raeburn  14612:                     }
1.1086    raeburn  14613:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14614:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14615:                                     &HTML::Entities::encode($path,'<>&"'),
                   14616:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14617:                                 '<br />';
1.1055    raeburn  14618:                 }
                   14619:             } else {
1.1294    raeburn  14620:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14621:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14622:             }
                   14623:         }
                   14624:         if (keys(%todelete)) {
                   14625:             foreach my $key (keys(%todelete)) {
                   14626:                 unlink($key);
1.1066    raeburn  14627:             }
                   14628:         }
                   14629:         if (keys(%todeletedir)) {
                   14630:             foreach my $key (keys(%todeletedir)) {
                   14631:                 rmdir($key);
                   14632:             }
                   14633:         }
                   14634:         foreach my $dir (sort(keys(%is_dir))) {
                   14635:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14636:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14637:             }
                   14638:         }
1.1067    raeburn  14639:         if ($result ne '') {
                   14640:             $output .= '<ul>'."\n".
                   14641:                        $result."\n".
                   14642:                        '</ul>';
                   14643:         }
                   14644:         unless ($ishome) {
                   14645:             my $replicationfail;
                   14646:             foreach my $item (keys(%prompttofetch)) {
                   14647:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14648:                 unless ($fetchresult eq 'ok') {
                   14649:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14650:                 }
                   14651:             }
                   14652:             if ($replicationfail) {
                   14653:                 $output .= '<p class="LC_error">'.
                   14654:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14655:                            $replicationfail.
                   14656:                            '</ul></p>';
                   14657:             }
                   14658:         }
1.1055    raeburn  14659:     } else {
                   14660:         $warning = &mt('No items found in archive.');
                   14661:     }
                   14662:     if ($error) {
                   14663:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14664:                    $error.'</p>'."\n";
                   14665:     }
                   14666:     if ($warning) {
                   14667:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14668:     }
                   14669:     return $output;
                   14670: }
                   14671: 
1.1066    raeburn  14672: sub cleanup_empty_dirs {
                   14673:     my ($path) = @_;
                   14674:     if (($path ne '') && (-d $path)) {
                   14675:         if (opendir(my $dirh,$path)) {
                   14676:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14677:             my $numitems = 0;
                   14678:             foreach my $item (@dircontents) {
                   14679:                 if (-d "$path/$item") {
1.1111    raeburn  14680:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14681:                     if (-e "$path/$item") {
                   14682:                         $numitems ++;
                   14683:                     }
                   14684:                 } else {
                   14685:                     $numitems ++;
                   14686:                 }
                   14687:             }
                   14688:             if ($numitems == 0) {
                   14689:                 rmdir($path);
                   14690:             }
                   14691:             closedir($dirh);
                   14692:         }
                   14693:     }
                   14694:     return;
                   14695: }
                   14696: 
1.41      ng       14697: =pod
1.45      matthew  14698: 
1.1162    raeburn  14699: =item * &get_folder_hierarchy()
1.1068    raeburn  14700: 
                   14701: Provides hierarchy of names of folders/sub-folders containing the current
                   14702: item,
                   14703: 
                   14704: Inputs: 3
                   14705:      - $navmap - navmaps object
                   14706: 
                   14707:      - $map - url for map (either the trigger itself, or map containing
                   14708:                            the resource, which is the trigger).
                   14709: 
                   14710:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14711: 
                   14712: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14713: 
                   14714: =cut
                   14715: 
                   14716: sub get_folder_hierarchy {
                   14717:     my ($navmap,$map,$showitem) = @_;
                   14718:     my @pathitems;
                   14719:     if (ref($navmap)) {
                   14720:         my $mapres = $navmap->getResourceByUrl($map);
                   14721:         if (ref($mapres)) {
                   14722:             my $pcslist = $mapres->map_hierarchy();
                   14723:             if ($pcslist ne '') {
                   14724:                 my @pcs = split(/,/,$pcslist);
                   14725:                 foreach my $pc (@pcs) {
                   14726:                     if ($pc == 1) {
1.1129    raeburn  14727:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14728:                     } else {
                   14729:                         my $res = $navmap->getByMapPc($pc);
                   14730:                         if (ref($res)) {
                   14731:                             my $title = $res->compTitle();
                   14732:                             $title =~ s/\W+/_/g;
                   14733:                             if ($title ne '') {
                   14734:                                 push(@pathitems,$title);
                   14735:                             }
                   14736:                         }
                   14737:                     }
                   14738:                 }
                   14739:             }
1.1071    raeburn  14740:             if ($showitem) {
                   14741:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14742:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14743:                 } else {
                   14744:                     my $maptitle = $mapres->compTitle();
                   14745:                     $maptitle =~ s/\W+/_/g;
                   14746:                     if ($maptitle ne '') {
                   14747:                         push(@pathitems,$maptitle);
                   14748:                     }
1.1068    raeburn  14749:                 }
                   14750:             }
                   14751:         }
                   14752:     }
                   14753:     return @pathitems;
                   14754: }
                   14755: 
                   14756: =pod
                   14757: 
1.1015    raeburn  14758: =item * &get_turnedin_filepath()
                   14759: 
                   14760: Determines path in a user's portfolio file for storage of files uploaded
                   14761: to a specific essayresponse or dropbox item.
                   14762: 
                   14763: Inputs: 3 required + 1 optional.
                   14764: $symb is symb for resource, $uname and $udom are for current user (required).
                   14765: $caller is optional (can be "submission", if routine is called when storing
                   14766: an upoaded file when "Submit Answer" button was pressed).
                   14767: 
                   14768: Returns array containing $path and $multiresp. 
                   14769: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14770: than one file upload item.  Callers of routine should append partid as a 
                   14771: subdirectory to $path in cases where $multiresp is 1.
                   14772: 
                   14773: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14774: 
                   14775: =cut
                   14776: 
                   14777: sub get_turnedin_filepath {
                   14778:     my ($symb,$uname,$udom,$caller) = @_;
                   14779:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14780:     my $turnindir;
                   14781:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14782:     $turnindir = $userhash{'turnindir'};
                   14783:     my ($path,$multiresp);
                   14784:     if ($turnindir eq '') {
                   14785:         if ($caller eq 'submission') {
                   14786:             $turnindir = &mt('turned in');
                   14787:             $turnindir =~ s/\W+/_/g;
                   14788:             my %newhash = (
                   14789:                             'turnindir' => $turnindir,
                   14790:                           );
                   14791:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14792:         }
                   14793:     }
                   14794:     if ($turnindir ne '') {
                   14795:         $path = '/'.$turnindir.'/';
                   14796:         my ($multipart,$turnin,@pathitems);
                   14797:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14798:         if (defined($navmap)) {
                   14799:             my $mapres = $navmap->getResourceByUrl($map);
                   14800:             if (ref($mapres)) {
                   14801:                 my $pcslist = $mapres->map_hierarchy();
                   14802:                 if ($pcslist ne '') {
                   14803:                     foreach my $pc (split(/,/,$pcslist)) {
                   14804:                         my $res = $navmap->getByMapPc($pc);
                   14805:                         if (ref($res)) {
                   14806:                             my $title = $res->compTitle();
                   14807:                             $title =~ s/\W+/_/g;
                   14808:                             if ($title ne '') {
1.1149    raeburn  14809:                                 if (($pc > 1) && (length($title) > 12)) {
                   14810:                                     $title = substr($title,0,12);
                   14811:                                 }
1.1015    raeburn  14812:                                 push(@pathitems,$title);
                   14813:                             }
                   14814:                         }
                   14815:                     }
                   14816:                 }
                   14817:                 my $maptitle = $mapres->compTitle();
                   14818:                 $maptitle =~ s/\W+/_/g;
                   14819:                 if ($maptitle ne '') {
1.1149    raeburn  14820:                     if (length($maptitle) > 12) {
                   14821:                         $maptitle = substr($maptitle,0,12);
                   14822:                     }
1.1015    raeburn  14823:                     push(@pathitems,$maptitle);
                   14824:                 }
                   14825:                 unless ($env{'request.state'} eq 'construct') {
                   14826:                     my $res = $navmap->getBySymb($symb);
                   14827:                     if (ref($res)) {
                   14828:                         my $partlist = $res->parts();
                   14829:                         my $totaluploads = 0;
                   14830:                         if (ref($partlist) eq 'ARRAY') {
                   14831:                             foreach my $part (@{$partlist}) {
                   14832:                                 my @types = $res->responseType($part);
                   14833:                                 my @ids = $res->responseIds($part);
                   14834:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14835:                                     if ($types[$i] eq 'essay') {
                   14836:                                         my $partid = $part.'_'.$ids[$i];
                   14837:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14838:                                             $totaluploads ++;
                   14839:                                         }
                   14840:                                     }
                   14841:                                 }
                   14842:                             }
                   14843:                             if ($totaluploads > 1) {
                   14844:                                 $multiresp = 1;
                   14845:                             }
                   14846:                         }
                   14847:                     }
                   14848:                 }
                   14849:             } else {
                   14850:                 return;
                   14851:             }
                   14852:         } else {
                   14853:             return;
                   14854:         }
                   14855:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14856:         $restitle =~ s/\W+/_/g;
                   14857:         if ($restitle eq '') {
                   14858:             $restitle = ($resurl =~ m{/[^/]+$});
                   14859:             if ($restitle eq '') {
                   14860:                 $restitle = time;
                   14861:             }
                   14862:         }
1.1149    raeburn  14863:         if (length($restitle) > 12) {
                   14864:             $restitle = substr($restitle,0,12);
                   14865:         }
1.1015    raeburn  14866:         push(@pathitems,$restitle);
                   14867:         $path .= join('/',@pathitems);
                   14868:     }
                   14869:     return ($path,$multiresp);
                   14870: }
                   14871: 
                   14872: =pod
                   14873: 
1.464     albertel 14874: =back
1.41      ng       14875: 
1.112     bowersj2 14876: =head1 CSV Upload/Handling functions
1.38      albertel 14877: 
1.41      ng       14878: =over 4
                   14879: 
1.648     raeburn  14880: =item * &upfile_store($r)
1.41      ng       14881: 
                   14882: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14883: needs $env{'form.upfile'}
1.41      ng       14884: returns $datatoken to be put into hidden field
                   14885: 
                   14886: =cut
1.31      albertel 14887: 
                   14888: sub upfile_store {
                   14889:     my $r=shift;
1.258     albertel 14890:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14891:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14892:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14893:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14894: 
1.1299    raeburn  14895:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14896:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14897:                                      time.'_'.$$);
                   14898:     return if ($datatoken eq '');
                   14899: 
1.31      albertel 14900:     {
1.158     raeburn  14901:         my $datafile = $r->dir_config('lonDaemons').
                   14902:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14903:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14904:             print $fh $env{'form.upfile'};
1.158     raeburn  14905:             close($fh);
                   14906:         }
1.31      albertel 14907:     }
                   14908:     return $datatoken;
                   14909: }
                   14910: 
1.56      matthew  14911: =pod
                   14912: 
1.1290    raeburn  14913: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14914: 
                   14915: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14916: $datatoken is the name to assign to the temporary file.
1.258     albertel 14917: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14918: 
                   14919: =cut
1.31      albertel 14920: 
                   14921: sub load_tmp_file {
1.1290    raeburn  14922:     my ($r,$datatoken) = @_;
                   14923:     return if ($datatoken eq '');
1.31      albertel 14924:     my @studentdata=();
                   14925:     {
1.158     raeburn  14926:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14927:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14928:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14929:             @studentdata=<$fh>;
                   14930:             close($fh);
                   14931:         }
1.31      albertel 14932:     }
1.258     albertel 14933:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14934: }
                   14935: 
1.1290    raeburn  14936: sub valid_datatoken {
                   14937:     my ($datatoken) = @_;
1.1325    raeburn  14938:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14939:         return $datatoken;
                   14940:     }
                   14941:     return;
                   14942: }
                   14943: 
1.56      matthew  14944: =pod
                   14945: 
1.648     raeburn  14946: =item * &upfile_record_sep()
1.41      ng       14947: 
                   14948: Separate uploaded file into records
                   14949: returns array of records,
1.258     albertel 14950: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14951: 
                   14952: =cut
1.31      albertel 14953: 
                   14954: sub upfile_record_sep {
1.258     albertel 14955:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14956:     } else {
1.248     albertel 14957: 	my @records;
1.258     albertel 14958: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14959: 	    if ($line=~/^\s*$/) { next; }
                   14960: 	    push(@records,$line);
                   14961: 	}
                   14962: 	return @records;
1.31      albertel 14963:     }
                   14964: }
                   14965: 
1.56      matthew  14966: =pod
                   14967: 
1.648     raeburn  14968: =item * &record_sep($record)
1.41      ng       14969: 
1.258     albertel 14970: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14971: 
                   14972: =cut
                   14973: 
1.263     www      14974: sub takeleft {
                   14975:     my $index=shift;
                   14976:     return substr('0000'.$index,-4,4);
                   14977: }
                   14978: 
1.31      albertel 14979: sub record_sep {
                   14980:     my $record=shift;
                   14981:     my %components=();
1.258     albertel 14982:     if ($env{'form.upfiletype'} eq 'xml') {
                   14983:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14984:         my $i=0;
1.356     albertel 14985:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14986:             $field=~s/^(\"|\')//;
                   14987:             $field=~s/(\"|\')$//;
1.263     www      14988:             $components{&takeleft($i)}=$field;
1.31      albertel 14989:             $i++;
                   14990:         }
1.258     albertel 14991:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14992:         my $i=0;
1.356     albertel 14993:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14994:             $field=~s/^(\"|\')//;
                   14995:             $field=~s/(\"|\')$//;
1.263     www      14996:             $components{&takeleft($i)}=$field;
1.31      albertel 14997:             $i++;
                   14998:         }
                   14999:     } else {
1.561     www      15000:         my $separator=',';
1.480     banghart 15001:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15002:             $separator=';';
1.480     banghart 15003:         }
1.31      albertel 15004:         my $i=0;
1.561     www      15005: # the character we are looking for to indicate the end of a quote or a record 
                   15006:         my $looking_for=$separator;
                   15007: # do not add the characters to the fields
                   15008:         my $ignore=0;
                   15009: # we just encountered a separator (or the beginning of the record)
                   15010:         my $just_found_separator=1;
                   15011: # store the field we are working on here
                   15012:         my $field='';
                   15013: # work our way through all characters in record
                   15014:         foreach my $character ($record=~/(.)/g) {
                   15015:             if ($character eq $looking_for) {
                   15016:                if ($character ne $separator) {
                   15017: # Found the end of a quote, again looking for separator
                   15018:                   $looking_for=$separator;
                   15019:                   $ignore=1;
                   15020:                } else {
                   15021: # Found a separator, store away what we got
                   15022:                   $components{&takeleft($i)}=$field;
                   15023: 	          $i++;
                   15024:                   $just_found_separator=1;
                   15025:                   $ignore=0;
                   15026:                   $field='';
                   15027:                }
                   15028:                next;
                   15029:             }
                   15030: # single or double quotation marks after a separator indicate beginning of a quote
                   15031: # we are now looking for the end of the quote and need to ignore separators
                   15032:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15033:                $looking_for=$character;
                   15034:                next;
                   15035:             }
                   15036: # ignore would be true after we reached the end of a quote
                   15037:             if ($ignore) { next; }
                   15038:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15039:             $field.=$character;
                   15040:             $just_found_separator=0; 
1.31      albertel 15041:         }
1.561     www      15042: # catch the very last entry, since we never encountered the separator
                   15043:         $components{&takeleft($i)}=$field;
1.31      albertel 15044:     }
                   15045:     return %components;
                   15046: }
                   15047: 
1.144     matthew  15048: ######################################################
                   15049: ######################################################
                   15050: 
1.56      matthew  15051: =pod
                   15052: 
1.648     raeburn  15053: =item * &upfile_select_html()
1.41      ng       15054: 
1.144     matthew  15055: Return HTML code to select a file from the users machine and specify 
                   15056: the file type.
1.41      ng       15057: 
                   15058: =cut
                   15059: 
1.144     matthew  15060: ######################################################
                   15061: ######################################################
1.31      albertel 15062: sub upfile_select_html {
1.144     matthew  15063:     my %Types = (
                   15064:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15065:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15066:                  space => &mt('Space separated'),
                   15067:                  tab   => &mt('Tabulator separated'),
                   15068: #                 xml   => &mt('HTML/XML'),
                   15069:                  );
                   15070:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15071:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15072:     foreach my $type (sort(keys(%Types))) {
                   15073:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15074:     }
                   15075:     $Str .= "</select>\n";
                   15076:     return $Str;
1.31      albertel 15077: }
                   15078: 
1.301     albertel 15079: sub get_samples {
                   15080:     my ($records,$toget) = @_;
                   15081:     my @samples=({});
                   15082:     my $got=0;
                   15083:     foreach my $rec (@$records) {
                   15084: 	my %temp = &record_sep($rec);
                   15085: 	if (! grep(/\S/, values(%temp))) { next; }
                   15086: 	if (%temp) {
                   15087: 	    $samples[$got]=\%temp;
                   15088: 	    $got++;
                   15089: 	    if ($got == $toget) { last; }
                   15090: 	}
                   15091:     }
                   15092:     return \@samples;
                   15093: }
                   15094: 
1.144     matthew  15095: ######################################################
                   15096: ######################################################
                   15097: 
1.56      matthew  15098: =pod
                   15099: 
1.648     raeburn  15100: =item * &csv_print_samples($r,$records)
1.41      ng       15101: 
                   15102: Prints a table of sample values from each column uploaded $r is an
                   15103: Apache Request ref, $records is an arrayref from
                   15104: &Apache::loncommon::upfile_record_sep
                   15105: 
                   15106: =cut
                   15107: 
1.144     matthew  15108: ######################################################
                   15109: ######################################################
1.31      albertel 15110: sub csv_print_samples {
                   15111:     my ($r,$records) = @_;
1.662     bisitz   15112:     my $samples = &get_samples($records,5);
1.301     albertel 15113: 
1.594     raeburn  15114:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15115:               &start_data_table_header_row());
1.356     albertel 15116:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15117:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15118:     $r->print(&end_data_table_header_row());
1.301     albertel 15119:     foreach my $hash (@$samples) {
1.594     raeburn  15120: 	$r->print(&start_data_table_row());
1.356     albertel 15121: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15122: 	    $r->print('<td>');
1.356     albertel 15123: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15124: 	    $r->print('</td>');
                   15125: 	}
1.594     raeburn  15126: 	$r->print(&end_data_table_row());
1.31      albertel 15127:     }
1.594     raeburn  15128:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15129: }
                   15130: 
1.144     matthew  15131: ######################################################
                   15132: ######################################################
                   15133: 
1.56      matthew  15134: =pod
                   15135: 
1.648     raeburn  15136: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15137: 
                   15138: Prints a table to create associations between values and table columns.
1.144     matthew  15139: 
1.41      ng       15140: $r is an Apache Request ref,
                   15141: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15142: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15143: 
                   15144: =cut
                   15145: 
1.144     matthew  15146: ######################################################
                   15147: ######################################################
1.31      albertel 15148: sub csv_print_select_table {
                   15149:     my ($r,$records,$d) = @_;
1.301     albertel 15150:     my $i=0;
                   15151:     my $samples = &get_samples($records,1);
1.144     matthew  15152:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15153: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15154:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15155:               '<th>'.&mt('Column').'</th>'.
                   15156:               &end_data_table_header_row()."\n");
1.356     albertel 15157:     foreach my $array_ref (@$d) {
                   15158: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15159: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15160: 
1.875     bisitz   15161: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15162: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15163: 	$r->print('<option value="none"></option>');
1.356     albertel 15164: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15165: 	    $r->print('<option value="'.$sample.'"'.
                   15166:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15167:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15168: 	}
1.594     raeburn  15169: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15170: 	$i++;
                   15171:     }
1.594     raeburn  15172:     $r->print(&end_data_table());
1.31      albertel 15173:     $i--;
                   15174:     return $i;
                   15175: }
1.56      matthew  15176: 
1.144     matthew  15177: ######################################################
                   15178: ######################################################
                   15179: 
1.56      matthew  15180: =pod
1.31      albertel 15181: 
1.648     raeburn  15182: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15183: 
                   15184: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15185: 
                   15186: $r is an Apache Request ref,
                   15187: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15188: $d is an array of 2 element arrays (internal name, displayed name)
                   15189: 
                   15190: =cut
                   15191: 
1.144     matthew  15192: ######################################################
                   15193: ######################################################
1.31      albertel 15194: sub csv_samples_select_table {
                   15195:     my ($r,$records,$d) = @_;
                   15196:     my $i=0;
1.144     matthew  15197:     #
1.662     bisitz   15198:     my $max_samples = 5;
                   15199:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15200:     $r->print(&start_data_table().
                   15201:               &start_data_table_header_row().'<th>'.
                   15202:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15203:               &end_data_table_header_row());
1.301     albertel 15204: 
                   15205:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15206: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15207: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15208: 	foreach my $option (@$d) {
                   15209: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15210: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15211:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15212:                       $display.'</option>');
1.31      albertel 15213: 	}
                   15214: 	$r->print('</select></td><td>');
1.662     bisitz   15215: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15216: 	    if (defined($samples->[$line]{$key})) { 
                   15217: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15218: 	    }
                   15219: 	}
1.594     raeburn  15220: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15221: 	$i++;
                   15222:     }
1.594     raeburn  15223:     $r->print(&end_data_table());
1.31      albertel 15224:     $i--;
                   15225:     return($i);
1.115     matthew  15226: }
                   15227: 
1.144     matthew  15228: ######################################################
                   15229: ######################################################
                   15230: 
1.115     matthew  15231: =pod
                   15232: 
1.648     raeburn  15233: =item * &clean_excel_name($name)
1.115     matthew  15234: 
                   15235: Returns a replacement for $name which does not contain any illegal characters.
                   15236: 
                   15237: =cut
                   15238: 
1.144     matthew  15239: ######################################################
                   15240: ######################################################
1.115     matthew  15241: sub clean_excel_name {
                   15242:     my ($name) = @_;
                   15243:     $name =~ s/[:\*\?\/\\]//g;
                   15244:     if (length($name) > 31) {
                   15245:         $name = substr($name,0,31);
                   15246:     }
                   15247:     return $name;
1.25      albertel 15248: }
1.84      albertel 15249: 
1.85      albertel 15250: =pod
                   15251: 
1.648     raeburn  15252: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15253: 
                   15254: Returns either 1 or undef
                   15255: 
                   15256: 1 if the part is to be hidden, undef if it is to be shown
                   15257: 
                   15258: Arguments are:
                   15259: 
                   15260: $id the id of the part to be checked
                   15261: $symb, optional the symb of the resource to check
                   15262: $udom, optional the domain of the user to check for
                   15263: $uname, optional the username of the user to check for
                   15264: 
                   15265: =cut
1.84      albertel 15266: 
                   15267: sub check_if_partid_hidden {
                   15268:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15269:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15270: 					 $symb,$udom,$uname);
1.141     albertel 15271:     my $truth=1;
                   15272:     #if the string starts with !, then the list is the list to show not hide
                   15273:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15274:     my @hiddenlist=split(/,/,$hiddenparts);
                   15275:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15276: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15277:     }
1.141     albertel 15278:     return !$truth;
1.84      albertel 15279: }
1.127     matthew  15280: 
1.138     matthew  15281: 
                   15282: ############################################################
                   15283: ############################################################
                   15284: 
                   15285: =pod
                   15286: 
1.157     matthew  15287: =back 
                   15288: 
1.138     matthew  15289: =head1 cgi-bin script and graphing routines
                   15290: 
1.157     matthew  15291: =over 4
                   15292: 
1.648     raeburn  15293: =item * &get_cgi_id()
1.138     matthew  15294: 
                   15295: Inputs: none
                   15296: 
                   15297: Returns an id which can be used to pass environment variables
                   15298: to various cgi-bin scripts.  These environment variables will
                   15299: be removed from the users environment after a given time by
                   15300: the routine &Apache::lonnet::transfer_profile_to_env.
                   15301: 
                   15302: =cut
                   15303: 
                   15304: ############################################################
                   15305: ############################################################
1.152     albertel 15306: my $uniq=0;
1.136     matthew  15307: sub get_cgi_id {
1.154     albertel 15308:     $uniq=($uniq+1)%100000;
1.280     albertel 15309:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15310: }
                   15311: 
1.127     matthew  15312: ############################################################
                   15313: ############################################################
                   15314: 
                   15315: =pod
                   15316: 
1.648     raeburn  15317: =item * &DrawBarGraph()
1.127     matthew  15318: 
1.138     matthew  15319: Facilitates the plotting of data in a (stacked) bar graph.
                   15320: Puts plot definition data into the users environment in order for 
                   15321: graph.png to plot it.  Returns an <img> tag for the plot.
                   15322: The bars on the plot are labeled '1','2',...,'n'.
                   15323: 
                   15324: Inputs:
                   15325: 
                   15326: =over 4
                   15327: 
                   15328: =item $Title: string, the title of the plot
                   15329: 
                   15330: =item $xlabel: string, text describing the X-axis of the plot
                   15331: 
                   15332: =item $ylabel: string, text describing the Y-axis of the plot
                   15333: 
                   15334: =item $Max: scalar, the maximum Y value to use in the plot
                   15335: If $Max is < any data point, the graph will not be rendered.
                   15336: 
1.140     matthew  15337: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15338: they are plotted.  If undefined, default values will be used.
                   15339: 
1.178     matthew  15340: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15341: 
1.138     matthew  15342: =item @Values: An array of array references.  Each array reference holds data
                   15343: to be plotted in a stacked bar chart.
                   15344: 
1.239     matthew  15345: =item If the final element of @Values is a hash reference the key/value
                   15346: pairs will be added to the graph definition.
                   15347: 
1.138     matthew  15348: =back
                   15349: 
                   15350: Returns:
                   15351: 
                   15352: An <img> tag which references graph.png and the appropriate identifying
                   15353: information for the plot.
                   15354: 
1.127     matthew  15355: =cut
                   15356: 
                   15357: ############################################################
                   15358: ############################################################
1.134     matthew  15359: sub DrawBarGraph {
1.178     matthew  15360:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15361:     #
                   15362:     if (! defined($colors)) {
                   15363:         $colors = ['#33ff00', 
                   15364:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15365:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15366:                   ]; 
                   15367:     }
1.228     matthew  15368:     my $extra_settings = {};
                   15369:     if (ref($Values[-1]) eq 'HASH') {
                   15370:         $extra_settings = pop(@Values);
                   15371:     }
1.127     matthew  15372:     #
1.136     matthew  15373:     my $identifier = &get_cgi_id();
                   15374:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15375:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15376:         return '';
                   15377:     }
1.225     matthew  15378:     #
                   15379:     my @Labels;
                   15380:     if (defined($labels)) {
                   15381:         @Labels = @$labels;
                   15382:     } else {
                   15383:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15384:             push(@Labels,$i+1);
1.225     matthew  15385:         }
                   15386:     }
                   15387:     #
1.129     matthew  15388:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15389:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15390:     my %ValuesHash;
                   15391:     my $NumSets=1;
                   15392:     foreach my $array (@Values) {
                   15393:         next if (! ref($array));
1.136     matthew  15394:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15395:             join(',',@$array);
1.129     matthew  15396:     }
1.127     matthew  15397:     #
1.136     matthew  15398:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15399:     if ($NumBars < 3) {
                   15400:         $width = 120+$NumBars*32;
1.220     matthew  15401:         $xskip = 1;
1.225     matthew  15402:         $bar_width = 30;
                   15403:     } elsif ($NumBars < 5) {
                   15404:         $width = 120+$NumBars*20;
                   15405:         $xskip = 1;
                   15406:         $bar_width = 20;
1.220     matthew  15407:     } elsif ($NumBars < 10) {
1.136     matthew  15408:         $width = 120+$NumBars*15;
                   15409:         $xskip = 1;
                   15410:         $bar_width = 15;
                   15411:     } elsif ($NumBars <= 25) {
                   15412:         $width = 120+$NumBars*11;
                   15413:         $xskip = 5;
                   15414:         $bar_width = 8;
                   15415:     } elsif ($NumBars <= 50) {
                   15416:         $width = 120+$NumBars*8;
                   15417:         $xskip = 5;
                   15418:         $bar_width = 4;
                   15419:     } else {
                   15420:         $width = 120+$NumBars*8;
                   15421:         $xskip = 5;
                   15422:         $bar_width = 4;
                   15423:     }
                   15424:     #
1.137     matthew  15425:     $Max = 1 if ($Max < 1);
                   15426:     if ( int($Max) < $Max ) {
                   15427:         $Max++;
                   15428:         $Max = int($Max);
                   15429:     }
1.127     matthew  15430:     $Title  = '' if (! defined($Title));
                   15431:     $xlabel = '' if (! defined($xlabel));
                   15432:     $ylabel = '' if (! defined($ylabel));
1.369     www      15433:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15434:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15435:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15436:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15437:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15438:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15439:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15440:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15441:     $ValuesHash{$id.'.height'}   = $height;
                   15442:     $ValuesHash{$id.'.width'}    = $width;
                   15443:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15444:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15445:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15446:     #
1.228     matthew  15447:     # Deal with other parameters
                   15448:     while (my ($key,$value) = each(%$extra_settings)) {
                   15449:         $ValuesHash{$id.'.'.$key} = $value;
                   15450:     }
                   15451:     #
1.646     raeburn  15452:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15453:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15454: }
                   15455: 
                   15456: ############################################################
                   15457: ############################################################
                   15458: 
                   15459: =pod
                   15460: 
1.648     raeburn  15461: =item * &DrawXYGraph()
1.137     matthew  15462: 
1.138     matthew  15463: Facilitates the plotting of data in an XY graph.
                   15464: Puts plot definition data into the users environment in order for 
                   15465: graph.png to plot it.  Returns an <img> tag for the plot.
                   15466: 
                   15467: Inputs:
                   15468: 
                   15469: =over 4
                   15470: 
                   15471: =item $Title: string, the title of the plot
                   15472: 
                   15473: =item $xlabel: string, text describing the X-axis of the plot
                   15474: 
                   15475: =item $ylabel: string, text describing the Y-axis of the plot
                   15476: 
                   15477: =item $Max: scalar, the maximum Y value to use in the plot
                   15478: If $Max is < any data point, the graph will not be rendered.
                   15479: 
                   15480: =item $colors: Array ref containing the hex color codes for the data to be 
                   15481: plotted in.  If undefined, default values will be used.
                   15482: 
                   15483: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15484: 
                   15485: =item $Ydata: Array ref containing Array refs.  
1.185     www      15486: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15487: 
                   15488: =item %Values: hash indicating or overriding any default values which are 
                   15489: passed to graph.png.  
                   15490: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15491: 
                   15492: =back
                   15493: 
                   15494: Returns:
                   15495: 
                   15496: An <img> tag which references graph.png and the appropriate identifying
                   15497: information for the plot.
                   15498: 
1.137     matthew  15499: =cut
                   15500: 
                   15501: ############################################################
                   15502: ############################################################
                   15503: sub DrawXYGraph {
                   15504:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15505:     #
                   15506:     # Create the identifier for the graph
                   15507:     my $identifier = &get_cgi_id();
                   15508:     my $id = 'cgi.'.$identifier;
                   15509:     #
                   15510:     $Title  = '' if (! defined($Title));
                   15511:     $xlabel = '' if (! defined($xlabel));
                   15512:     $ylabel = '' if (! defined($ylabel));
                   15513:     my %ValuesHash = 
                   15514:         (
1.369     www      15515:          $id.'.title'  => &escape($Title),
                   15516:          $id.'.xlabel' => &escape($xlabel),
                   15517:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15518:          $id.'.y_max_value'=> $Max,
                   15519:          $id.'.labels'     => join(',',@$Xlabels),
                   15520:          $id.'.PlotType'   => 'XY',
                   15521:          );
                   15522:     #
                   15523:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15524:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15525:     }
                   15526:     #
                   15527:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15528:         return '';
                   15529:     }
                   15530:     my $NumSets=1;
1.138     matthew  15531:     foreach my $array (@{$Ydata}){
1.137     matthew  15532:         next if (! ref($array));
                   15533:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15534:     }
1.138     matthew  15535:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15536:     #
                   15537:     # Deal with other parameters
                   15538:     while (my ($key,$value) = each(%Values)) {
                   15539:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15540:     }
                   15541:     #
1.646     raeburn  15542:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15543:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15544: }
                   15545: 
                   15546: ############################################################
                   15547: ############################################################
                   15548: 
                   15549: =pod
                   15550: 
1.648     raeburn  15551: =item * &DrawXYYGraph()
1.138     matthew  15552: 
                   15553: Facilitates the plotting of data in an XY graph with two Y axes.
                   15554: Puts plot definition data into the users environment in order for 
                   15555: graph.png to plot it.  Returns an <img> tag for the plot.
                   15556: 
                   15557: Inputs:
                   15558: 
                   15559: =over 4
                   15560: 
                   15561: =item $Title: string, the title of the plot
                   15562: 
                   15563: =item $xlabel: string, text describing the X-axis of the plot
                   15564: 
                   15565: =item $ylabel: string, text describing the Y-axis of the plot
                   15566: 
                   15567: =item $colors: Array ref containing the hex color codes for the data to be 
                   15568: plotted in.  If undefined, default values will be used.
                   15569: 
                   15570: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15571: 
                   15572: =item $Ydata1: The first data set
                   15573: 
                   15574: =item $Min1: The minimum value of the left Y-axis
                   15575: 
                   15576: =item $Max1: The maximum value of the left Y-axis
                   15577: 
                   15578: =item $Ydata2: The second data set
                   15579: 
                   15580: =item $Min2: The minimum value of the right Y-axis
                   15581: 
                   15582: =item $Max2: The maximum value of the left Y-axis
                   15583: 
                   15584: =item %Values: hash indicating or overriding any default values which are 
                   15585: passed to graph.png.  
                   15586: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15587: 
                   15588: =back
                   15589: 
                   15590: Returns:
                   15591: 
                   15592: An <img> tag which references graph.png and the appropriate identifying
                   15593: information for the plot.
1.136     matthew  15594: 
                   15595: =cut
                   15596: 
                   15597: ############################################################
                   15598: ############################################################
1.137     matthew  15599: sub DrawXYYGraph {
                   15600:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15601:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15602:     #
                   15603:     # Create the identifier for the graph
                   15604:     my $identifier = &get_cgi_id();
                   15605:     my $id = 'cgi.'.$identifier;
                   15606:     #
                   15607:     $Title  = '' if (! defined($Title));
                   15608:     $xlabel = '' if (! defined($xlabel));
                   15609:     $ylabel = '' if (! defined($ylabel));
                   15610:     my %ValuesHash = 
                   15611:         (
1.369     www      15612:          $id.'.title'  => &escape($Title),
                   15613:          $id.'.xlabel' => &escape($xlabel),
                   15614:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15615:          $id.'.labels' => join(',',@$Xlabels),
                   15616:          $id.'.PlotType' => 'XY',
                   15617:          $id.'.NumSets' => 2,
1.137     matthew  15618:          $id.'.two_axes' => 1,
                   15619:          $id.'.y1_max_value' => $Max1,
                   15620:          $id.'.y1_min_value' => $Min1,
                   15621:          $id.'.y2_max_value' => $Max2,
                   15622:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15623:          );
                   15624:     #
1.137     matthew  15625:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15626:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15627:     }
                   15628:     #
                   15629:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15630:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15631:         return '';
                   15632:     }
                   15633:     my $NumSets=1;
1.137     matthew  15634:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15635:         next if (! ref($array));
                   15636:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15637:     }
                   15638:     #
                   15639:     # Deal with other parameters
                   15640:     while (my ($key,$value) = each(%Values)) {
                   15641:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15642:     }
                   15643:     #
1.646     raeburn  15644:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15645:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15646: }
                   15647: 
                   15648: ############################################################
                   15649: ############################################################
                   15650: 
                   15651: =pod
                   15652: 
1.157     matthew  15653: =back 
                   15654: 
1.139     matthew  15655: =head1 Statistics helper routines?  
                   15656: 
                   15657: Bad place for them but what the hell.
                   15658: 
1.157     matthew  15659: =over 4
                   15660: 
1.648     raeburn  15661: =item * &chartlink()
1.139     matthew  15662: 
                   15663: Returns a link to the chart for a specific student.  
                   15664: 
                   15665: Inputs:
                   15666: 
                   15667: =over 4
                   15668: 
                   15669: =item $linktext: The text of the link
                   15670: 
                   15671: =item $sname: The students username
                   15672: 
                   15673: =item $sdomain: The students domain
                   15674: 
                   15675: =back
                   15676: 
1.157     matthew  15677: =back
                   15678: 
1.139     matthew  15679: =cut
                   15680: 
                   15681: ############################################################
                   15682: ############################################################
                   15683: sub chartlink {
                   15684:     my ($linktext, $sname, $sdomain) = @_;
                   15685:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15686:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15687:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15688:        '">'.$linktext.'</a>';
1.153     matthew  15689: }
                   15690: 
                   15691: #######################################################
                   15692: #######################################################
                   15693: 
                   15694: =pod
                   15695: 
                   15696: =head1 Course Environment Routines
1.157     matthew  15697: 
                   15698: =over 4
1.153     matthew  15699: 
1.648     raeburn  15700: =item * &restore_course_settings()
1.153     matthew  15701: 
1.648     raeburn  15702: =item * &store_course_settings()
1.153     matthew  15703: 
                   15704: Restores/Store indicated form parameters from the course environment.
                   15705: Will not overwrite existing values of the form parameters.
                   15706: 
                   15707: Inputs: 
                   15708: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15709: 
                   15710: a hash ref describing the data to be stored.  For example:
                   15711:    
                   15712: %Save_Parameters = ('Status' => 'scalar',
                   15713:     'chartoutputmode' => 'scalar',
                   15714:     'chartoutputdata' => 'scalar',
                   15715:     'Section' => 'array',
1.373     raeburn  15716:     'Group' => 'array',
1.153     matthew  15717:     'StudentData' => 'array',
                   15718:     'Maps' => 'array');
                   15719: 
                   15720: Returns: both routines return nothing
                   15721: 
1.631     raeburn  15722: =back
                   15723: 
1.153     matthew  15724: =cut
                   15725: 
                   15726: #######################################################
                   15727: #######################################################
                   15728: sub store_course_settings {
1.496     albertel 15729:     return &store_settings($env{'request.course.id'},@_);
                   15730: }
                   15731: 
                   15732: sub store_settings {
1.153     matthew  15733:     # save to the environment
                   15734:     # appenv the same items, just to be safe
1.300     albertel 15735:     my $udom  = $env{'user.domain'};
                   15736:     my $uname = $env{'user.name'};
1.496     albertel 15737:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15738:     my %SaveHash;
                   15739:     my %AppHash;
                   15740:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15741:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15742:         my $envname = 'environment.'.$basename;
1.258     albertel 15743:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15744:             # Save this value away
                   15745:             if ($type eq 'scalar' &&
1.258     albertel 15746:                 (! exists($env{$envname}) || 
                   15747:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15748:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15749:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15750:             } elsif ($type eq 'array') {
                   15751:                 my $stored_form;
1.258     albertel 15752:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15753:                     $stored_form = join(',',
                   15754:                                         map {
1.369     www      15755:                                             &escape($_);
1.258     albertel 15756:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15757:                 } else {
                   15758:                     $stored_form = 
1.369     www      15759:                         &escape($env{'form.'.$setting});
1.153     matthew  15760:                 }
                   15761:                 # Determine if the array contents are the same.
1.258     albertel 15762:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15763:                     $SaveHash{$basename} = $stored_form;
                   15764:                     $AppHash{$envname}   = $stored_form;
                   15765:                 }
                   15766:             }
                   15767:         }
                   15768:     }
                   15769:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15770:                                           $udom,$uname);
1.153     matthew  15771:     if ($put_result !~ /^(ok|delayed)/) {
                   15772:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15773:                                  'got error:'.$put_result);
                   15774:     }
                   15775:     # Make sure these settings stick around in this session, too
1.646     raeburn  15776:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15777:     return;
                   15778: }
                   15779: 
                   15780: sub restore_course_settings {
1.499     albertel 15781:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15782: }
                   15783: 
                   15784: sub restore_settings {
                   15785:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15786:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15787:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15788:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15789:             '.'.$setting;
1.258     albertel 15790:         if (exists($env{$envname})) {
1.153     matthew  15791:             if ($type eq 'scalar') {
1.258     albertel 15792:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15793:             } elsif ($type eq 'array') {
1.258     albertel 15794:                 $env{'form.'.$setting} = [ 
1.153     matthew  15795:                                            map { 
1.369     www      15796:                                                &unescape($_); 
1.258     albertel 15797:                                            } split(',',$env{$envname})
1.153     matthew  15798:                                            ];
                   15799:             }
                   15800:         }
                   15801:     }
1.127     matthew  15802: }
                   15803: 
1.618     raeburn  15804: #######################################################
                   15805: #######################################################
                   15806: 
                   15807: =pod
                   15808: 
                   15809: =head1 Domain E-mail Routines  
                   15810: 
                   15811: =over 4
                   15812: 
1.648     raeburn  15813: =item * &build_recipient_list()
1.618     raeburn  15814: 
1.1144    raeburn  15815: Build recipient lists for following types of e-mail:
1.766     raeburn  15816: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15817: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15818: module change checking, student/employee ID conflict checks, as
                   15819: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15820: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15821: 
                   15822: Inputs:
1.619     raeburn  15823: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15824: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15825: requestsmail, updatesmail, or idconflictsmail).
                   15826: 
1.619     raeburn  15827: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15828: 
1.619     raeburn  15829: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15830: i.e., predates configuration by DC via domainprefs.pm
                   15831: 
                   15832: $requname username of requester (if mailing type is helpdeskmail)
                   15833: 
                   15834: $requdom domain of requester (if mailing type is helpdeskmail)
                   15835: 
                   15836: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15837: 
1.618     raeburn  15838: 
1.655     raeburn  15839: Returns: comma separated list of addresses to which to send e-mail.
                   15840: 
                   15841: =back
1.618     raeburn  15842: 
                   15843: =cut
                   15844: 
                   15845: ############################################################
                   15846: ############################################################
                   15847: sub build_recipient_list {
1.1297    raeburn  15848:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15849:     my @recipients;
1.1270    raeburn  15850:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15851:     my %domconfig =
1.1270    raeburn  15852:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15853:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15854:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15855:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15856:                 my @contacts = ('adminemail','supportemail');
                   15857:                 foreach my $item (@contacts) {
                   15858:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15859:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15860:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15861:                             push(@recipients,$addr);
                   15862:                         }
1.619     raeburn  15863:                     }
1.1270    raeburn  15864:                 }
                   15865:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15866:                 if ($mailing eq 'helpdeskmail') {
                   15867:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15868:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15869:                         my @ok_bccs;
                   15870:                         foreach my $bcc (@bccs) {
                   15871:                             $bcc =~ s/^\s+//g;
                   15872:                             $bcc =~ s/\s+$//g;
                   15873:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15874:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15875:                                     push(@ok_bccs,$bcc);
                   15876:                                 }
                   15877:                             }
                   15878:                         }
                   15879:                         if (@ok_bccs > 0) {
                   15880:                             $allbcc = join(', ',@ok_bccs);
                   15881:                         }
                   15882:                     }
                   15883:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15884:                 }
                   15885:             }
1.766     raeburn  15886:         } elsif ($origmail ne '') {
1.1270    raeburn  15887:             $lastresort = $origmail;
1.618     raeburn  15888:         }
1.1297    raeburn  15889:         if ($mailing eq 'helpdeskmail') {
                   15890:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15891:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15892:                 my ($inststatus,$inststatus_checked);
                   15893:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15894:                     ($env{'user.domain'} ne 'public')) {
                   15895:                     $inststatus_checked = 1;
                   15896:                     $inststatus = $env{'environment.inststatus'};
                   15897:                 }
                   15898:                 unless ($inststatus_checked) {
                   15899:                     if (($requname ne '') && ($requdom ne '')) {
                   15900:                         if (($requname =~ /^$match_username$/) &&
                   15901:                             ($requdom =~ /^$match_domain$/) &&
                   15902:                             (&Apache::lonnet::domain($requdom))) {
                   15903:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15904:                                                                       $requdom);
                   15905:                             unless ($requhome eq 'no_host') {
                   15906:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15907:                                 $inststatus = $userenv{'inststatus'};
                   15908:                                 $inststatus_checked = 1;
                   15909:                             }
                   15910:                         }
                   15911:                     }
                   15912:                 }
                   15913:                 unless ($inststatus_checked) {
                   15914:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15915:                         my %srch = (srchby     => 'email',
                   15916:                                     srchdomain => $defdom,
                   15917:                                     srchterm   => $reqemail,
                   15918:                                     srchtype   => 'exact');
                   15919:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15920:                         foreach my $uname (keys(%srch_results)) {
                   15921:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15922:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15923:                                 $inststatus_checked = 1;
                   15924:                                 last;
                   15925:                             }
                   15926:                         }
                   15927:                         unless ($inststatus_checked) {
                   15928:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15929:                             if ($dirsrchres eq 'ok') {
                   15930:                                 foreach my $uname (keys(%srch_results)) {
                   15931:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15932:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15933:                                         $inststatus_checked = 1;
                   15934:                                         last;
                   15935:                                     }
                   15936:                                 }
                   15937:                             }
                   15938:                         }
                   15939:                     }
                   15940:                 }
                   15941:                 if ($inststatus ne '') {
                   15942:                     foreach my $status (split(/\:/,$inststatus)) {
                   15943:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15944:                             my @contacts = ('adminemail','supportemail');
                   15945:                             foreach my $item (@contacts) {
                   15946:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15947:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15948:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15949:                                         push(@recipients,$addr);
                   15950:                                     }
                   15951:                                 }
                   15952:                             }
                   15953:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15954:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15955:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15956:                                 my @ok_bccs;
                   15957:                                 foreach my $bcc (@bccs) {
                   15958:                                     $bcc =~ s/^\s+//g;
                   15959:                                     $bcc =~ s/\s+$//g;
                   15960:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15961:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15962:                                             push(@ok_bccs,$bcc);
                   15963:                                         }
                   15964:                                     }
                   15965:                                 }
                   15966:                                 if (@ok_bccs > 0) {
                   15967:                                     $allbcc = join(', ',@ok_bccs);
                   15968:                                 }
                   15969:                             }
                   15970:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15971:                             last;
                   15972:                         }
                   15973:                     }
                   15974:                 }
                   15975:             }
                   15976:         }
1.619     raeburn  15977:     } elsif ($origmail ne '') {
1.1270    raeburn  15978:         $lastresort = $origmail;
                   15979:     }
1.1297    raeburn  15980:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15981:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15982:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15983:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15984:             my %what = (
                   15985:                           perlvar => 1,
                   15986:                        );
                   15987:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15988:             if ($primary) {
                   15989:                 my $gotaddr;
                   15990:                 my ($result,$returnhash) =
                   15991:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15992:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15993:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15994:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15995:                         $gotaddr = 1;
                   15996:                     }
                   15997:                 }
                   15998:                 unless ($gotaddr) {
                   15999:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16000:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16001:                     unless ($uintdom eq $intdom) {
                   16002:                         my %domconfig =
                   16003:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16004:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16005:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16006:                                 my @contacts = ('adminemail','supportemail');
                   16007:                                 foreach my $item (@contacts) {
                   16008:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16009:                                         my $addr = $domconfig{'contacts'}{$item};
                   16010:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16011:                                             push(@recipients,$addr);
                   16012:                                         }
                   16013:                                     }
                   16014:                                 }
                   16015:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16016:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16017:                                 }
                   16018:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16019:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16020:                                     my @ok_bccs;
                   16021:                                     foreach my $bcc (@bccs) {
                   16022:                                         $bcc =~ s/^\s+//g;
                   16023:                                         $bcc =~ s/\s+$//g;
                   16024:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16025:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16026:                                                 push(@ok_bccs,$bcc);
                   16027:                                             }
                   16028:                                         }
                   16029:                                     }
                   16030:                                     if (@ok_bccs > 0) {
                   16031:                                         $allbcc = join(', ',@ok_bccs);
                   16032:                                     }
                   16033:                                 }
                   16034:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16035:                             }
                   16036:                         }
                   16037:                     }
                   16038:                 }
                   16039:             }
                   16040:         }
1.618     raeburn  16041:     }
1.688     raeburn  16042:     if (defined($defmail)) {
                   16043:         if ($defmail ne '') {
                   16044:             push(@recipients,$defmail);
                   16045:         }
1.618     raeburn  16046:     }
                   16047:     if ($otheremails) {
1.619     raeburn  16048:         my @others;
                   16049:         if ($otheremails =~ /,/) {
                   16050:             @others = split(/,/,$otheremails);
1.618     raeburn  16051:         } else {
1.619     raeburn  16052:             push(@others,$otheremails);
                   16053:         }
                   16054:         foreach my $addr (@others) {
                   16055:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16056:                 push(@recipients,$addr);
                   16057:             }
1.618     raeburn  16058:         }
                   16059:     }
1.1298    raeburn  16060:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16061:         if ((!@recipients) && ($lastresort ne '')) {
                   16062:             push(@recipients,$lastresort);
                   16063:         }
                   16064:     } elsif ($lastresort ne '') {
                   16065:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16066:             push(@recipients,$lastresort);
                   16067:         }
                   16068:     }
1.1271    raeburn  16069:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16070:     if (wantarray) {
                   16071:         return ($recipientlist,$allbcc,$addtext);
                   16072:     } else {
                   16073:         return $recipientlist;
                   16074:     }
1.618     raeburn  16075: }
                   16076: 
1.127     matthew  16077: ############################################################
                   16078: ############################################################
1.154     albertel 16079: 
1.655     raeburn  16080: =pod
                   16081: 
1.1224    musolffc 16082: =over 4
                   16083: 
1.1223    musolffc 16084: =item * &mime_email()
                   16085: 
                   16086: Sends an email with a possible attachment
                   16087: 
                   16088: Inputs:
                   16089: 
                   16090: =over 4
                   16091: 
                   16092: from -              Sender's email address
                   16093: 
1.1343    raeburn  16094: replyto -           Reply-To email address
                   16095: 
1.1223    musolffc 16096: to -                Email address of recipient
                   16097: 
                   16098: subject -           Subject of email
                   16099: 
                   16100: body -              Body of email
                   16101: 
                   16102: cc_string -         Carbon copy email address
                   16103: 
                   16104: bcc -               Blind carbon copy email address
                   16105: 
                   16106: attachment_path -   Path of file to be attached
                   16107: 
                   16108: file_name -         Name of file to be attached
                   16109: 
                   16110: attachment_text -   The body of an attachment of type "TEXT"
                   16111: 
                   16112: =back
                   16113: 
                   16114: =back
                   16115: 
                   16116: =cut
                   16117: 
                   16118: ############################################################
                   16119: ############################################################
                   16120: 
                   16121: sub mime_email {
1.1343    raeburn  16122:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16123:         $file_name,$attachment_text) = @_;
                   16124:  
1.1223    musolffc 16125:     my $msg = MIME::Lite->new(
                   16126:              From    => $from,
                   16127:              To      => $to,
                   16128:              Subject => $subject,
                   16129:              Type    =>'TEXT',
                   16130:              Data    => $body,
                   16131:              );
1.1343    raeburn  16132:     if ($replyto ne '') {
                   16133:         $msg->add("Reply-To" => $replyto);
                   16134:     }
1.1223    musolffc 16135:     if ($cc_string ne '') {
                   16136:         $msg->add("Cc" => $cc_string);
                   16137:     }
                   16138:     if ($bcc ne '') {
                   16139:         $msg->add("Bcc" => $bcc);
                   16140:     }
                   16141:     $msg->attr("content-type"         => "text/plain");
                   16142:     $msg->attr("content-type.charset" => "UTF-8");
                   16143:     # Attach file if given
                   16144:     if ($attachment_path) {
                   16145:         unless ($file_name) {
                   16146:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16147:         }
                   16148:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16149:         $msg->attach(Type     => $type,
                   16150:                      Path     => $attachment_path,
                   16151:                      Filename => $file_name
                   16152:                      );
                   16153:     # Otherwise attach text if given
                   16154:     } elsif ($attachment_text) {
                   16155:         $msg->attach(Type => 'TEXT',
                   16156:                      Data => $attachment_text);
                   16157:     }
                   16158:     # Send it
                   16159:     $msg->send('sendmail');
                   16160: }
                   16161: 
                   16162: ############################################################
                   16163: ############################################################
                   16164: 
                   16165: =pod
                   16166: 
1.655     raeburn  16167: =head1 Course Catalog Routines
                   16168: 
                   16169: =over 4
                   16170: 
                   16171: =item * &gather_categories()
                   16172: 
                   16173: Converts category definitions - keys of categories hash stored in  
                   16174: coursecategories in configuration.db on the primary library server in a 
                   16175: domain - to an array.  Also generates javascript and idx hash used to 
                   16176: generate Domain Coordinator interface for editing Course Categories.
                   16177: 
                   16178: Inputs:
1.663     raeburn  16179: 
1.655     raeburn  16180: categories (reference to hash of category definitions).
1.663     raeburn  16181: 
1.655     raeburn  16182: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16183:       categories and subcategories).
1.663     raeburn  16184: 
1.655     raeburn  16185: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16186:       editing Course Categories).
1.663     raeburn  16187: 
1.655     raeburn  16188: jsarray (reference to array of categories used to create Javascript arrays for
                   16189:          Domain Coordinator interface for editing Course Categories).
                   16190: 
                   16191: Returns: nothing
                   16192: 
                   16193: Side effects: populates cats, idx and jsarray. 
                   16194: 
                   16195: =cut
                   16196: 
                   16197: sub gather_categories {
                   16198:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16199:     my %counters;
                   16200:     my $num = 0;
                   16201:     foreach my $item (keys(%{$categories})) {
                   16202:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16203:         if ($container eq '' && $depth == 0) {
                   16204:             $cats->[$depth][$categories->{$item}] = $cat;
                   16205:         } else {
                   16206:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16207:         }
                   16208:         my ($escitem,$tail) = split(/:/,$item,2);
                   16209:         if ($counters{$tail} eq '') {
                   16210:             $counters{$tail} = $num;
                   16211:             $num ++;
                   16212:         }
                   16213:         if (ref($idx) eq 'HASH') {
                   16214:             $idx->{$item} = $counters{$tail};
                   16215:         }
                   16216:         if (ref($jsarray) eq 'ARRAY') {
                   16217:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16218:         }
                   16219:     }
                   16220:     return;
                   16221: }
                   16222: 
                   16223: =pod
                   16224: 
                   16225: =item * &extract_categories()
                   16226: 
                   16227: Used to generate breadcrumb trails for course categories.
                   16228: 
                   16229: Inputs:
1.663     raeburn  16230: 
1.655     raeburn  16231: categories (reference to hash of category definitions).
1.663     raeburn  16232: 
1.655     raeburn  16233: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16234:       categories and subcategories).
1.663     raeburn  16235: 
1.655     raeburn  16236: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16237: 
1.655     raeburn  16238: allitems (reference to hash - key is category key 
                   16239:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16240: 
1.655     raeburn  16241: idx (reference to hash of counters used in Domain Coordinator interface for
                   16242:       editing Course Categories).
1.663     raeburn  16243: 
1.655     raeburn  16244: jsarray (reference to array of categories used to create Javascript arrays for
                   16245:          Domain Coordinator interface for editing Course Categories).
                   16246: 
1.665     raeburn  16247: subcats (reference to hash of arrays containing all subcategories within each 
                   16248:          category, -recursive)
                   16249: 
1.1321    raeburn  16250: maxd (reference to hash used to hold max depth for all top-level categories).
                   16251: 
1.655     raeburn  16252: Returns: nothing
                   16253: 
                   16254: Side effects: populates trails and allitems hash references.
                   16255: 
                   16256: =cut
                   16257: 
                   16258: sub extract_categories {
1.1321    raeburn  16259:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16260:     if (ref($categories) eq 'HASH') {
                   16261:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16262:         if (ref($cats->[0]) eq 'ARRAY') {
                   16263:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16264:                 my $name = $cats->[0][$i];
                   16265:                 my $item = &escape($name).'::0';
                   16266:                 my $trailstr;
                   16267:                 if ($name eq 'instcode') {
                   16268:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16269:                 } elsif ($name eq 'communities') {
                   16270:                     $trailstr = &mt('Communities');
1.1239    raeburn  16271:                 } elsif ($name eq 'placement') {
                   16272:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16273:                 } else {
                   16274:                     $trailstr = $name;
                   16275:                 }
                   16276:                 if ($allitems->{$item} eq '') {
                   16277:                     push(@{$trails},$trailstr);
                   16278:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16279:                 }
                   16280:                 my @parents = ($name);
                   16281:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16282:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16283:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16284:                         if (ref($subcats) eq 'HASH') {
                   16285:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16286:                         }
1.1321    raeburn  16287:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16288:                     }
                   16289:                 } else {
                   16290:                     if (ref($subcats) eq 'HASH') {
                   16291:                         $subcats->{$item} = [];
1.655     raeburn  16292:                     }
1.1321    raeburn  16293:                     if (ref($maxd) eq 'HASH') {
                   16294:                         $maxd->{$name} = 1;
                   16295:                     }
1.655     raeburn  16296:                 }
                   16297:             }
                   16298:         }
                   16299:     }
                   16300:     return;
                   16301: }
                   16302: 
                   16303: =pod
                   16304: 
1.1162    raeburn  16305: =item * &recurse_categories()
1.655     raeburn  16306: 
                   16307: Recursively used to generate breadcrumb trails for course categories.
                   16308: 
                   16309: Inputs:
1.663     raeburn  16310: 
1.655     raeburn  16311: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16312:       categories and subcategories).
1.663     raeburn  16313: 
1.655     raeburn  16314: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16315: 
                   16316: category (current course category, for which breadcrumb trail is being generated).
                   16317: 
                   16318: trails (reference to array of breadcrumb trails for each category).
                   16319: 
1.655     raeburn  16320: allitems (reference to hash - key is category key
                   16321:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16322: 
1.655     raeburn  16323: parents (array containing containers directories for current category, 
                   16324:          back to top level). 
                   16325: 
                   16326: Returns: nothing
                   16327: 
                   16328: Side effects: populates trails and allitems hash references
                   16329: 
                   16330: =cut
                   16331: 
                   16332: sub recurse_categories {
1.1321    raeburn  16333:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16334:     my $shallower = $depth - 1;
                   16335:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16336:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16337:             my $name = $cats->[$depth]{$category}[$k];
                   16338:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16339:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16340:             if ($allitems->{$item} eq '') {
                   16341:                 push(@{$trails},$trailstr);
                   16342:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16343:             }
                   16344:             my $deeper = $depth+1;
                   16345:             push(@{$parents},$category);
1.665     raeburn  16346:             if (ref($subcats) eq 'HASH') {
                   16347:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16348:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16349:                     my $higher;
                   16350:                     if ($j > 0) {
                   16351:                         $higher = &escape($parents->[$j]).':'.
                   16352:                                   &escape($parents->[$j-1]).':'.$j;
                   16353:                     } else {
                   16354:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16355:                     }
                   16356:                     push(@{$subcats->{$higher}},$subcat);
                   16357:                 }
                   16358:             }
                   16359:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16360:                                 $subcats,$maxd);
1.655     raeburn  16361:             pop(@{$parents});
                   16362:         }
                   16363:     } else {
                   16364:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16365:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16366:         if ($allitems->{$item} eq '') {
                   16367:             push(@{$trails},$trailstr);
                   16368:             $allitems->{$item} = scalar(@{$trails})-1;
                   16369:         }
1.1321    raeburn  16370:         if (ref($maxd) eq 'HASH') {
                   16371:             if ($depth > $maxd->{$parents->[0]}) {
                   16372:                 $maxd->{$parents->[0]} = $depth;
                   16373:             }
                   16374:         }
1.655     raeburn  16375:     }
                   16376:     return;
                   16377: }
                   16378: 
1.663     raeburn  16379: =pod
                   16380: 
1.1162    raeburn  16381: =item * &assign_categories_table()
1.663     raeburn  16382: 
                   16383: Create a datatable for display of hierarchical categories in a domain,
                   16384: with checkboxes to allow a course to be categorized. 
                   16385: 
                   16386: Inputs:
                   16387: 
                   16388: cathash - reference to hash of categories defined for the domain (from
                   16389:           configuration.db)
                   16390: 
                   16391: currcat - scalar with an & separated list of categories assigned to a course. 
                   16392: 
1.919     raeburn  16393: type    - scalar contains course type (Course or Community).
                   16394: 
1.1260    raeburn  16395: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16396:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16397: 
1.663     raeburn  16398: Returns: $output (markup to be displayed) 
                   16399: 
                   16400: =cut
                   16401: 
                   16402: sub assign_categories_table {
1.1259    raeburn  16403:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16404:     my $output;
                   16405:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16406:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16407:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16408:         $maxdepth = scalar(@cats);
                   16409:         if (@cats > 0) {
                   16410:             my $itemcount = 0;
                   16411:             if (ref($cats[0]) eq 'ARRAY') {
                   16412:                 my @currcategories;
                   16413:                 if ($currcat ne '') {
                   16414:                     @currcategories = split('&',$currcat);
                   16415:                 }
1.919     raeburn  16416:                 my $table;
1.663     raeburn  16417:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16418:                     my $parent = $cats[0][$i];
1.919     raeburn  16419:                     next if ($parent eq 'instcode');
                   16420:                     if ($type eq 'Community') {
                   16421:                         next unless ($parent eq 'communities');
1.1239    raeburn  16422:                     } elsif ($type eq 'Placement') {
                   16423:                         next unless ($parent eq 'placement');
1.919     raeburn  16424:                     } else {
1.1239    raeburn  16425:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16426:                     }
1.663     raeburn  16427:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16428:                     my $item = &escape($parent).'::0';
                   16429:                     my $checked = '';
                   16430:                     if (@currcategories > 0) {
                   16431:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16432:                             $checked = ' checked="checked"';
1.663     raeburn  16433:                         }
                   16434:                     }
1.919     raeburn  16435:                     my $parent_title = $parent;
                   16436:                     if ($parent eq 'communities') {
                   16437:                         $parent_title = &mt('Communities');
1.1239    raeburn  16438:                     } elsif ($parent eq 'placement') {
                   16439:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16440:                     }
                   16441:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16442:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16443:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16444:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16445:                     my $depth = 1;
                   16446:                     push(@path,$parent);
1.1259    raeburn  16447:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16448:                     pop(@path);
1.919     raeburn  16449:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16450:                     $itemcount ++;
                   16451:                 }
1.919     raeburn  16452:                 if ($itemcount) {
                   16453:                     $output = &Apache::loncommon::start_data_table().
                   16454:                               $table.
                   16455:                               &Apache::loncommon::end_data_table();
                   16456:                 }
1.663     raeburn  16457:             }
                   16458:         }
                   16459:     }
                   16460:     return $output;
                   16461: }
                   16462: 
                   16463: =pod
                   16464: 
1.1162    raeburn  16465: =item * &assign_category_rows()
1.663     raeburn  16466: 
                   16467: Create a datatable row for display of nested categories in a domain,
                   16468: with checkboxes to allow a course to be categorized,called recursively.
                   16469: 
                   16470: Inputs:
                   16471: 
                   16472: itemcount - track row number for alternating colors
                   16473: 
                   16474: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16475:       categories and subcategories.
                   16476: 
                   16477: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16478: 
                   16479: parent - parent of current category item
                   16480: 
                   16481: path - Array containing all categories back up through the hierarchy from the
                   16482:        current category to the top level.
                   16483: 
                   16484: currcategories - reference to array of current categories assigned to the course
                   16485: 
1.1260    raeburn  16486: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16487:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16488: 
1.663     raeburn  16489: Returns: $output (markup to be displayed).
                   16490: 
                   16491: =cut
                   16492: 
                   16493: sub assign_category_rows {
1.1259    raeburn  16494:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16495:     my ($text,$name,$item,$chgstr);
                   16496:     if (ref($cats) eq 'ARRAY') {
                   16497:         my $maxdepth = scalar(@{$cats});
                   16498:         if (ref($cats->[$depth]) eq 'HASH') {
                   16499:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16500:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16501:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16502:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16503:                 for (my $j=0; $j<$numchildren; $j++) {
                   16504:                     $name = $cats->[$depth]{$parent}[$j];
                   16505:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16506:                     my $deeper = $depth+1;
                   16507:                     my $checked = '';
                   16508:                     if (ref($currcategories) eq 'ARRAY') {
                   16509:                         if (@{$currcategories} > 0) {
                   16510:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16511:                                 $checked = ' checked="checked"';
1.663     raeburn  16512:                             }
                   16513:                         }
                   16514:                     }
1.664     raeburn  16515:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16516:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16517:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16518:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16519:                              '</td><td>';
1.663     raeburn  16520:                     if (ref($path) eq 'ARRAY') {
                   16521:                         push(@{$path},$name);
1.1259    raeburn  16522:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16523:                         pop(@{$path});
                   16524:                     }
                   16525:                     $text .= '</td></tr>';
                   16526:                 }
                   16527:                 $text .= '</table></td>';
                   16528:             }
                   16529:         }
                   16530:     }
                   16531:     return $text;
                   16532: }
                   16533: 
1.1181    raeburn  16534: =pod
                   16535: 
                   16536: =back
                   16537: 
                   16538: =cut
                   16539: 
1.655     raeburn  16540: ############################################################
                   16541: ############################################################
                   16542: 
                   16543: 
1.443     albertel 16544: sub commit_customrole {
1.1408    raeburn  16545:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  16546:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  16547:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   16548:                      $context,$othdomby,$requester);
1.630     raeburn  16549:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16550:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  16551:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   16552:     if (wantarray) {
                   16553:         return ($output,$result);
                   16554:     } else {
                   16555:         return $output;
                   16556:     }
1.443     albertel 16557: }
                   16558: 
                   16559: sub commit_standardrole {
1.1408    raeburn  16560:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   16561:         $othdomby,$requester) = @_;
1.1399    raeburn  16562:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  16563:     if ($context eq 'auto') {
                   16564:         $linefeed = "\n";
                   16565:     } else {
                   16566:         $linefeed = "<br />\n";
                   16567:     }  
1.443     albertel 16568:     if ($three eq 'st') {
1.1399    raeburn  16569:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  16570:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   16571:                                       $requester);
1.541     raeburn  16572:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16573:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16574:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16575:         } else {
1.541     raeburn  16576:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16577:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16578:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16579:             if ($context eq 'auto') {
                   16580:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16581:             } else {
                   16582:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16583:                &mt('Add to classlist').': <b>ok</b>';
                   16584:             }
                   16585:             $output .= $linefeed;
1.443     albertel 16586:         }
                   16587:     } else {
                   16588:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16589:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16590:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  16591:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   16592:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  16593:         if ($context eq 'auto') {
                   16594:             $output .= $result.$linefeed;
                   16595:         } else {
                   16596:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16597:         }
1.443     albertel 16598:     }
1.1399    raeburn  16599:     if (wantarray) {
                   16600:         return ($output,$result);
                   16601:     } else {
                   16602:         return $output;
                   16603:     }
1.443     albertel 16604: }
                   16605: 
                   16606: sub commit_studentrole {
1.1116    raeburn  16607:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  16608:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  16609:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16610:     if ($context eq 'auto') {
                   16611:         $linefeed = "\n";
                   16612:     } else {
                   16613:         $linefeed = '<br />'."\n";
                   16614:     }
1.443     albertel 16615:     if (defined($one) && defined($two)) {
                   16616:         my $cid=$one.'_'.$two;
                   16617:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16618:         my $secchange = 0;
                   16619:         my $expire_role_result;
                   16620:         my $modify_section_result;
1.628     raeburn  16621:         if ($oldsec ne '-1') { 
                   16622:             if ($oldsec ne $sec) {
1.443     albertel 16623:                 $secchange = 1;
1.628     raeburn  16624:                 my $now = time;
1.443     albertel 16625:                 my $uurl='/'.$cid;
                   16626:                 $uurl=~s/\_/\//g;
                   16627:                 if ($oldsec) {
                   16628:                     $uurl.='/'.$oldsec;
                   16629:                 }
1.626     raeburn  16630:                 $oldsecurl = $uurl;
1.628     raeburn  16631:                 $expire_role_result = 
1.1408    raeburn  16632:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   16633:                                                 '','','',$context,$othdomby,$requester);
                   16634:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  16635:                     if ($expire_role_result eq 'refused') {
                   16636:                         my @roles = ('st');
                   16637:                         my @statuses = ('previous');
                   16638:                         my @roledoms = ($one);
                   16639:                         my $withsec = 1;
                   16640:                         my %roleshash = 
                   16641:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16642:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16643:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16644:                             my ($oldstart,$oldend) = 
                   16645:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16646:                             if ($oldend > 0 && $oldend <= $now) {
                   16647:                                 $expire_role_result = 'ok';
                   16648:                             }
                   16649:                         }
                   16650:                     }
                   16651:                 }
1.443     albertel 16652:                 $result = $expire_role_result;
                   16653:             }
                   16654:         }
                   16655:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16656:             $modify_section_result = 
                   16657:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16658:                                                            undef,undef,undef,$sec,
                   16659:                                                            $end,$start,'','',$cid,
1.1408    raeburn  16660:                                                            '',$context,$credits,'',
                   16661:                                                            $othdomby,$requester);
1.443     albertel 16662:             if ($modify_section_result =~ /^ok/) {
                   16663:                 if ($secchange == 1) {
1.628     raeburn  16664:                     if ($sec eq '') {
                   16665:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16666:                     } else {
                   16667:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16668:                     }
1.443     albertel 16669:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16670:                     if ($sec eq '') {
                   16671:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16672:                     } else {
                   16673:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16674:                     }
1.443     albertel 16675:                 } else {
1.628     raeburn  16676:                     if ($sec eq '') {
                   16677:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16678:                     } else {
                   16679:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16680:                     }
1.443     albertel 16681:                 }
                   16682:             } else {
1.1115    raeburn  16683:                 if ($secchange) { 
1.628     raeburn  16684:                     $$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;
                   16685:                 } else {
                   16686:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16687:                 }
1.443     albertel 16688:             }
                   16689:             $result = $modify_section_result;
                   16690:         } elsif ($secchange == 1) {
1.628     raeburn  16691:             if ($oldsec eq '') {
1.1103    raeburn  16692:                 $$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  16693:             } else {
                   16694:                 $$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;
                   16695:             }
1.626     raeburn  16696:             if ($expire_role_result eq 'refused') {
                   16697:                 my $newsecurl = '/'.$cid;
                   16698:                 $newsecurl =~ s/\_/\//g;
                   16699:                 if ($sec ne '') {
                   16700:                     $newsecurl.='/'.$sec;
                   16701:                 }
                   16702:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16703:                     if ($sec eq '') {
                   16704:                         $$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;
                   16705:                     } else {
                   16706:                         $$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;
                   16707:                     }
                   16708:                 }
                   16709:             }
1.443     albertel 16710:         }
                   16711:     } else {
1.626     raeburn  16712:         $$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 16713:         $result = "error: incomplete course id\n";
                   16714:     }
                   16715:     return $result;
                   16716: }
                   16717: 
1.1108    raeburn  16718: sub show_role_extent {
                   16719:     my ($scope,$context,$role) = @_;
                   16720:     $scope =~ s{^/}{};
                   16721:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16722:     push(@courseroles,'co');
                   16723:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16724:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16725:         $scope =~ s{/}{_};
                   16726:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16727:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16728:         my ($audom,$auname) = split(/\//,$scope);
                   16729:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16730:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16731:     } else {
                   16732:         $scope =~ s{/$}{};
                   16733:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16734:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16735:     }
                   16736: }
                   16737: 
1.443     albertel 16738: ############################################################
                   16739: ############################################################
                   16740: 
1.566     albertel 16741: sub check_clone {
1.578     raeburn  16742:     my ($args,$linefeed) = @_;
1.566     albertel 16743:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16744:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16745:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16746:     my $clonetitle;
                   16747:     my @clonemsg;
1.566     albertel 16748:     my $can_clone = 0;
1.944     raeburn  16749:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16750:     if ($lctype ne 'community') {
                   16751:         $lctype = 'course';
                   16752:     }
1.566     albertel 16753:     if ($clonehome eq 'no_host') {
1.944     raeburn  16754:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16755:             push(@clonemsg,({
                   16756:                               mt => 'No new community created.',
                   16757:                               args => [],
                   16758:                             },
                   16759:                             {
                   16760:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16761:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16762:                             }));
1.908     raeburn  16763:         } else {
1.1344    raeburn  16764:             push(@clonemsg,({
                   16765:                               mt => 'No new course created.',
                   16766:                               args => [],
                   16767:                             },
                   16768:                             {
                   16769:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16770:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16771:                             }));
                   16772:         }
1.566     albertel 16773:     } else {
                   16774: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16775:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16776:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16777:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16778:                 push(@clonemsg,({
                   16779:                                   mt => 'No new community created.',
                   16780:                                   args => [],
                   16781:                                 },
                   16782:                                 {
                   16783:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16784:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16785:                                 }));
                   16786:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16787:             }
                   16788:         }
1.1262    raeburn  16789: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16790:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16791: 	    $can_clone = 1;
                   16792: 	} else {
1.1221    raeburn  16793: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16794: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16795:             if ($clonehash{'cloners'} eq '') {
                   16796:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16797:                 if ($domdefs{'canclone'}) {
                   16798:                     unless ($domdefs{'canclone'} eq 'none') {
                   16799:                         if ($domdefs{'canclone'} eq 'domain') {
                   16800:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16801:                                 $can_clone = 1;
                   16802:                             }
                   16803:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16804:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16805:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16806:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16807:                                 $can_clone = 1;
                   16808:                             }
                   16809:                         }
                   16810:                     }
                   16811:                 }
1.578     raeburn  16812:             } else {
1.1221    raeburn  16813: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16814:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16815:                     $can_clone = 1;
1.1221    raeburn  16816:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16817:                     $can_clone = 1;
1.1225    raeburn  16818:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16819:                     $can_clone = 1;
1.1221    raeburn  16820:                 }
                   16821:                 unless ($can_clone) {
1.1225    raeburn  16822:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16823:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16824:                         my (%gotdomdefaults,%gotcodedefaults);
                   16825:                         foreach my $cloner (@cloners) {
                   16826:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16827:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16828:                                 my (%codedefaults,@code_order);
                   16829:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16830:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16831:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16832:                                     }
                   16833:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16834:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16835:                                     }
                   16836:                                 } else {
                   16837:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16838:                                                                             \%codedefaults,
                   16839:                                                                             \@code_order);
                   16840:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16841:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16842:                                 }
                   16843:                                 if (@code_order > 0) {
                   16844:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16845:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16846:                                                                                 $args->{'crscode'})) {
                   16847:                                         $can_clone = 1;
                   16848:                                         last;
                   16849:                                     }
                   16850:                                 }
                   16851:                             }
                   16852:                         }
                   16853:                     }
1.1225    raeburn  16854:                 }
                   16855:             }
                   16856:             unless ($can_clone) {
                   16857:                 my $ccrole = 'cc';
                   16858:                 if ($args->{'crstype'} eq 'Community') {
                   16859:                     $ccrole = 'co';
                   16860:                 }
                   16861: 	        my %roleshash =
                   16862: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16863: 					          $args->{'ccdomain'},
                   16864:                                                   'userroles',['active'],[$ccrole],
                   16865: 					          [$args->{'clonedomain'}]);
                   16866: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16867:                     $can_clone = 1;
                   16868:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16869:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16870:                     $can_clone = 1;
1.1221    raeburn  16871:                 }
                   16872:             }
                   16873:             unless ($can_clone) {
                   16874:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16875:                     push(@clonemsg,({
                   16876:                                       mt => 'No new community created.',
                   16877:                                       args => [],
                   16878:                                     },
                   16879:                                     {
                   16880:                                       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]).',
                   16881:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16882:                                     }));
1.942     raeburn  16883:                 } else {
1.1344    raeburn  16884:                     push(@clonemsg,({
                   16885:                                       mt => 'No new course created.',
                   16886:                                       args => [],
                   16887:                                     },
                   16888:                                     {
                   16889:                                       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]).',
                   16890:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16891:                                     }));
1.1221    raeburn  16892:                 }
1.566     albertel 16893: 	    }
1.578     raeburn  16894:         }
1.566     albertel 16895:     }
1.1344    raeburn  16896:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16897: }
                   16898: 
1.444     albertel 16899: sub construct_course {
1.1262    raeburn  16900:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16901:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16902:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16903:     my $linefeed =  '<br />'."\n";
                   16904:     if ($context eq 'auto') {
                   16905:         $linefeed = "\n";
                   16906:     }
1.566     albertel 16907: 
                   16908: #
                   16909: # Are we cloning?
                   16910: #
1.1344    raeburn  16911:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16912:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16913: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16914:         if (!$can_clone) {
1.1344    raeburn  16915: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16916: 	}
                   16917:     }
                   16918: 
1.444     albertel 16919: #
                   16920: # Open course
                   16921: #
1.1239    raeburn  16922:     my $showncrstype;
                   16923:     if ($args->{'crstype'} eq 'Placement') {
                   16924:         $showncrstype = 'placement test'; 
                   16925:     } else {  
                   16926:         $showncrstype = lc($args->{'crstype'});
                   16927:     }
1.444     albertel 16928:     my %cenv=();
                   16929:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16930:                                              $args->{'cdescr'},
                   16931:                                              $args->{'curl'},
                   16932:                                              $args->{'course_home'},
                   16933:                                              $args->{'nonstandard'},
                   16934:                                              $args->{'crscode'},
                   16935:                                              $args->{'ccuname'}.':'.
                   16936:                                              $args->{'ccdomain'},
1.882     raeburn  16937:                                              $args->{'crstype'},
1.1344    raeburn  16938:                                              $cnum,$context,$category,
                   16939:                                              $callercontext);
1.444     albertel 16940: 
                   16941:     # Note: The testing routines depend on this being output; see 
                   16942:     # Utils::Course. This needs to at least be output as a comment
                   16943:     # if anyone ever decides to not show this, and Utils::Course::new
                   16944:     # will need to be suitably modified.
1.1344    raeburn  16945:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16946:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16947:     } else {
                   16948:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16949:     }
1.943     raeburn  16950:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16951:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16952:     }
                   16953: 
1.444     albertel 16954: #
                   16955: # Check if created correctly
                   16956: #
1.479     albertel 16957:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16958:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16959:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16960:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16961:             $outcome .= &mt_user($user_lh,
                   16962:                             'Course creation failed, unrecognized course home server.');
                   16963:         } else {
                   16964:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16965:         }
                   16966:         $outcome .= $linefeed;
                   16967:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16968:     }
1.541     raeburn  16969:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16970: 
1.444     albertel 16971: #
1.566     albertel 16972: # Do the cloning
                   16973: #   
1.1344    raeburn  16974:     my @clonemsg;
1.566     albertel 16975:     if ($can_clone && $cloneid) {
1.1344    raeburn  16976:         push(@clonemsg,
                   16977:                       {
                   16978:                           mt => 'Created [_1] by cloning from [_2]',
                   16979:                           args => [$showncrstype,$clonetitle],
                   16980:                       });
1.566     albertel 16981: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16982: # Copy all files
1.1344    raeburn  16983:         my @info =
                   16984: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16985: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16986:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16987:                                                      $args->{'tinyurls'});
                   16988:         if (@info) {
                   16989:             push(@clonemsg,@info);
                   16990:         }
1.444     albertel 16991: # Restore URL
1.566     albertel 16992: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16993: # Restore title
1.566     albertel 16994: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16995: # Restore creation date, creator and creation context.
                   16996:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16997:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16998:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16999: # Mark as cloned
1.566     albertel 17000: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17001: # Need to clone grading mode
                   17002:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17003:         $cenv{'grading'}=$newenv{'grading'};
                   17004: # Do not clone these environment entries
                   17005:         &Apache::lonnet::del('environment',
                   17006:                   ['default_enrollment_start_date',
                   17007:                    'default_enrollment_end_date',
                   17008:                    'question.email',
                   17009:                    'policy.email',
                   17010:                    'comment.email',
                   17011:                    'pch.users.denied',
1.725     raeburn  17012:                    'plc.users.denied',
                   17013:                    'hidefromcat',
1.1121    raeburn  17014:                    'checkforpriv',
1.1355    raeburn  17015:                    'categories'],
1.638     www      17016:                    $$crsudom,$$crsunum);
1.1170    raeburn  17017:         if ($args->{'textbook'}) {
                   17018:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17019:         }
1.444     albertel 17020:     }
1.566     albertel 17021: 
1.444     albertel 17022: #
                   17023: # Set environment (will override cloned, if existing)
                   17024: #
                   17025:     my @sections = ();
                   17026:     my @xlists = ();
                   17027:     if ($args->{'crstype'}) {
                   17028:         $cenv{'type'}=$args->{'crstype'};
                   17029:     }
1.1371    raeburn  17030:     if ($args->{'lti'}) {
                   17031:         $cenv{'internal.lti'}=$args->{'lti'};
                   17032:     }
1.444     albertel 17033:     if ($args->{'crsid'}) {
                   17034:         $cenv{'courseid'}=$args->{'crsid'};
                   17035:     }
                   17036:     if ($args->{'crscode'}) {
                   17037:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17038:     }
                   17039:     if ($args->{'crsquota'} ne '') {
                   17040:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17041:     } else {
                   17042:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17043:     }
                   17044:     if ($args->{'ccuname'}) {
                   17045:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17046:                                         ':'.$args->{'ccdomain'};
                   17047:     } else {
                   17048:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17049:     }
1.1116    raeburn  17050:     if ($args->{'defaultcredits'}) {
                   17051:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17052:     }
1.444     albertel 17053:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   17054:     if ($args->{'crssections'}) {
                   17055:         $cenv{'internal.sectionnums'} = '';
                   17056:         if ($args->{'crssections'} =~ m/,/) {
                   17057:             @sections = split/,/,$args->{'crssections'};
                   17058:         } else {
                   17059:             $sections[0] = $args->{'crssections'};
                   17060:         }
                   17061:         if (@sections > 0) {
                   17062:             foreach my $item (@sections) {
                   17063:                 my ($sec,$gp) = split/:/,$item;
                   17064:                 my $class = $args->{'crscode'}.$sec;
                   17065:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17066:                 $cenv{'internal.sectionnums'} .= $item.',';
                   17067:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  17068:                     push(@badclasses,$class);
1.444     albertel 17069:                 }
                   17070:             }
                   17071:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17072:         }
                   17073:     }
                   17074: # do not hide course coordinator from staff listing, 
                   17075: # even if privileged
                   17076:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17077: # add course coordinator's domain to domains to check for privileged users
                   17078: # if different to course domain
                   17079:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17080:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17081:     }
1.444     albertel 17082: # add crosslistings
                   17083:     if ($args->{'crsxlist'}) {
                   17084:         $cenv{'internal.crosslistings'}='';
                   17085:         if ($args->{'crsxlist'} =~ m/,/) {
                   17086:             @xlists = split/,/,$args->{'crsxlist'};
                   17087:         } else {
                   17088:             $xlists[0] = $args->{'crsxlist'};
                   17089:         }
                   17090:         if (@xlists > 0) {
                   17091:             foreach my $item (@xlists) {
                   17092:                 my ($xl,$gp) = split/:/,$item;
                   17093:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17094:                 $cenv{'internal.crosslistings'} .= $item.',';
                   17095:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  17096:                     push(@badclasses,$xl);
1.444     albertel 17097:                 }
                   17098:             }
                   17099:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17100:         }
                   17101:     }
                   17102:     if ($args->{'autoadds'}) {
                   17103:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17104:     }
                   17105:     if ($args->{'autodrops'}) {
                   17106:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17107:     }
                   17108: # check for notification of enrollment changes
                   17109:     my @notified = ();
                   17110:     if ($args->{'notify_owner'}) {
                   17111:         if ($args->{'ccuname'} ne '') {
                   17112:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17113:         }
                   17114:     }
                   17115:     if ($args->{'notify_dc'}) {
                   17116:         if ($uname ne '') { 
1.630     raeburn  17117:             push(@notified,$uname.':'.$udom);
1.444     albertel 17118:         }
                   17119:     }
                   17120:     if (@notified > 0) {
                   17121:         my $notifylist;
                   17122:         if (@notified > 1) {
                   17123:             $notifylist = join(',',@notified);
                   17124:         } else {
                   17125:             $notifylist = $notified[0];
                   17126:         }
                   17127:         $cenv{'internal.notifylist'} = $notifylist;
                   17128:     }
                   17129:     if (@badclasses > 0) {
                   17130:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17131:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17132:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17133:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17134:         );
1.1264    raeburn  17135:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17136:                            &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  17137:         if ($context eq 'auto') {
                   17138:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17139:         } else {
1.566     albertel 17140:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17141:         }
                   17142:         foreach my $item (@badclasses) {
1.541     raeburn  17143:             if ($context eq 'auto') {
1.1261    raeburn  17144:                 $outcome .= " - $item\n";
1.541     raeburn  17145:             } else {
1.1261    raeburn  17146:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17147:             }
1.1261    raeburn  17148:         }
                   17149:         if ($context eq 'auto') {
                   17150:             $outcome .= $linefeed;
                   17151:         } else {
                   17152:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17153:         } 
1.444     albertel 17154:     }
                   17155:     if ($args->{'no_end_date'}) {
                   17156:         $args->{'endaccess'} = 0;
                   17157:     }
                   17158:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17159:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17160:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17161:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17162:     if ($args->{'showphotos'}) {
                   17163:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17164:     }
                   17165:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17166:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17167:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17168:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17169:             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'); 
                   17170:             if ($context eq 'auto') {
                   17171:                 $outcome .= $krb_msg;
                   17172:             } else {
1.566     albertel 17173:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17174:             }
                   17175:             $outcome .= $linefeed;
1.444     albertel 17176:         }
                   17177:     }
                   17178:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17179:        if ($args->{'setpolicy'}) {
                   17180:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17181:        }
                   17182:        if ($args->{'setcontent'}) {
                   17183:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17184:        }
1.1251    raeburn  17185:        if ($args->{'setcomment'}) {
                   17186:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17187:        }
1.444     albertel 17188:     }
                   17189:     if ($args->{'reshome'}) {
                   17190: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17191: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17192:     }
                   17193: #
                   17194: # course has keyed access
                   17195: #
                   17196:     if ($args->{'setkeys'}) {
                   17197:        $cenv{'keyaccess'}='yes';
                   17198:     }
                   17199: # if specified, key authority is not course, but user
                   17200: # only active if keyaccess is yes
                   17201:     if ($args->{'keyauth'}) {
1.487     albertel 17202: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17203: 	$user = &LONCAPA::clean_username($user);
                   17204: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17205: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17206: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17207: 	}
                   17208:     }
                   17209: 
1.1166    raeburn  17210: #
1.1167    raeburn  17211: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17212: #
                   17213:     if ($args->{'uniquecode'}) {
                   17214:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17215:         if ($code) {
                   17216:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17217:             my %crsinfo =
                   17218:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17219:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17220:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17221:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17222:             } 
1.1166    raeburn  17223:             if (ref($coderef)) {
                   17224:                 $$coderef = $code;
                   17225:             }
                   17226:         }
                   17227:     }
                   17228: 
1.444     albertel 17229:     if ($args->{'disresdis'}) {
                   17230:         $cenv{'pch.roles.denied'}='st';
                   17231:     }
                   17232:     if ($args->{'disablechat'}) {
                   17233:         $cenv{'plc.roles.denied'}='st';
                   17234:     }
                   17235: 
                   17236:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17237:     # course
                   17238:     $cenv{'course.helper.not.run'} = 1;
                   17239:     #
                   17240:     # Use new Randomseed
                   17241:     #
                   17242:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17243:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17244:     #
                   17245:     # The encryption code and receipt prefix for this course
                   17246:     #
                   17247:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17248:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17249:     #
                   17250:     # By default, use standard grading
                   17251:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17252: 
1.541     raeburn  17253:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17254:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17255: #
                   17256: # Open all assignments
                   17257: #
                   17258:     if ($args->{'openall'}) {
1.1341    raeburn  17259:        my $opendate = time;
                   17260:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17261:            $opendate = $args->{'openallfrom'};
                   17262:        }
1.444     albertel 17263:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17264:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17265:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17266:        $outcome .= &mt('All assignments open starting [_1]',
                   17267:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17268:                    &Apache::lonnet::cput
                   17269:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17270:    }
                   17271: #
                   17272: # Set first page
                   17273: #
                   17274:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17275: 	    || ($cloneid)) {
                   17276: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17277: 
                   17278: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17279:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17280: 
1.444     albertel 17281:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17282:         my $title; my $url;
                   17283:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17284: 	    $title=&mt('Syllabus');
1.444     albertel 17285:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17286:         } else {
1.963     raeburn  17287:             $title=&mt('Table of Contents');
1.444     albertel 17288:             $url='/adm/navmaps';
                   17289:         }
1.445     albertel 17290: 
                   17291:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17292: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17293: 
                   17294: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17295:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17296:     }
1.566     albertel 17297: 
1.1237    raeburn  17298: # 
                   17299: # Set params for Placement Tests
                   17300: #
1.1239    raeburn  17301:     if ($args->{'crstype'} eq 'Placement') {
                   17302:        my %storecontent; 
                   17303:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17304:        my %defaults = (
                   17305:                         buttonshide   => { value => 'yes',
                   17306:                                            type => 'string_yesno',},
                   17307:                         type          => { value => 'randomizetry',
                   17308:                                            type  => 'string_questiontype',},
                   17309:                         maxtries      => { value => 1,
                   17310:                                            type => 'int_pos',},
                   17311:                         problemstatus => { value => 'no',
                   17312:                                            type  => 'string_problemstatus',},
                   17313:                       );
                   17314:        foreach my $key (keys(%defaults)) {
                   17315:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17316:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17317:        }
1.1237    raeburn  17318:        &Apache::lonnet::cput
                   17319:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17320:     }
                   17321: 
1.1344    raeburn  17322:     return (1,$outcome,\@clonemsg);
1.444     albertel 17323: }
                   17324: 
1.1166    raeburn  17325: sub make_unique_code {
                   17326:     my ($cdom,$cnum) = @_;
                   17327:     # get lock on uniquecodes db
                   17328:     my $lockhash = {
                   17329:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17330:                                                   ':'.$env{'user.domain'},
                   17331:                    };
                   17332:     my $tries = 0;
                   17333:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17334:     my ($code,$error);
                   17335:   
                   17336:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17337:         $tries ++;
                   17338:         sleep 1;
                   17339:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17340:     }
                   17341:     if ($gotlock eq 'ok') {
                   17342:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17343:         my $gotcode;
                   17344:         my $attempts = 0;
                   17345:         while ((!$gotcode) && ($attempts < 100)) {
                   17346:             $code = &generate_code();
                   17347:             if (!exists($currcodes{$code})) {
                   17348:                 $gotcode = 1;
                   17349:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17350:                     $error = 'nostore';
                   17351:                 }
                   17352:             }
                   17353:             $attempts ++;
                   17354:         }
                   17355:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17356:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17357:     } else {
                   17358:         $error = 'nolock';
                   17359:     }
                   17360:     return ($code,$error);
                   17361: }
                   17362: 
                   17363: sub generate_code {
                   17364:     my $code;
                   17365:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17366:     for (my $i=0; $i<6; $i++) {
                   17367:         my $lettnum = int (rand 2);
                   17368:         my $item = '';
                   17369:         if ($lettnum) {
                   17370:             $item = $letts[int( rand(18) )];
                   17371:         } else {
                   17372:             $item = 1+int( rand(8) );
                   17373:         }
                   17374:         $code .= $item;
                   17375:     }
                   17376:     return $code;
                   17377: }
                   17378: 
1.444     albertel 17379: ############################################################
                   17380: ############################################################
                   17381: 
1.1237    raeburn  17382: # Community, Course and Placement Test
1.378     raeburn  17383: sub course_type {
                   17384:     my ($cid) = @_;
                   17385:     if (!defined($cid)) {
                   17386:         $cid = $env{'request.course.id'};
                   17387:     }
1.404     albertel 17388:     if (defined($env{'course.'.$cid.'.type'})) {
                   17389:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17390:     } else {
                   17391:         return 'Course';
1.377     raeburn  17392:     }
                   17393: }
1.156     albertel 17394: 
1.406     raeburn  17395: sub group_term {
                   17396:     my $crstype = &course_type();
                   17397:     my %names = (
                   17398:                   'Course' => 'group',
1.865     raeburn  17399:                   'Community' => 'group',
1.1237    raeburn  17400:                   'Placement' => 'group',
1.406     raeburn  17401:                 );
                   17402:     return $names{$crstype};
                   17403: }
                   17404: 
1.902     raeburn  17405: sub course_types {
1.1310    raeburn  17406:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17407:     my %typename = (
                   17408:                          official   => 'Official course',
                   17409:                          unofficial => 'Unofficial course',
                   17410:                          community  => 'Community',
1.1165    raeburn  17411:                          textbook   => 'Textbook course',
1.1237    raeburn  17412:                          placement  => 'Placement test',
1.1310    raeburn  17413:                          lti        => 'LTI provider',
1.902     raeburn  17414:                    );
                   17415:     return (\@types,\%typename);
                   17416: }
                   17417: 
1.156     albertel 17418: sub icon {
                   17419:     my ($file)=@_;
1.505     albertel 17420:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17421:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17422:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17423:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17424: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17425: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17426: 	            $curfext.".gif") {
                   17427: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17428: 		$curfext.".gif";
                   17429: 	}
                   17430:     }
1.249     albertel 17431:     return &lonhttpdurl($iconname);
1.154     albertel 17432: } 
1.84      albertel 17433: 
1.575     albertel 17434: sub lonhttpdurl {
1.692     www      17435: #
                   17436: # Had been used for "small fry" static images on separate port 8080.
                   17437: # Modify here if lightweight http functionality desired again.
                   17438: # Currently eliminated due to increasing firewall issues.
                   17439: #
1.575     albertel 17440:     my ($url)=@_;
1.692     www      17441:     return $url;
1.215     albertel 17442: }
                   17443: 
1.213     albertel 17444: sub connection_aborted {
                   17445:     my ($r)=@_;
                   17446:     $r->print(" ");$r->rflush();
                   17447:     my $c = $r->connection;
                   17448:     return $c->aborted();
                   17449: }
                   17450: 
1.221     foxr     17451: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17452: #    strings as 'strings'.
                   17453: sub escape_single {
1.221     foxr     17454:     my ($input) = @_;
1.223     albertel 17455:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17456:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17457:     return $input;
                   17458: }
1.223     albertel 17459: 
1.222     foxr     17460: #  Same as escape_single, but escape's "'s  This 
                   17461: #  can be used for  "strings"
                   17462: sub escape_double {
                   17463:     my ($input) = @_;
                   17464:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17465:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17466:     return $input;
                   17467: }
1.223     albertel 17468:  
1.222     foxr     17469: #   Escapes the last element of a full URL.
                   17470: sub escape_url {
                   17471:     my ($url)   = @_;
1.238     raeburn  17472:     my @urlslices = split(/\//, $url,-1);
1.369     www      17473:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17474:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17475: }
1.462     albertel 17476: 
1.820     raeburn  17477: sub compare_arrays {
                   17478:     my ($arrayref1,$arrayref2) = @_;
                   17479:     my (@difference,%count);
                   17480:     @difference = ();
                   17481:     %count = ();
                   17482:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17483:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17484:         foreach my $element (keys(%count)) {
                   17485:             if ($count{$element} == 1) {
                   17486:                 push(@difference,$element);
                   17487:             }
                   17488:         }
                   17489:     }
                   17490:     return @difference;
                   17491: }
                   17492: 
1.1322    raeburn  17493: sub lon_status_items {
                   17494:     my %defaults = (
                   17495:                      E         => 100,
                   17496:                      W         => 4,
                   17497:                      N         => 1,
1.1324    raeburn  17498:                      U         => 5,
1.1322    raeburn  17499:                      threshold => 200,
                   17500:                      sysmail   => 2500,
                   17501:                    );
                   17502:     my %names = (
                   17503:                    E => 'Errors',
                   17504:                    W => 'Warnings',
                   17505:                    N => 'Notices',
1.1324    raeburn  17506:                    U => 'Unsent',
1.1322    raeburn  17507:                 );
                   17508:     return (\%defaults,\%names);
                   17509: }
                   17510: 
1.817     bisitz   17511: # -------------------------------------------------------- Initialize user login
1.462     albertel 17512: sub init_user_environment {
1.463     albertel 17513:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17514:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17515: 
                   17516:     my $public=($username eq 'public' && $domain eq 'public');
                   17517: 
1.1062    raeburn  17518:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17519:     my $now=time;
                   17520: 
                   17521:     if ($public) {
                   17522: 	my $max_public=100;
                   17523: 	my $oldest;
                   17524: 	my $oldest_time=0;
                   17525: 	for(my $next=1;$next<=$max_public;$next++) {
                   17526: 	    if (-e $lonids."/publicuser_$next.id") {
                   17527: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17528: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17529: 		    $oldest_time=$mtime;
                   17530: 		    $oldest=$next;
                   17531: 		}
                   17532: 	    } else {
                   17533: 		$cookie="publicuser_$next";
                   17534: 		last;
                   17535: 	    }
                   17536: 	}
                   17537: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17538:     } else {
1.1275    raeburn  17539: 	# See if old ID present, if so, remove if this isn't a robot,
                   17540: 	# killing any existing non-robot sessions
1.463     albertel 17541: 	if (!$args->{'robot'}) {
                   17542: 	    opendir(DIR,$lonids);
                   17543: 	    while ($filename=readdir(DIR)) {
                   17544: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17545:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17546:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17547:                         my $linkedfile;
1.1320    raeburn  17548:                         if (exists($oldenv{'user.linkedenv'})) {
                   17549:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17550:                         }
1.1320    raeburn  17551:                         untie(%oldenv);
                   17552:                         if (unlink("$lonids/$filename")) {
                   17553:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17554:                                 if (-l "$lonids/$linkedfile.id") {
                   17555:                                     unlink("$lonids/$linkedfile.id");
                   17556:                                 }
1.1295    raeburn  17557:                             }
                   17558:                         }
                   17559:                     } else {
                   17560:                         unlink($lonids.'/'.$filename);
                   17561:                     }
1.463     albertel 17562: 		}
1.462     albertel 17563: 	    }
1.463     albertel 17564: 	    closedir(DIR);
1.1204    raeburn  17565: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17566:             my $namespace = 'nohist_courseeditor';
                   17567:             my $lockingkey = 'paste'."\0".'locked_num';
                   17568:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17569:                                                 $domain,$username);
                   17570:             if (exists($lockhash{$lockingkey})) {
                   17571:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17572:                 unless ($delresult eq 'ok') {
                   17573:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17574:                 }
                   17575:             }
1.462     albertel 17576: 	}
                   17577: # Give them a new cookie
1.463     albertel 17578: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17579: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17580: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17581:     
                   17582: # Initialize roles
                   17583: 
1.1062    raeburn  17584: 	($userroles,$firstaccenv,$timerintenv) = 
                   17585:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17586:     }
                   17587: # ------------------------------------ Check browser type and MathML capability
                   17588: 
1.1194    raeburn  17589:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17590:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17591: 
                   17592: # ------------------------------------------------------------- Get environment
                   17593: 
                   17594:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17595:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17596:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17597: 	undef(%userenv);
                   17598:     }
                   17599:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17600: 	$form->{'interface'}=$userenv{'interface'};
                   17601:     }
                   17602:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17603: 
                   17604: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17605:     foreach my $option ('interface','localpath','localres') {
                   17606:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17607:     }
                   17608: # --------------------------------------------------------- Write first profile
                   17609: 
                   17610:     {
1.1350    raeburn  17611:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17612: 	my %initial_env = 
                   17613: 	    ("user.name"          => $username,
                   17614: 	     "user.domain"        => $domain,
                   17615: 	     "user.home"          => $authhost,
                   17616: 	     "browser.type"       => $clientbrowser,
                   17617: 	     "browser.version"    => $clientversion,
                   17618: 	     "browser.mathml"     => $clientmathml,
                   17619: 	     "browser.unicode"    => $clientunicode,
                   17620: 	     "browser.os"         => $clientos,
1.1137    raeburn  17621:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17622:              "browser.info"       => $clientinfo,
1.1194    raeburn  17623:              "browser.osversion"  => $clientosversion,
1.462     albertel 17624: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17625: 	     "request.course.fn"  => '',
                   17626: 	     "request.course.uri" => '',
                   17627: 	     "request.course.sec" => '',
                   17628: 	     "request.role"       => 'cm',
                   17629: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17630: 	     "request.host"       => $ip,);
1.462     albertel 17631: 
                   17632:         if ($form->{'localpath'}) {
                   17633: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17634: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17635:         }
                   17636: 	
                   17637: 	if ($form->{'interface'}) {
                   17638: 	    $form->{'interface'}=~s/\W//gs;
                   17639: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17640: 	    $env{'browser.interface'}=$form->{'interface'};
                   17641: 	}
                   17642: 
1.1157    raeburn  17643:         if ($form->{'iptoken'}) {
                   17644:             my $lonhost = $r->dir_config('lonHostID');
                   17645:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17646:             $env{'user.noloadbalance'} = $lonhost;
                   17647:         }
                   17648: 
1.1268    raeburn  17649:         if ($form->{'noloadbalance'}) {
                   17650:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17651:             my $hosthere = $form->{'noloadbalance'};
                   17652:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17653:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17654:                 $env{'user.noloadbalance'} = $hosthere;
                   17655:             }
                   17656:         }
                   17657: 
1.1016    raeburn  17658:         unless ($domain eq 'public') {
1.1273    raeburn  17659:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17660:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17661: 
1.1387    raeburn  17662:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1273    raeburn  17663:                 $userenv{'availabletools.'.$tool} = 
                   17664:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17665:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17666:             }
1.980     raeburn  17667: 
1.1311    raeburn  17668:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17669:                 $userenv{'canrequest.'.$crstype} =
                   17670:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17671:                                                       'reload','requestcourses',
                   17672:                                                       \%userenv,\%domdef,\%is_adv);
                   17673:             }
1.724     raeburn  17674: 
1.1273    raeburn  17675:             $userenv{'canrequest.author'} =
                   17676:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17677:                                                   'reload','requestauthor',
1.980     raeburn  17678:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17679:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17680:                                                  $domain,$username);
                   17681:             my $reqstatus = $reqauthor{'author_status'};
                   17682:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17683:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17684:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17685:                                                       $reqauthor{'author'}{'timestamp'};
                   17686:                 }
1.1092    raeburn  17687:             }
1.1287    raeburn  17688:             my ($types,$typename) = &course_types();
                   17689:             if (ref($types) eq 'ARRAY') {
                   17690:                 my @options = ('approval','validate','autolimit');
                   17691:                 my $optregex = join('|',@options);
                   17692:                 my (%willtrust,%trustchecked);
                   17693:                 foreach my $type (@{$types}) {
                   17694:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17695:                     if ($dom_str ne '') {
                   17696:                         my $updatedstr = '';
                   17697:                         my @possdomains = split(',',$dom_str);
                   17698:                         foreach my $entry (@possdomains) {
                   17699:                             my ($extdom,$extopt) = split(':',$entry);
                   17700:                             unless ($trustchecked{$extdom}) {
                   17701:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17702:                                 $trustchecked{$extdom} = 1;
                   17703:                             }
                   17704:                             if ($willtrust{$extdom}) {
                   17705:                                 $updatedstr .= $entry.',';
                   17706:                             }
                   17707:                         }
                   17708:                         $updatedstr =~ s/,$//;
                   17709:                         if ($updatedstr) {
                   17710:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17711:                         } else {
                   17712:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17713:                         }
                   17714:                     }
                   17715:                 }
                   17716:             }
1.1092    raeburn  17717:         }
1.462     albertel 17718: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17719: 
1.462     albertel 17720: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17721: 		 &GDBM_WRCREAT(),0640)) {
                   17722: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17723: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17724: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17725:             if (ref($firstaccenv) eq 'HASH') {
                   17726:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17727:             }
                   17728:             if (ref($timerintenv) eq 'HASH') {
                   17729:                 &_add_to_env(\%disk_env,$timerintenv);
                   17730:             }
1.463     albertel 17731: 	    if (ref($args->{'extra_env'})) {
                   17732: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17733: 	    }
1.462     albertel 17734: 	    untie(%disk_env);
                   17735: 	} else {
1.705     tempelho 17736: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17737: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17738: 	    return 'error: '.$!;
                   17739: 	}
                   17740:     }
                   17741:     $env{'request.role'}='cm';
                   17742:     $env{'request.role.adv'}=$env{'user.adv'};
                   17743:     $env{'browser.type'}=$clientbrowser;
                   17744: 
                   17745:     return $cookie;
                   17746: 
                   17747: }
                   17748: 
                   17749: sub _add_to_env {
                   17750:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17751:     if (ref($env_data) eq 'HASH') {
                   17752:         while (my ($key,$value) = each(%$env_data)) {
                   17753: 	    $idf->{$prefix.$key} = $value;
                   17754: 	    $env{$prefix.$key}   = $value;
                   17755:         }
1.462     albertel 17756:     }
                   17757: }
                   17758: 
1.685     tempelho 17759: # --- Get the symbolic name of a problem and the url
                   17760: sub get_symb {
                   17761:     my ($request,$silent) = @_;
1.726     raeburn  17762:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17763:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17764:     if ($symb eq '') {
                   17765:         if (!$silent) {
1.1071    raeburn  17766:             if (ref($request)) { 
                   17767:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17768:             }
1.685     tempelho 17769:             return ();
                   17770:         }
                   17771:     }
                   17772:     &Apache::lonenc::check_decrypt(\$symb);
                   17773:     return ($symb);
                   17774: }
                   17775: 
                   17776: # --------------------------------------------------------------Get annotation
                   17777: 
                   17778: sub get_annotation {
                   17779:     my ($symb,$enc) = @_;
                   17780: 
                   17781:     my $key = $symb;
                   17782:     if (!$enc) {
                   17783:         $key =
                   17784:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17785:     }
                   17786:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17787:     return $annotation{$key};
                   17788: }
                   17789: 
                   17790: sub clean_symb {
1.731     raeburn  17791:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17792: 
                   17793:     &Apache::lonenc::check_decrypt(\$symb);
                   17794:     my $enc = $env{'request.enc'};
1.731     raeburn  17795:     if ($delete_enc) {
1.730     raeburn  17796:         delete($env{'request.enc'});
                   17797:     }
1.685     tempelho 17798: 
                   17799:     return ($symb,$enc);
                   17800: }
1.462     albertel 17801: 
1.1181    raeburn  17802: ############################################################
                   17803: ############################################################
                   17804: 
                   17805: =pod
                   17806: 
                   17807: =head1 Routines for building display used to search for courses
                   17808: 
                   17809: 
                   17810: =over 4
                   17811: 
                   17812: =item * &build_filters()
                   17813: 
                   17814: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17815: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17816: and quotacheck.pl
                   17817: 
1.1181    raeburn  17818: 
                   17819: Inputs:
                   17820: 
                   17821: filterlist - anonymous array of fields to include as potential filters 
                   17822: 
                   17823: crstype - course type
                   17824: 
                   17825: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17826:               to pop-open a course selector (will contain "extra element"). 
                   17827: 
                   17828: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17829: 
                   17830: filter - anonymous hash of criteria and their values
                   17831: 
                   17832: action - form action
                   17833: 
                   17834: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17835: 
1.1182    raeburn  17836: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17837: 
                   17838: cloneruname - username of owner of new course who wants to clone
                   17839: 
                   17840: clonerudom - domain of owner of new course who wants to clone
                   17841: 
                   17842: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17843: 
                   17844: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17845: 
                   17846: codedom - domain
                   17847: 
                   17848: formname - value of form element named "form". 
                   17849: 
                   17850: fixeddom - domain, if fixed.
                   17851: 
                   17852: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17853: 
                   17854: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17855: 
                   17856: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17857: 
                   17858: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17859: 
                   17860: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17861: 
                   17862: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17863: 
                   17864: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17865: 
1.1182    raeburn  17866: 
1.1181    raeburn  17867: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17868: 
1.1182    raeburn  17869: 
1.1181    raeburn  17870: Side Effects: None
                   17871: 
                   17872: =cut
                   17873: 
                   17874: # ---------------------------------------------- search for courses based on last activity etc.
                   17875: 
                   17876: sub build_filters {
                   17877:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17878:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17879:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17880:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17881:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17882:     my ($list,$jscript);
1.1181    raeburn  17883:     my $onchange = 'javascript:updateFilters(this)';
                   17884:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17885:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17886:         $typeselectform,$instcodetitle);
                   17887:     if ($formname eq '') {
                   17888:         $formname = $caller;
                   17889:     }
                   17890:     foreach my $item (@{$filterlist}) {
                   17891:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17892:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17893:             if ($item eq 'domainfilter') {
                   17894:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17895:             } elsif ($item eq 'coursefilter') {
                   17896:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17897:             } elsif ($item eq 'ownerfilter') {
                   17898:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17899:             } elsif ($item eq 'ownerdomfilter') {
                   17900:                 $filter->{'ownerdomfilter'} =
                   17901:                     &LONCAPA::clean_domain($filter->{$item});
                   17902:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17903:                                                        'ownerdomfilter',1);
                   17904:             } elsif ($item eq 'personfilter') {
                   17905:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17906:             } elsif ($item eq 'persondomfilter') {
                   17907:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17908:                                                         'persondomfilter',1);
                   17909:             } else {
                   17910:                 $filter->{$item} =~ s/\W//g;
                   17911:             }
                   17912:             if (!$filter->{$item}) {
                   17913:                 $filter->{$item} = '';
                   17914:             }
                   17915:         }
                   17916:         if ($item eq 'domainfilter') {
                   17917:             my $allow_blank = 1;
                   17918:             if ($formname eq 'portform') {
                   17919:                 $allow_blank=0;
                   17920:             } elsif ($formname eq 'studentform') {
                   17921:                 $allow_blank=0;
                   17922:             }
                   17923:             if ($fixeddom) {
                   17924:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17925:                                     ' value="'.$codedom.'" />'.
                   17926:                                     &Apache::lonnet::domain($codedom,'description');
                   17927:             } else {
                   17928:                 $domainselectform = &select_dom_form($filter->{$item},
                   17929:                                                      'domainfilter',
                   17930:                                                       $allow_blank,'',$onchange);
                   17931:             }
                   17932:         } else {
                   17933:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17934:         }
                   17935:     }
                   17936: 
                   17937:     # last course activity filter and selection
                   17938:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17939: 
                   17940:     # course created filter and selection
                   17941:     if (exists($filter->{'createdfilter'})) {
                   17942:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17943:     }
                   17944: 
1.1239    raeburn  17945:     my $prefix = $crstype;
                   17946:     if ($crstype eq 'Placement') {
                   17947:         $prefix = 'Placement Test'
                   17948:     }
1.1181    raeburn  17949:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17950:                 'cac' => "$prefix Activity",
                   17951:                 'ccr' => "$prefix Created",
                   17952:                 'cde' => "$prefix Title",
                   17953:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17954:                 'ins' => 'Institutional Code',
                   17955:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17956:                 'cow' => "$prefix Owner/Co-owner",
                   17957:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17958:                 'cog' => 'Type',
                   17959:              );
                   17960: 
                   17961:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17962:         my $typeval = 'Course';
                   17963:         if ($crstype eq 'Community') {
                   17964:             $typeval = 'Community';
1.1239    raeburn  17965:         } elsif ($crstype eq 'Placement') {
                   17966:             $typeval = 'Placement';
1.1181    raeburn  17967:         }
                   17968:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17969:     } else {
                   17970:         $typeselectform =  '<select name="type" size="1"';
                   17971:         if ($onchange) {
                   17972:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17973:         }
                   17974:         $typeselectform .= '>'."\n";
1.1237    raeburn  17975:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17976:             my $shown;
                   17977:             if ($posstype eq 'Placement') {
                   17978:                 $shown = &mt('Placement Test');
                   17979:             } else {
                   17980:                 $shown = &mt($posstype);
                   17981:             }
1.1181    raeburn  17982:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17983:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17984:         }
                   17985:         $typeselectform.="</select>";
                   17986:     }
                   17987: 
                   17988:     my ($cloneableonlyform,$cloneabletitle);
                   17989:     if (exists($filter->{'cloneableonly'})) {
                   17990:         my $cloneableon = '';
                   17991:         my $cloneableoff = ' checked="checked"';
                   17992:         if ($filter->{'cloneableonly'}) {
                   17993:             $cloneableon = $cloneableoff;
                   17994:             $cloneableoff = '';
                   17995:         }
                   17996:         $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>';
                   17997:         if ($formname eq 'ccrs') {
1.1187    bisitz   17998:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17999:         } else {
                   18000:             $cloneabletitle = &mt('Cloneable by you');
                   18001:         }
                   18002:     }
                   18003:     my $officialjs;
                   18004:     if ($crstype eq 'Course') {
                   18005:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18006: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18007: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18008:             if ($codedom) { 
1.1181    raeburn  18009:                 $officialjs = 1;
                   18010:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18011:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18012:                                                                   $officialjs,$codetitlesref);
                   18013:                 if ($jscript) {
1.1182    raeburn  18014:                     $jscript = '<script type="text/javascript">'."\n".
                   18015:                                '// <![CDATA['."\n".
                   18016:                                $jscript."\n".
                   18017:                                '// ]]>'."\n".
                   18018:                                '</script>'."\n";
1.1181    raeburn  18019:                 }
                   18020:             }
                   18021:             if ($instcodeform eq '') {
                   18022:                 $instcodeform =
                   18023:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18024:                     $list->{'instcodefilter'}.'" />';
                   18025:                 $instcodetitle = $lt{'ins'};
                   18026:             } else {
                   18027:                 $instcodetitle = $lt{'inc'};
                   18028:             }
                   18029:             if ($fixeddom) {
                   18030:                 $instcodetitle .= '<br />('.$codedom.')';
                   18031:             }
                   18032:         }
                   18033:     }
                   18034:     my $output = qq|
                   18035: <form method="post" name="filterpicker" action="$action">
                   18036: <input type="hidden" name="form" value="$formname" />
                   18037: |;
                   18038:     if ($formname eq 'modifycourse') {
                   18039:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18040:                    '<input type="hidden" name="prevphase" value="'.
                   18041:                    $prevphase.'" />'."\n";
1.1198    musolffc 18042:     } elsif ($formname eq 'quotacheck') {
                   18043:         $output .= qq|
                   18044: <input type="hidden" name="sortby" value="" />
                   18045: <input type="hidden" name="sortorder" value="" />
                   18046: |;
                   18047:     } else {
1.1181    raeburn  18048:         my $name_input;
                   18049:         if ($cnameelement ne '') {
                   18050:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18051:                           $cnameelement.'" />';
                   18052:         }
                   18053:         $output .= qq|
1.1182    raeburn  18054: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18055: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18056: $name_input
                   18057: $roleelement
                   18058: $multelement
                   18059: $typeelement
                   18060: |;
                   18061:         if ($formname eq 'portform') {
                   18062:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18063:         }
                   18064:     }
                   18065:     if ($fixeddom) {
                   18066:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18067:     }
                   18068:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18069:     if ($sincefilterform) {
                   18070:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18071:                   .$sincefilterform
                   18072:                   .&Apache::lonhtmlcommon::row_closure();
                   18073:     }
                   18074:     if ($createdfilterform) {
                   18075:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18076:                   .$createdfilterform
                   18077:                   .&Apache::lonhtmlcommon::row_closure();
                   18078:     }
                   18079:     if ($domainselectform) {
                   18080:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18081:                   .$domainselectform
                   18082:                   .&Apache::lonhtmlcommon::row_closure();
                   18083:     }
                   18084:     if ($typeselectform) {
                   18085:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18086:             $output .= $typeselectform;
                   18087:         } else {
                   18088:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18089:                       .$typeselectform
                   18090:                       .&Apache::lonhtmlcommon::row_closure();
                   18091:         }
                   18092:     }
                   18093:     if ($instcodeform) {
                   18094:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18095:                   .$instcodeform
                   18096:                   .&Apache::lonhtmlcommon::row_closure();
                   18097:     }
                   18098:     if (exists($filter->{'ownerfilter'})) {
                   18099:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18100:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18101:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18102:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18103:                    $ownerdomselectform.'</td></tr></table>'.
                   18104:                    &Apache::lonhtmlcommon::row_closure();
                   18105:     }
                   18106:     if (exists($filter->{'personfilter'})) {
                   18107:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18108:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18109:                    '<input type="text" name="personfilter" size="20" value="'.
                   18110:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18111:                    $persondomselectform.'</td></tr></table>'.
                   18112:                    &Apache::lonhtmlcommon::row_closure();
                   18113:     }
                   18114:     if (exists($filter->{'coursefilter'})) {
                   18115:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18116:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18117:                   .$list->{'coursefilter'}.'" />'
                   18118:                   .&Apache::lonhtmlcommon::row_closure();
                   18119:     }
                   18120:     if ($cloneableonlyform) {
                   18121:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18122:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18123:     }
                   18124:     if (exists($filter->{'descriptfilter'})) {
                   18125:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18126:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18127:                   .$list->{'descriptfilter'}.'" />'
                   18128:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18129:     }
                   18130:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18131:                '<input type="hidden" name="updater" value="" />'."\n".
                   18132:                '<input type="submit" name="gosearch" value="'.
                   18133:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18134:     return $jscript.$clonewarning.$output;
                   18135: }
                   18136: 
                   18137: =pod 
                   18138: 
                   18139: =item * &timebased_select_form()
                   18140: 
1.1182    raeburn  18141: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18142: filter e.g., Course Activity, Course Created, when searching for courses
                   18143: or communities
                   18144: 
                   18145: Inputs:
                   18146: 
                   18147: item - name of form element (sincefilter or createdfilter)
                   18148: 
                   18149: filter - anonymous hash of criteria and their values
                   18150: 
                   18151: Returns: HTML for a select box contained a blank, then six time selections,
                   18152:          with value set in incoming form variables currently selected. 
                   18153: 
                   18154: Side Effects: None
                   18155: 
                   18156: =cut
                   18157: 
                   18158: sub timebased_select_form {
                   18159:     my ($item,$filter) = @_;
                   18160:     if (ref($filter) eq 'HASH') {
                   18161:         $filter->{$item} =~ s/[^\d-]//g;
                   18162:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18163:         return &select_form(
                   18164:                             $filter->{$item},
                   18165:                             $item,
                   18166:                             {      '-1' => '',
                   18167:                                 '86400' => &mt('today'),
                   18168:                                '604800' => &mt('last week'),
                   18169:                               '2592000' => &mt('last month'),
                   18170:                               '7776000' => &mt('last three months'),
                   18171:                              '15552000' => &mt('last six months'),
                   18172:                              '31104000' => &mt('last year'),
                   18173:                     'select_form_order' =>
                   18174:                            ['-1','86400','604800','2592000','7776000',
                   18175:                             '15552000','31104000']});
                   18176:     }
                   18177: }
                   18178: 
                   18179: =pod
                   18180: 
                   18181: =item * &js_changer()
                   18182: 
                   18183: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18184: when course type or domain is changed, and also to hide 'Searching ...' on
                   18185: page load completion for page showing search result.
1.1181    raeburn  18186: 
                   18187: Inputs: None
                   18188: 
1.1183    raeburn  18189: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18190: 
                   18191: Side Effects: None
                   18192: 
                   18193: =cut
                   18194: 
                   18195: sub js_changer {
                   18196:     return <<ENDJS;
                   18197: <script type="text/javascript">
                   18198: // <![CDATA[
                   18199: function updateFilters(caller) {
                   18200:     if (typeof(caller) != "undefined") {
                   18201:         document.filterpicker.updater.value = caller.name;
                   18202:     }
                   18203:     document.filterpicker.submit();
                   18204: }
1.1183    raeburn  18205: 
                   18206: function hideSearching() {
                   18207:     if (document.getElementById('searching')) {
                   18208:         document.getElementById('searching').style.display = 'none';
                   18209:     }
                   18210:     return;
                   18211: }
                   18212: 
1.1181    raeburn  18213: // ]]>
                   18214: </script>
                   18215: 
                   18216: ENDJS
                   18217: }
                   18218: 
                   18219: =pod
                   18220: 
1.1182    raeburn  18221: =item * &search_courses()
                   18222: 
                   18223: Process selected filters form course search form and pass to lonnet::courseiddump
                   18224: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18225: 
                   18226: Inputs:
                   18227: 
                   18228: dom - domain being searched 
                   18229: 
                   18230: type - course type ('Course' or 'Community' or '.' if any).
                   18231: 
                   18232: filter - anonymous hash of criteria and their values
                   18233: 
                   18234: numtitles - for institutional codes - number of categories
                   18235: 
                   18236: cloneruname - optional username of new course owner
                   18237: 
                   18238: clonerudom - optional domain of new course owner
                   18239: 
1.1221    raeburn  18240: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18241:             (used when DC is using course creation form)
                   18242: 
                   18243: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18244: 
1.1221    raeburn  18245: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18246:            (and so can clone automatically)
                   18247: 
                   18248: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18249: 
                   18250: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18251:               courses to clone 
1.1182    raeburn  18252: 
                   18253: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18254: 
                   18255: 
                   18256: Side Effects: None
                   18257: 
                   18258: =cut
                   18259: 
                   18260: 
                   18261: sub search_courses {
1.1221    raeburn  18262:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18263:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18264:     my (%courses,%showcourses,$cloner);
                   18265:     if (($filter->{'ownerfilter'} ne '') ||
                   18266:         ($filter->{'ownerdomfilter'} ne '')) {
                   18267:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18268:                                        $filter->{'ownerdomfilter'};
                   18269:     }
                   18270:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18271:         if (!$filter->{$item}) {
                   18272:             $filter->{$item}='.';
                   18273:         }
                   18274:     }
                   18275:     my $now = time;
                   18276:     my $timefilter =
                   18277:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18278:     my ($createdbefore,$createdafter);
                   18279:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18280:         $createdbefore = $now;
                   18281:         $createdafter = $now-$filter->{'createdfilter'};
                   18282:     }
                   18283:     my ($instcodefilter,$regexpok);
                   18284:     if ($numtitles) {
                   18285:         if ($env{'form.official'} eq 'on') {
                   18286:             $instcodefilter =
                   18287:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18288:             $regexpok = 1;
                   18289:         } elsif ($env{'form.official'} eq 'off') {
                   18290:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18291:             unless ($instcodefilter eq '') {
                   18292:                 $regexpok = -1;
                   18293:             }
                   18294:         }
                   18295:     } else {
                   18296:         $instcodefilter = $filter->{'instcodefilter'};
                   18297:     }
                   18298:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18299:     if ($type eq '') { $type = '.'; }
                   18300: 
                   18301:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18302:         $cloner = $cloneruname.':'.$clonerudom;
                   18303:     }
                   18304:     %courses = &Apache::lonnet::courseiddump($dom,
                   18305:                                              $filter->{'descriptfilter'},
                   18306:                                              $timefilter,
                   18307:                                              $instcodefilter,
                   18308:                                              $filter->{'combownerfilter'},
                   18309:                                              $filter->{'coursefilter'},
                   18310:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18311:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18312:                                              $filter->{'cloneableonly'},
                   18313:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18314:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18315:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18316:         my $ccrole;
                   18317:         if ($type eq 'Community') {
                   18318:             $ccrole = 'co';
                   18319:         } else {
                   18320:             $ccrole = 'cc';
                   18321:         }
                   18322:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18323:                                                      $filter->{'persondomfilter'},
                   18324:                                                      'userroles',undef,
                   18325:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18326:                                                      $dom);
                   18327:         foreach my $role (keys(%rolehash)) {
                   18328:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18329:             my $cid = $cdom.'_'.$cnum;
                   18330:             if (exists($courses{$cid})) {
                   18331:                 if (ref($courses{$cid}) eq 'HASH') {
                   18332:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18333:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18334:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18335:                         }
                   18336:                     } else {
                   18337:                         $courses{$cid}{roles} = [$courserole];
                   18338:                     }
                   18339:                     $showcourses{$cid} = $courses{$cid};
                   18340:                 }
                   18341:             }
                   18342:         }
                   18343:         %courses = %showcourses;
                   18344:     }
                   18345:     return %courses;
                   18346: }
                   18347: 
                   18348: =pod
                   18349: 
1.1181    raeburn  18350: =back
                   18351: 
1.1207    raeburn  18352: =head1 Routines for version requirements for current course.
                   18353: 
                   18354: =over 4
                   18355: 
                   18356: =item * &check_release_required()
                   18357: 
                   18358: Compares required LON-CAPA version with version on server, and
                   18359: if required version is newer looks for a server with the required version.
                   18360: 
                   18361: Looks first at servers in user's owen domain; if none suitable, looks at
                   18362: servers in course's domain are permitted to host sessions for user's domain.
                   18363: 
                   18364: Inputs:
                   18365: 
                   18366: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18367: 
                   18368: $courseid - Course ID of current course
                   18369: 
                   18370: $rolecode - User's current role in course (for switchserver query string).
                   18371: 
                   18372: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18373: 
                   18374: 
                   18375: Returns:
                   18376: 
                   18377: $switchserver - query string tp append to /adm/switchserver call (if 
                   18378:                 current server's LON-CAPA version is too old. 
                   18379: 
                   18380: $warning - Message is displayed if no suitable server could be found.
                   18381: 
                   18382: =cut
                   18383: 
                   18384: sub check_release_required {
                   18385:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18386:     my ($switchserver,$warning);
                   18387:     if ($required ne '') {
                   18388:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18389:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18390:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18391:             my $otherserver;
                   18392:             if (($major eq '' && $minor eq '') ||
                   18393:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18394:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18395:                 my $switchlcrev =
                   18396:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18397:                                                            $userdomserver);
                   18398:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18399:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18400:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18401:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18402:                     if ($cdom ne $env{'user.domain'}) {
                   18403:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18404:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18405:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18406:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18407:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18408:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18409:                         my $canhost =
                   18410:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18411:                                                               $coursedomserver,
                   18412:                                                               $remoterev,
                   18413:                                                               $udomdefaults{'remotesessions'},
                   18414:                                                               $defdomdefaults{'hostedsessions'});
                   18415: 
                   18416:                         if ($canhost) {
                   18417:                             $otherserver = $coursedomserver;
                   18418:                         } else {
                   18419:                             $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.");
                   18420:                         }
                   18421:                     } else {
                   18422:                         $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).");
                   18423:                     }
                   18424:                 } else {
                   18425:                     $otherserver = $userdomserver;
                   18426:                 }
                   18427:             }
                   18428:             if ($otherserver ne '') {
                   18429:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18430:             }
                   18431:         }
                   18432:     }
                   18433:     return ($switchserver,$warning);
                   18434: }
                   18435: 
                   18436: =pod
                   18437: 
                   18438: =item * &check_release_result()
                   18439: 
                   18440: Inputs:
                   18441: 
                   18442: $switchwarning - Warning message if no suitable server found to host session.
                   18443: 
                   18444: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18445:                 and current role.
                   18446: 
                   18447: Returns: HTML to display with information about requirement to switch server.
                   18448:          Either displaying warning with link to Roles/Courses screen or
                   18449:          display link to switchserver.
                   18450: 
1.1181    raeburn  18451: =cut
                   18452: 
1.1207    raeburn  18453: sub check_release_result {
                   18454:     my ($switchwarning,$switchserver) = @_;
                   18455:     my $output = &start_page('Selected course unavailable on this server').
                   18456:                  '<p class="LC_warning">';
                   18457:     if ($switchwarning) {
                   18458:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18459:         if (&show_course()) {
                   18460:             $output .= &mt('Display courses');
                   18461:         } else {
                   18462:             $output .= &mt('Display roles');
                   18463:         }
                   18464:         $output .= '</a>';
                   18465:     } elsif ($switchserver) {
                   18466:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18467:                    '<br />'.
                   18468:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18469:                    &mt('Switch Server').
                   18470:                    '</a>';
                   18471:     }
                   18472:     $output .= '</p>'.&end_page();
                   18473:     return $output;
                   18474: }
                   18475: 
                   18476: =pod
                   18477: 
                   18478: =item * &needs_coursereinit()
                   18479: 
                   18480: Determine if course contents stored for user's session needs to be
                   18481: refreshed, because content has changed since "Big Hash" last tied.
                   18482: 
                   18483: Check for change is made if time last checked is more than 10 minutes ago
                   18484: (by default).
                   18485: 
                   18486: Inputs:
                   18487: 
                   18488: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18489: 
                   18490: $interval (optional) - Time which may elapse (in s) between last check for content
                   18491:                        change in current course. (default: 600 s).  
                   18492: 
                   18493: Returns: an array; first element is:
                   18494: 
                   18495: =over 4
                   18496: 
                   18497: 'switch' - if content updates mean user's session
                   18498:            needs to be switched to a server running a newer LON-CAPA version
                   18499:  
                   18500: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18501:            on current server hosting user's session                
                   18502: 
                   18503: ''       - if no action required.
                   18504: 
                   18505: =back
                   18506: 
                   18507: If first item element is 'switch':
                   18508: 
                   18509: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18510: 
                   18511: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18512:                               and current role. 
                   18513: 
                   18514: otherwise: no other elements returned.
                   18515: 
                   18516: =back
                   18517: 
                   18518: =cut
                   18519: 
                   18520: sub needs_coursereinit {
                   18521:     my ($loncaparev,$interval) = @_;
                   18522:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18523:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18524:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18525:     my $now = time;
                   18526:     if ($interval eq '') {
                   18527:         $interval = 600;
                   18528:     }
                   18529:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18530:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18531:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18532:         if ($blocked) {
                   18533:             return ();
                   18534:         }
1.1391    raeburn  18535:         my $update;
                   18536:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18537:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18538:         if ($lastmainchange > $env{'request.course.tied'}) {
                   18539:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18540:             if ($needswitch) {
                   18541:                 return ('switch',$switchwarning,$switchserver);
                   18542:             }
                   18543:             $update = 'main';
                   18544:         }
                   18545:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18546:             if ($update) {
                   18547:                 $update = 'both';
                   18548:             } else {
                   18549:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18550:                 if ($needswitch) {
                   18551:                     return ('switch',$switchwarning,$switchserver);
                   18552:                 } else {
                   18553:                     $update = 'supp';
1.1207    raeburn  18554:                 }
                   18555:             }
1.1391    raeburn  18556:             return ($update);
                   18557:         }
                   18558:     }
                   18559:     return ();
                   18560: }
                   18561: 
                   18562: sub switch_for_update {
                   18563:     my ($loncaparev,$cdom,$cnum) = @_;
                   18564:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18565:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18566:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18567:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18568:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18569:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18570:             my ($switchserver,$switchwarning) =
                   18571:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18572:                                         $curr_reqd_hash{'internal.releaserequired'});
                   18573:             if ($switchwarning ne '' || $switchserver ne '') {
                   18574:                 return ('switch',$switchwarning,$switchserver);
                   18575:             }
1.1207    raeburn  18576:         }
                   18577:     }
                   18578:     return ();
                   18579: }
1.1181    raeburn  18580: 
1.1083    raeburn  18581: sub update_content_constraints {
1.1395    raeburn  18582:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  18583:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18584:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18585:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18586:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18587:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18588:         if ($item eq 'resourcetag') {
                   18589:             if ($name eq 'responsetype') {
                   18590:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18591:             }
1.1307    raeburn  18592:         } elsif ($item eq 'course') {
                   18593:             if ($name eq 'courserestype') {
                   18594:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18595:             }
1.1083    raeburn  18596:         }
                   18597:     }
                   18598:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18599:     if (defined($navmap)) {
1.1307    raeburn  18600:         my (%allresponses,%allcrsrestypes);
                   18601:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18602:             if ($res->is_tool()) {
                   18603:                 if ($allcrsrestypes{'exttool'}) {
                   18604:                     $allcrsrestypes{'exttool'} ++;
                   18605:                 } else {
                   18606:                     $allcrsrestypes{'exttool'} = 1;
                   18607:                 }
                   18608:                 next;
                   18609:             }
1.1083    raeburn  18610:             my %responses = $res->responseTypes();
                   18611:             foreach my $key (keys(%responses)) {
                   18612:                 next unless(exists($checkresponsetypes{$key}));
                   18613:                 $allresponses{$key} += $responses{$key};
                   18614:             }
                   18615:         }
                   18616:         foreach my $key (keys(%allresponses)) {
                   18617:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18618:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18619:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18620:             }
                   18621:         }
1.1307    raeburn  18622:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18623:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18624:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18625:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18626:             }
                   18627:         }
1.1083    raeburn  18628:         undef($navmap);
                   18629:     }
1.1391    raeburn  18630:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  18631:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18632:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18633:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18634:         }
                   18635:     }
1.1083    raeburn  18636:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18637:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18638:     }
                   18639:     return;
                   18640: }
                   18641: 
1.1110    raeburn  18642: sub allmaps_incourse {
                   18643:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18644:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18645:         $cid = $env{'request.course.id'};
                   18646:         $cdom = $env{'course.'.$cid.'.domain'};
                   18647:         $cnum = $env{'course.'.$cid.'.num'};
                   18648:         $chome = $env{'course.'.$cid.'.home'};
                   18649:     }
                   18650:     my %allmaps = ();
                   18651:     my $lastchange =
                   18652:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18653:     if ($lastchange > $env{'request.course.tied'}) {
                   18654:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18655:         unless ($ferr) {
1.1395    raeburn  18656:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  18657:         }
                   18658:     }
                   18659:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18660:     if (defined($navmap)) {
                   18661:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18662:             $allmaps{$res->src()} = 1;
                   18663:         }
                   18664:     }
                   18665:     return \%allmaps;
                   18666: }
                   18667: 
1.1083    raeburn  18668: sub parse_supplemental_title {
                   18669:     my ($title) = @_;
                   18670: 
                   18671:     my ($foldertitle,$renametitle);
                   18672:     if ($title =~ /&amp;&amp;&amp;/) {
                   18673:         $title = &HTML::Entites::decode($title);
                   18674:     }
                   18675:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18676:         $renametitle=$4;
                   18677:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18678:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18679:         my $name =  &plainname($uname,$udom);
                   18680:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18681:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  18682:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  18683:         if ($foldertitle ne '') {
1.1401    raeburn  18684:             $title .= ': <br />'.$foldertitle;
                   18685:         }
1.1083    raeburn  18686:     }
                   18687:     if (wantarray) {
                   18688:         return ($title,$foldertitle,$renametitle);
                   18689:     }
                   18690:     return $title;
                   18691: }
                   18692: 
1.1395    raeburn  18693: sub get_supplemental {
                   18694:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   18695:     my $hashid=$cnum.':'.$cdom;
                   18696:     my ($supplemental,$cached,$set_httprefs);
                   18697:     unless ($ignorecache) {
                   18698:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   18699:     }
                   18700:     unless (defined($cached)) {
                   18701:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   18702:         unless ($chome eq 'no_host') {
                   18703:             my @order = @LONCAPA::map::order;
                   18704:             my @resources = @LONCAPA::map::resources;
                   18705:             my @resparms = @LONCAPA::map::resparms;
                   18706:             my @zombies = @LONCAPA::map::zombies;
                   18707:             my ($errors,%ids,%hidden);
                   18708:             $errors =
                   18709:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   18710:                                       $errors,$possdel,\%ids,\%hidden);
                   18711:             @LONCAPA::map::order = @order;
                   18712:             @LONCAPA::map::resources = @resources;
                   18713:             @LONCAPA::map::resparms = @resparms;
                   18714:             @LONCAPA::map::zombies = @zombies;
                   18715:             $set_httprefs = 1;
                   18716:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18717:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18718:             }
                   18719:             $supplemental = {
                   18720:                                ids => \%ids,
                   18721:                                hidden => \%hidden,
                   18722:                             };
                   18723:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   18724:         }
                   18725:     }
                   18726:     return ($supplemental,$set_httprefs);
                   18727: }
                   18728: 
1.1143    raeburn  18729: sub recurse_supplemental {
1.1391    raeburn  18730:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   18731:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   18732:         my $mapnum;
                   18733:         if ($suppmap eq 'supplemental.sequence') {
                   18734:             $mapnum = 0;
                   18735:         } else {
                   18736:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   18737:         }
1.1143    raeburn  18738:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18739:         if ($fatal) {
                   18740:             $errors ++;
                   18741:         } else {
1.1389    raeburn  18742:             my @order = @LONCAPA::map::order;
                   18743:             if (@order > 0) {
                   18744:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  18745:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  18746:                 foreach my $idx (@order) {
                   18747:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  18748:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  18749:                         my $id = $mapnum.':'.$idx;
                   18750:                         push(@{$suppids->{$src}},$id);
                   18751:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   18752:                             $hiddensupp->{$id} = 1;
                   18753:                         }
1.1146    raeburn  18754:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  18755:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   18756:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  18757:                         } else {
1.1391    raeburn  18758:                             my $allowed;
                   18759:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   18760:                                 $allowed = 1;
                   18761:                             } elsif ($possdel) {
                   18762:                                 foreach my $item (@{$suppids->{$src}}) {
                   18763:                                     next if ($item eq $id);
                   18764:                                     unless ($hiddensupp->{$item}) {
                   18765:                                        $allowed = 1;
                   18766:                                        last;
                   18767:                                     }
                   18768:                                 }
                   18769:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   18770:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   18771:                                 }
                   18772:                             }
                   18773:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   18774:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  18775:                             }
1.1143    raeburn  18776:                         }
                   18777:                     }
                   18778:                 }
                   18779:             }
                   18780:         }
                   18781:     }
1.1391    raeburn  18782:     return $errors;
                   18783: }
                   18784: 
                   18785: sub set_supp_httprefs {
                   18786:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   18787:     if (ref($supplemental) eq 'HASH') {
                   18788:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   18789:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   18790:                 next if ($src =~ /\.sequence$/);
                   18791:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   18792:                     my $allowed;
                   18793:                     if ($env{'request.role.adv'}) {
                   18794:                         $allowed = 1;
                   18795:                     } else {
                   18796:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   18797:                             unless ($supplemental->{'hidden'}->{$id}) {
                   18798:                                 $allowed = 1;
                   18799:                                 last;
                   18800:                             }
                   18801:                         }
                   18802:                     }
                   18803:                     if (exists($env{'httpref.'.$src})) {
                   18804:                         if ($possdel) {
                   18805:                             unless ($allowed) {
                   18806:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   18807:                             }
                   18808:                         }
                   18809:                     } elsif ($allowed) {
                   18810:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   18811:                     }
                   18812:                 }
                   18813:             }
                   18814:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18815:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18816:             }
                   18817:         }
                   18818:     }
                   18819: }
                   18820: 
                   18821: sub get_supp_parameter {
                   18822:     my ($resparm,$name)=@_;
                   18823:     return if ($resparm eq '');
                   18824:     my $value=undef;
                   18825:     my $ptype=undef;
                   18826:     foreach (split('&&&',$resparm)) {
                   18827:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   18828:         if ($thisname eq $name) {
                   18829:             $value=$thisvalue;
                   18830:             $ptype=$thistype;
                   18831:         }
                   18832:     }
                   18833:     return $value;
1.1143    raeburn  18834: }
                   18835: 
1.1101    raeburn  18836: sub symb_to_docspath {
1.1267    raeburn  18837:     my ($symb,$navmapref) = @_;
                   18838:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18839:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18840:     if ($resurl=~/\.(sequence|page)$/) {
                   18841:         $mapurl=$resurl;
                   18842:     } elsif ($resurl eq 'adm/navmaps') {
                   18843:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18844:     }
                   18845:     my $mapresobj;
1.1267    raeburn  18846:     unless (ref($$navmapref)) {
                   18847:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18848:     }
                   18849:     if (ref($$navmapref)) {
                   18850:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18851:     }
                   18852:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18853:     my $type=$2;
                   18854:     my $path;
                   18855:     if (ref($mapresobj)) {
                   18856:         my $pcslist = $mapresobj->map_hierarchy();
                   18857:         if ($pcslist ne '') {
                   18858:             foreach my $pc (split(/,/,$pcslist)) {
                   18859:                 next if ($pc <= 1);
1.1267    raeburn  18860:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18861:                 if (ref($res)) {
                   18862:                     my $thisurl = $res->src();
                   18863:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18864:                     my $thistitle = $res->title();
                   18865:                     $path .= '&'.
                   18866:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18867:                              &escape($thistitle).
1.1101    raeburn  18868:                              ':'.$res->randompick().
                   18869:                              ':'.$res->randomout().
                   18870:                              ':'.$res->encrypted().
                   18871:                              ':'.$res->randomorder().
                   18872:                              ':'.$res->is_page();
                   18873:                 }
                   18874:             }
                   18875:         }
                   18876:         $path =~ s/^\&//;
                   18877:         my $maptitle = $mapresobj->title();
                   18878:         if ($mapurl eq 'default') {
1.1129    raeburn  18879:             $maptitle = 'Main Content';
1.1101    raeburn  18880:         }
                   18881:         $path .= (($path ne '')? '&' : '').
                   18882:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18883:                  &escape($maptitle).
1.1101    raeburn  18884:                  ':'.$mapresobj->randompick().
                   18885:                  ':'.$mapresobj->randomout().
                   18886:                  ':'.$mapresobj->encrypted().
                   18887:                  ':'.$mapresobj->randomorder().
                   18888:                  ':'.$mapresobj->is_page();
                   18889:     } else {
                   18890:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18891:         my $ispage = (($type eq 'page')? 1 : '');
                   18892:         if ($mapurl eq 'default') {
1.1129    raeburn  18893:             $maptitle = 'Main Content';
1.1101    raeburn  18894:         }
                   18895:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18896:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18897:     }
                   18898:     unless ($mapurl eq 'default') {
                   18899:         $path = 'default&'.
1.1146    raeburn  18900:                 &escape('Main Content').
1.1101    raeburn  18901:                 ':::::&'.$path;
                   18902:     }
                   18903:     return $path;
                   18904: }
                   18905: 
1.1393    raeburn  18906: sub validate_folderpath {
                   18907:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   18908:     if ($env{'form.folderpath'} ne '') {
                   18909:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  18910:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  18911:         for (my $i=0; $i<@items; $i++) {
                   18912:             my $odd = $i%2;
                   18913:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   18914:                 $badpath = 1;
1.1394    raeburn  18915:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  18916:                 my $idx = $i-1;
1.1394    raeburn  18917:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   18918:                     my $esc_name = $1;
                   18919:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   18920:                         $supppath .= '&'.$esc_name;
                   18921:                         $changed = 1;
                   18922:                     } else {
                   18923:                         $supppath .= '&'.$items[$i];
                   18924:                     }
                   18925:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   18926:                     $changed = 1;
1.1393    raeburn  18927:                     my $is_hidden;
                   18928:                     unless ($got_supp) {
1.1395    raeburn  18929:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  18930:                         if (ref($supplemental) eq 'HASH') {
                   18931:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   18932:                                 %supphidden = %{$supplemental->{'hidden'}};
                   18933:                             }
                   18934:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   18935:                                 %suppids = %{$supplemental->{'ids'}};
                   18936:                             }
                   18937:                         }
                   18938:                         $got_supp = 1;
                   18939:                     }
                   18940:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   18941:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   18942:                         if ($supphidden{$mapid}) {
                   18943:                             $is_hidden = 1;
                   18944:                         }
                   18945:                     }
1.1394    raeburn  18946:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   18947:                 } else {
                   18948:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  18949:                 }
                   18950:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   18951:                 $badpath = 1;
1.1394    raeburn  18952:             } elsif ($supplementalflag) {
1.1393    raeburn  18953:                 $supppath .= '&'.$items[$i];
                   18954:             }
                   18955:             last if ($badpath);
                   18956:         }
                   18957:         if ($badpath) {
                   18958:             delete($env{'form.folderpath'});
1.1394    raeburn  18959:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  18960:             $supppath =~ s/^\&//;
                   18961:             $env{'form.folderpath'} = $supppath;
                   18962:         }
                   18963:     }
                   18964:     return;
                   18965: }
                   18966: 
1.1094    raeburn  18967: sub captcha_display {
1.1327    raeburn  18968:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18969:     my ($output,$error);
1.1234    raeburn  18970:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18971:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18972:     if ($captcha eq 'original') {
1.1094    raeburn  18973:         $output = &create_captcha();
                   18974:         unless ($output) {
1.1172    raeburn  18975:             $error = 'captcha';
1.1094    raeburn  18976:         }
                   18977:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18978:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18979:         unless ($output) {
1.1172    raeburn  18980:             $error = 'recaptcha';
1.1094    raeburn  18981:         }
                   18982:     }
1.1234    raeburn  18983:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18984: }
                   18985: 
                   18986: sub captcha_response {
1.1327    raeburn  18987:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18988:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18989:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18990:     if ($captcha eq 'original') {
1.1094    raeburn  18991:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18992:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18993:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18994:     } else {
                   18995:         $captcha_chk = 1;
                   18996:     }
                   18997:     return ($captcha_chk,$captcha_error);
                   18998: }
                   18999: 
                   19000: sub get_captcha_config {
1.1327    raeburn  19001:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19002:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19003:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19004:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19005:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19006:     if ($context eq 'usercreation') {
                   19007:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19008:         if (ref($domconfig{$context}) eq 'HASH') {
                   19009:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19010:             if (ref($hashtocheck) eq 'HASH') {
                   19011:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19012:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19013:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19014:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19015:                     }
                   19016:                     if ($privkey && $pubkey) {
                   19017:                         $captcha = 'recaptcha';
1.1234    raeburn  19018:                         $version = $hashtocheck->{'recaptchaversion'};
                   19019:                         if ($version ne '2') {
                   19020:                             $version = 1;
                   19021:                         }
1.1095    raeburn  19022:                     } else {
                   19023:                         $captcha = 'original';
                   19024:                     }
                   19025:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19026:                     $captcha = 'original';
                   19027:                 }
1.1094    raeburn  19028:             }
1.1095    raeburn  19029:         } else {
                   19030:             $captcha = 'captcha';
                   19031:         }
                   19032:     } elsif ($context eq 'login') {
                   19033:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19034:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19035:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19036:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19037:             if ($privkey && $pubkey) {
                   19038:                 $captcha = 'recaptcha';
1.1234    raeburn  19039:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19040:                 if ($version ne '2') {
                   19041:                     $version = 1; 
                   19042:                 }
1.1095    raeburn  19043:             } else {
                   19044:                 $captcha = 'original';
1.1094    raeburn  19045:             }
1.1095    raeburn  19046:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19047:             $captcha = 'original';
1.1094    raeburn  19048:         }
1.1327    raeburn  19049:     } elsif ($context eq 'passwords') {
                   19050:         if ($dom_in_effect) {
                   19051:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19052:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19053:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19054:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19055:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19056:                 }
                   19057:                 if ($privkey && $pubkey) {
                   19058:                     $captcha = 'recaptcha';
                   19059:                     $version = $passwdconf{'recaptchaversion'};
                   19060:                     if ($version ne '2') {
                   19061:                         $version = 1;
                   19062:                     }
                   19063:                 } else {
                   19064:                     $captcha = 'original';
                   19065:                 }
                   19066:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19067:                 $captcha = 'original';
                   19068:             }
                   19069:         }
                   19070:     } 
1.1234    raeburn  19071:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19072: }
                   19073: 
                   19074: sub create_captcha {
                   19075:     my %captcha_params = &captcha_settings();
                   19076:     my ($output,$maxtries,$tries) = ('',10,0);
                   19077:     while ($tries < $maxtries) {
                   19078:         $tries ++;
                   19079:         my $captcha = Authen::Captcha->new (
                   19080:                                            output_folder => $captcha_params{'output_dir'},
                   19081:                                            data_folder   => $captcha_params{'db_dir'},
                   19082:                                           );
                   19083:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19084: 
                   19085:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19086:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19087:                       '<span class="LC_nobreak">'.
1.1094    raeburn  19088:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19089:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  19090:                       '</span><br />'.
1.1176    raeburn  19091:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19092:             last;
                   19093:         }
                   19094:     }
1.1323    raeburn  19095:     if ($output eq '') {
                   19096:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19097:     }
1.1094    raeburn  19098:     return $output;
                   19099: }
                   19100: 
                   19101: sub captcha_settings {
                   19102:     my %captcha_params = (
                   19103:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19104:                            www_output_dir => "/captchaspool",
                   19105:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19106:                            numchars       => '5',
                   19107:                          );
                   19108:     return %captcha_params;
                   19109: }
                   19110: 
                   19111: sub check_captcha {
                   19112:     my ($captcha_chk,$captcha_error);
                   19113:     my $code = $env{'form.code'};
                   19114:     my $md5sum = $env{'form.crypt'};
                   19115:     my %captcha_params = &captcha_settings();
                   19116:     my $captcha = Authen::Captcha->new(
                   19117:                       output_folder => $captcha_params{'output_dir'},
                   19118:                       data_folder   => $captcha_params{'db_dir'},
                   19119:                   );
1.1109    raeburn  19120:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19121:     my %captcha_hash = (
                   19122:                         0       => 'Code not checked (file error)',
                   19123:                        -1      => 'Failed: code expired',
                   19124:                        -2      => 'Failed: invalid code (not in database)',
                   19125:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19126:     );
                   19127:     if ($captcha_chk != 1) {
                   19128:         $captcha_error = $captcha_hash{$captcha_chk}
                   19129:     }
                   19130:     return ($captcha_chk,$captcha_error);
                   19131: }
                   19132: 
                   19133: sub create_recaptcha {
1.1234    raeburn  19134:     my ($pubkey,$version) = @_;
                   19135:     if ($version >= 2) {
1.1367    raeburn  19136:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19137:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19138:     } else {
                   19139:         my $use_ssl;
                   19140:         if ($ENV{'SERVER_PORT'} == 443) {
                   19141:             $use_ssl = 1;
                   19142:         }
                   19143:         my $captcha = Captcha::reCAPTCHA->new;
                   19144:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19145:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19146:                &mt('If the text is hard to read, [_1] will replace them.',
                   19147:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19148:                '<br /><br />';
                   19149:     }
1.1094    raeburn  19150: }
                   19151: 
                   19152: sub check_recaptcha {
1.1234    raeburn  19153:     my ($privkey,$version) = @_;
1.1094    raeburn  19154:     my $captcha_chk;
1.1350    raeburn  19155:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19156:     if ($version >= 2) {
                   19157:         my %info = (
                   19158:                      secret   => $privkey, 
                   19159:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19160:                      remoteip => $ip,
1.1234    raeburn  19161:                    );
1.1280    raeburn  19162:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19163:         $request->content(join('&',map {
                   19164:                          my $name = escape($_);
                   19165:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19166:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19167:                          : &escape($info{$_}) );
                   19168:         } keys(%info)));
                   19169:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19170:         if ($response->is_success)  {
                   19171:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19172:             if (ref($data) eq 'HASH') {
                   19173:                 if ($data->{'success'}) {
                   19174:                     $captcha_chk = 1;
                   19175:                 }
                   19176:             }
                   19177:         }
                   19178:     } else {
                   19179:         my $captcha = Captcha::reCAPTCHA->new;
                   19180:         my $captcha_result =
                   19181:             $captcha->check_answer(
                   19182:                                     $privkey,
1.1350    raeburn  19183:                                     $ip,
1.1234    raeburn  19184:                                     $env{'form.recaptcha_challenge_field'},
                   19185:                                     $env{'form.recaptcha_response_field'},
                   19186:                                   );
                   19187:         if ($captcha_result->{is_valid}) {
                   19188:             $captcha_chk = 1;
                   19189:         }
1.1094    raeburn  19190:     }
                   19191:     return $captcha_chk;
                   19192: }
                   19193: 
1.1174    raeburn  19194: sub emailusername_info {
1.1244    raeburn  19195:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19196:     my %titles = &Apache::lonlocal::texthash (
                   19197:                      lastname      => 'Last Name',
                   19198:                      firstname     => 'First Name',
                   19199:                      institution   => 'School/college/university',
                   19200:                      location      => "School's city, state/province, country",
                   19201:                      web           => "School's web address",
                   19202:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19203:                      id            => 'Student/Employee ID',
1.1174    raeburn  19204:                  );
                   19205:     return (\@fields,\%titles);
                   19206: }
                   19207: 
1.1161    raeburn  19208: sub cleanup_html {
                   19209:     my ($incoming) = @_;
                   19210:     my $outgoing;
                   19211:     if ($incoming ne '') {
                   19212:         $outgoing = $incoming;
                   19213:         $outgoing =~ s/;/&#059;/g;
                   19214:         $outgoing =~ s/\#/&#035;/g;
                   19215:         $outgoing =~ s/\&/&#038;/g;
                   19216:         $outgoing =~ s/</&#060;/g;
                   19217:         $outgoing =~ s/>/&#062;/g;
                   19218:         $outgoing =~ s/\(/&#040/g;
                   19219:         $outgoing =~ s/\)/&#041;/g;
                   19220:         $outgoing =~ s/"/&#034;/g;
                   19221:         $outgoing =~ s/'/&#039;/g;
                   19222:         $outgoing =~ s/\$/&#036;/g;
                   19223:         $outgoing =~ s{/}{&#047;}g;
                   19224:         $outgoing =~ s/=/&#061;/g;
                   19225:         $outgoing =~ s/\\/&#092;/g
                   19226:     }
                   19227:     return $outgoing;
                   19228: }
                   19229: 
1.1190    musolffc 19230: # Checks for critical messages and returns a redirect url if one exists.
                   19231: # $interval indicates how often to check for messages.
1.1282    raeburn  19232: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19233: sub critical_redirect {
1.1282    raeburn  19234:     my ($interval,$context) = @_;
1.1356    raeburn  19235:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19236:         return ();
                   19237:     }
1.1190    musolffc 19238:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19239:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19240:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19241:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19242:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19243:             if ($blocked) {
                   19244:                 my $checkrole = "cm./$cdom/$cnum";
                   19245:                 if ($env{'request.course.sec'} ne '') {
                   19246:                     $checkrole .= "/$env{'request.course.sec'}";
                   19247:                 }
                   19248:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19249:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19250:                     return;
                   19251:                 }
                   19252:             }
                   19253:         }
1.1190    musolffc 19254:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19255:                                         $env{'user.name'});
                   19256:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19257:         my $redirecturl;
1.1190    musolffc 19258:         if ($what[0]) {
1.1356    raeburn  19259: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19260: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19261: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19262:                 return (1, $url);
1.1190    musolffc 19263:             }
1.1191    raeburn  19264:         }
                   19265:     } 
                   19266:     return ();
1.1190    musolffc 19267: }
                   19268: 
1.1174    raeburn  19269: # Use:
                   19270: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19271: #
                   19272: ##################################################
                   19273: #          password associated functions         #
                   19274: ##################################################
                   19275: sub des_keys {
                   19276:     # Make a new key for DES encryption.
                   19277:     # Each key has two parts which are returned separately.
                   19278:     # Please note:  Each key must be passed through the &hex function
                   19279:     # before it is output to the web browser.  The hex versions cannot
                   19280:     # be used to decrypt.
                   19281:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19282:                 '8','9','a','b','c','d','e','f');
                   19283:     my $lkey='';
                   19284:     for (0..7) {
                   19285:         $lkey.=$hexstr[rand(15)];
                   19286:     }
                   19287:     my $ukey='';
                   19288:     for (0..7) {
                   19289:         $ukey.=$hexstr[rand(15)];
                   19290:     }
                   19291:     return ($lkey,$ukey);
                   19292: }
                   19293: 
                   19294: sub des_decrypt {
                   19295:     my ($key,$cyphertext) = @_;
                   19296:     my $keybin=pack("H16",$key);
                   19297:     my $cypher;
                   19298:     if ($Crypt::DES::VERSION>=2.03) {
                   19299:         $cypher=new Crypt::DES $keybin;
                   19300:     } else {
                   19301:         $cypher=new DES $keybin;
                   19302:     }
1.1233    raeburn  19303:     my $plaintext='';
                   19304:     my $cypherlength = length($cyphertext);
                   19305:     my $numchunks = int($cypherlength/32);
                   19306:     for (my $j=0; $j<$numchunks; $j++) {
                   19307:         my $start = $j*32;
                   19308:         my $cypherblock = substr($cyphertext,$start,32);
                   19309:         my $chunk =
                   19310:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19311:         $chunk .=
                   19312:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19313:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19314:         $plaintext .= $chunk;
                   19315:     }
1.1174    raeburn  19316:     return $plaintext;
                   19317: }
                   19318: 
1.1344    raeburn  19319: sub get_requested_shorturls {
1.1309    raeburn  19320:     my ($cdom,$cnum,$navmap) = @_;
                   19321:     return unless (ref($navmap));
1.1344    raeburn  19322:     my ($numnew,$errors);
1.1309    raeburn  19323:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19324:     if (@toshorten) {
                   19325:         my (%maps,%resources,%titles);
                   19326:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19327:                                                                'shorturls',$cdom,$cnum);
                   19328:         if (keys(%resources)) {
1.1344    raeburn  19329:             my %tocreate;
1.1309    raeburn  19330:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19331:                 my $symb = $resources{$item};
                   19332:                 if ($symb) {
                   19333:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19334:                 }
                   19335:             }
1.1344    raeburn  19336:             if (keys(%tocreate)) {
                   19337:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19338:                                                       \%tocreate);
                   19339:             }
1.1309    raeburn  19340:         }
1.1344    raeburn  19341:     }
                   19342:     return ($numnew,$errors);
                   19343: }
                   19344: 
                   19345: sub make_short_symbs {
                   19346:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19347:     my ($numnew,@errors);
                   19348:     if (ref($tocreateref) eq 'HASH') {
                   19349:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19350:         if (keys(%tocreate)) {
                   19351:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19352:             my $su = Short::URL->new(no_vowels => 1);
                   19353:             my $init = '';
                   19354:             my (%newunique,%addcourse,%courseonly,%failed);
                   19355:             # get lock on tiny db
                   19356:             my $now = time;
1.1344    raeburn  19357:             if ($lockuser eq '') {
                   19358:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19359:             }
1.1309    raeburn  19360:             my $lockhash = {
1.1344    raeburn  19361:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19362:                             };
                   19363:             my $tries = 0;
                   19364:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19365:             my ($code,$error);
                   19366:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19367:                 $tries ++;
                   19368:                 sleep 1;
1.1319    raeburn  19369:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19370:             }
                   19371:             if ($gotlock eq 'ok') {
                   19372:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19373:                                        \%addcourse,\%courseonly,\%failed);
                   19374:                 if (keys(%failed)) {
                   19375:                     my $numfailed = scalar(keys(%failed));
                   19376:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19377:                 }
                   19378:                 if (keys(%newunique)) {
                   19379:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19380:                     if ($putres eq 'ok') {
                   19381:                         $numnew = scalar(keys(%newunique));
                   19382:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19383:                         unless ($newputres eq 'ok') {
                   19384:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19385:                         }
                   19386:                     } else {
                   19387:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19388:                     }
                   19389:                 }
                   19390:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19391:                 unless ($dellockres eq 'ok') {
                   19392:                     push(@errors,&mt('error: could not release lockfile'));
                   19393:                 }
                   19394:             } else {
                   19395:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19396:             }
                   19397:             if (keys(%courseonly)) {
                   19398:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19399:                 if ($result ne 'ok') {
                   19400:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19401:                 }
                   19402:             }
                   19403:         }
                   19404:     }
                   19405:     return ($numnew,\@errors);
                   19406: }
                   19407: 
                   19408: sub shorten_symbs {
                   19409:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19410:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19411:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19412:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19413:     my (%possibles,%collisions);
                   19414:     foreach my $key (keys(%{$tocreate})) {
                   19415:         my $num = String::CRC32::crc32($key);
                   19416:         my $tiny = $su->encode($num,$init);
                   19417:         if ($tiny) {
                   19418:             $possibles{$tiny} = $key;
                   19419:         }
                   19420:     }
                   19421:     if (!$init) {
                   19422:         $init = 1;
                   19423:     } else {
                   19424:         $init ++;
                   19425:     }
                   19426:     if (keys(%possibles)) {
                   19427:         my @posstiny = keys(%possibles);
                   19428:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19429:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19430:         if (keys(%currtiny)) {
                   19431:             foreach my $key (keys(%currtiny)) {
                   19432:                 next if ($currtiny{$key} eq '');
                   19433:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19434:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19435:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19436:                         $courseonly->{$tsymb} = $key;
                   19437:                     }
                   19438:                 } else {
                   19439:                     $collisions{$possibles{$key}} = 1;
                   19440:                 }
                   19441:                 delete($possibles{$key});
                   19442:             }
                   19443:         }
                   19444:         foreach my $key (keys(%possibles)) {
                   19445:             $newunique->{$key} = $possibles{$key};
                   19446:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19447:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19448:                 $addcourse->{$tsymb} = $key;
                   19449:             }
                   19450:         }
                   19451:     }
                   19452:     if (keys(%collisions)) {
                   19453:         if ($init <5) {
                   19454:             if (!$init) {
                   19455:                 $init = 1;
                   19456:             } else {
                   19457:                 $init ++;
                   19458:             }
                   19459:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19460:                                    $newunique,$addcourse,$courseonly,$failed);
                   19461:         } else {
                   19462:             foreach my $key (keys(%collisions)) {
                   19463:                 $failed->{$key} = 1;
                   19464:             }
                   19465:         }
                   19466:     }
                   19467:     return $init;
                   19468: }
                   19469: 
1.1328    raeburn  19470: sub is_nonframeable {
1.1329    raeburn  19471:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19472:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19473:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19474: 
                   19475:     $remprotocol = lc($remprotocol);
                   19476:     $remhost = lc($remhost);
                   19477:     my $remport = 80;
                   19478:     if ($remprotocol eq 'https') {
                   19479:         $remport = 443;
                   19480:     }
1.1330    raeburn  19481:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19482:     if ($cached) {
                   19483:         unless ($nocache) {
                   19484:             if ($result) {
                   19485:                 return 1;
                   19486:             } else {
                   19487:                 return 0;
                   19488:             }
                   19489:         }
                   19490:     }
1.1328    raeburn  19491:     my $uselink;
                   19492:     my $request = new HTTP::Request('HEAD',$url);
                   19493:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19494:     if ($response->is_success()) {
                   19495:         my $secpolicy = lc($response->header('content-security-policy'));
                   19496:         my $xframeop = lc($response->header('x-frame-options'));
                   19497:         $secpolicy =~ s/^\s+|\s+$//g;
                   19498:         $xframeop =~ s/^\s+|\s+$//g;
                   19499:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19500:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19501:             my ($origin,$protocol,$port);
                   19502:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19503:                 $port = $ENV{'SERVER_PORT'};
                   19504:             } else {
                   19505:                 $port = 80;
                   19506:             }
                   19507:             if ($absolute eq '') {
                   19508:                 $protocol = 'http:';
                   19509:                 if ($port == 443) {
                   19510:                     $protocol = 'https:';
                   19511:                 }
                   19512:                 $origin = $protocol.'//'.lc($hostname);
                   19513:             } else {
                   19514:                 $origin = lc($absolute);
                   19515:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19516:             }
                   19517:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19518:                 my $framepolicy = $1;
                   19519:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19520:                 my @policies = split(/\s+/,$framepolicy);
                   19521:                 if (@policies) {
                   19522:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19523:                         $uselink = 1;
                   19524:                     } else {
                   19525:                         $uselink = 1;
                   19526:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19527:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19528:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19529:                             undef($uselink);
                   19530:                         }
                   19531:                         if ($uselink) {
                   19532:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19533:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19534:                                     undef($uselink);
                   19535:                                 }
                   19536:                             }
                   19537:                         }
                   19538:                         if ($uselink) {
                   19539:                             my @possok;
                   19540:                             if ($ip ne '') {
                   19541:                                 push(@possok,$ip);
                   19542:                             }
                   19543:                             my $hoststr = '';
                   19544:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19545:                                 if ($hoststr eq '') {
                   19546:                                     $hoststr = $part;
                   19547:                                 } else {
                   19548:                                     $hoststr = "$part.$hoststr";
                   19549:                                 }
                   19550:                                 if ($hoststr eq $hostname) {
                   19551:                                     push(@possok,$hostname);
                   19552:                                 } else {
                   19553:                                     push(@possok,"*.$hoststr");
                   19554:                                 }
                   19555:                             }
                   19556:                             if (@possok) {
                   19557:                                 foreach my $poss (@possok) {
                   19558:                                     last if (!$uselink);
                   19559:                                     foreach my $policy (@policies) {
                   19560:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19561:                                             undef($uselink);
                   19562:                                             last;
                   19563:                                         }
                   19564:                                     }
                   19565:                                 }
                   19566:                             }
                   19567:                         }
                   19568:                     }
                   19569:                 }
                   19570:             } elsif ($xframeop ne '') {
                   19571:                 $uselink = 1;
                   19572:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19573:                 if (@policies) {
                   19574:                     unless (grep(/^deny$/,@policies)) {
                   19575:                         if ($origin ne '') {
                   19576:                             if (grep(/^sameorigin$/,@policies)) {
                   19577:                                 if ($remotehost eq $origin) {
                   19578:                                     undef($uselink);
                   19579:                                 }
                   19580:                             }
                   19581:                             if ($uselink) {
                   19582:                                 foreach my $policy (@policies) {
                   19583:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19584:                                         my $allowfrom = $1;
                   19585:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19586:                                             undef($uselink);
                   19587:                                             last;
                   19588:                                         }
                   19589:                                     }
                   19590:                                 }
                   19591:                             }
                   19592:                         }
                   19593:                     }
                   19594:                 }
                   19595:             }
                   19596:         }
                   19597:     }
1.1329    raeburn  19598:     if ($nocache) {
                   19599:         if ($cached) {
                   19600:             my $devalidate;
                   19601:             if ($uselink && !$result) {
                   19602:                 $devalidate = 1;
                   19603:             } elsif (!$uselink && $result) {
                   19604:                 $devalidate = 1;
                   19605:             }
                   19606:             if ($devalidate) {
                   19607:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19608:             }
                   19609:         }
                   19610:     } else {
                   19611:         if ($uselink) {
                   19612:             $result = 1;
                   19613:         } else {
                   19614:             $result = 0;
                   19615:         }
                   19616:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19617:     }
1.1328    raeburn  19618:     return $uselink;
                   19619: }
                   19620: 
1.1359    raeburn  19621: sub page_menu {
                   19622:     my ($menucolls,$menunum) = @_;
                   19623:     my %menu;
                   19624:     foreach my $item (split(/;/,$menucolls)) {
                   19625:         my ($num,$value) = split(/\%/,$item);
                   19626:         if ($num eq $menunum) {
                   19627:             my @entries = split(/\&/,$value);
                   19628:             foreach my $entry (@entries) {
                   19629:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19630:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19631:                     $menu{$name} = $fields;
                   19632:                 } else {
                   19633:                     my @shown;
                   19634:                     if ($fields =~ /,/) {
                   19635:                         @shown = split(/,/,$fields);
                   19636:                     } else {
                   19637:                         @shown = ($fields);
                   19638:                     }
                   19639:                     if (@shown) {
                   19640:                         foreach my $field (@shown) {
                   19641:                             next if ($field eq '');
                   19642:                             $menu{$field} = 1;
                   19643:                         }
                   19644:                     }
                   19645:                 }
                   19646:             }
                   19647:         }
                   19648:     }
                   19649:     return %menu;
                   19650: }
                   19651: 
1.112     bowersj2 19652: 1;
                   19653: __END__;
1.41      ng       19654: 

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