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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.149! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.148 2020/10/01 10:27:14 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.685     tempelho   64: use Apache::lonnet();
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.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1075.2.135  raeburn    74: use HTTP::Request;
1.657     raeburn    75: use DateTime::TimeZone;
1.1075.2.102  raeburn    76: use DateTime::Locale;
1.1075.2.94  raeburn    77: use Encode();
1.1075.2.14  raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1075.2.64  raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    84: use File::Copy();
                     85: use File::Path();
1.117     www        86: 
1.517     raeburn    87: # ---------------------------------------------- Designs
                     88: use vars qw(%defaultdesign);
                     89: 
1.22      www        90: my $readit;
                     91: 
1.517     raeburn    92: 
1.157     matthew    93: ##
                     94: ## Global Variables
                     95: ##
1.46      matthew    96: 
1.643     foxr       97: 
                     98: # ----------------------------------------------- SSI with retries:
                     99: #
                    100: 
                    101: =pod
                    102: 
1.648     raeburn   103: =head1 Server Side include with retries:
1.643     foxr      104: 
                    105: =over 4
                    106: 
1.648     raeburn   107: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      108: 
                    109: Performs an ssi with some number of retries.  Retries continue either
                    110: until the result is ok or until the retry count supplied by the
                    111: caller is exhausted.  
                    112: 
                    113: Inputs:
1.648     raeburn   114: 
                    115: =over 4
                    116: 
1.643     foxr      117: resource   - Identifies the resource to insert.
1.648     raeburn   118: 
1.643     foxr      119: retries    - Count of the number of retries allowed.
1.648     raeburn   120: 
1.643     foxr      121: form       - Hash that identifies the rendering options.
                    122: 
1.648     raeburn   123: =back
                    124: 
                    125: Returns:
                    126: 
                    127: =over 4
                    128: 
1.643     foxr      129: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   130: 
1.643     foxr      131: response   - The response from the last attempt (which may or may not have been successful.
                    132: 
1.648     raeburn   133: =back
                    134: 
                    135: =back
                    136: 
1.643     foxr      137: =cut
                    138: 
                    139: sub ssi_with_retries {
                    140:     my ($resource, $retries, %form) = @_;
                    141: 
                    142: 
                    143:     my $ok = 0;			# True if we got a good response.
                    144:     my $content;
                    145:     my $response;
                    146: 
                    147:     # Try to get the ssi done. within the retries count:
                    148: 
                    149:     do {
                    150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    151: 	$ok      = $response->is_success;
1.650     www       152:         if (!$ok) {
                    153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    154:         }
1.643     foxr      155: 	$retries--;
                    156:     } while (!$ok && ($retries > 0));
                    157: 
                    158:     if (!$ok) {
                    159: 	$content = '';		# On error return an empty content.
                    160:     }
                    161:     return ($content, $response);
                    162: 
                    163: }
                    164: 
                    165: 
                    166: 
1.20      www       167: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  168: my %language;
1.124     www       169: my %supported_language;
1.1048    foxr      170: my %latex_language;		# For choosing hyphenation in <transl..>
                    171: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  172: my %cprtag;
1.192     taceyjo1  173: my %scprtag;
1.351     www       174: my %fe; my %fd; my %fm;
1.41      ng        175: my %category_extensions;
1.12      harris41  176: 
1.46      matthew   177: # ---------------------------------------------- Thesaurus variables
1.144     matthew   178: #
                    179: # %Keywords:
                    180: #      A hash used by &keyword to determine if a word is considered a keyword.
                    181: # $thesaurus_db_file 
                    182: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   183: 
                    184: my %Keywords;
                    185: my $thesaurus_db_file;
                    186: 
1.144     matthew   187: #
                    188: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    189: # thesaurus.tab, and filecategories.tab.
                    190: #
1.18      www       191: BEGIN {
1.46      matthew   192:     # Variable initialization
                    193:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    194:     #
1.22      www       195:     unless ($readit) {
1.12      harris41  196: # ------------------------------------------------------------------- languages
                    197:     {
1.158     raeburn   198:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    199:                                    '/language.tab';
1.1075.2.128  raeburn   200:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  201:             while (my $line = <$fh>) {
                    202:                 next if ($line=~/^\#/);
                    203:                 chomp($line);
1.1048    foxr      204:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   205:                 $language{$key}=$val.' - '.$enc;
                    206:                 if ($sup) {
                    207:                     $supported_language{$key}=$sup;
                    208:                 }
1.1048    foxr      209: 		if ($latex) {
                    210: 		    $latex_language_bykey{$key} = $latex;
                    211: 		    $latex_language{$two} = $latex;
                    212: 		}
1.158     raeburn   213:             }
                    214:             close($fh);
                    215:         }
1.12      harris41  216:     }
                    217: # ------------------------------------------------------------------ copyrights
                    218:     {
1.158     raeburn   219:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    220:                                   '/copyright.tab';
1.1075.2.128  raeburn   221:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  222:             while (my $line = <$fh>) {
                    223:                 next if ($line=~/^\#/);
                    224:                 chomp($line);
                    225:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   226:                 $cprtag{$key}=$val;
                    227:             }
                    228:             close($fh);
                    229:         }
1.12      harris41  230:     }
1.351     www       231: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  232:     {
                    233:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    234:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   235:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  236:             while (my $line = <$fh>) {
                    237:                 next if ($line =~ /^\#/);
                    238:                 chomp($line);
                    239:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  240:                 $scprtag{$key}=$val;
                    241:             }
                    242:             close($fh);
                    243:         }
                    244:     }
1.63      www       245: 
1.517     raeburn   246: # -------------------------------------------------------------- default domain designs
1.63      www       247:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   248:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   249:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   250:         while (my $line = <$fh>) {
                    251:             next if ($line =~ /^\#/);
                    252:             chomp($line);
                    253:             my ($key,$val)=(split(/\=/,$line));
                    254:             if ($val) { $defaultdesign{$key}=$val; }
                    255:         }
                    256:         close($fh);
1.63      www       257:     }
                    258: 
1.15      harris41  259: # ------------------------------------------------------------- file categories
                    260:     {
1.158     raeburn   261:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    262:                                   '/filecategories.tab';
1.1075.2.128  raeburn   263:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  264: 	    while (my $line = <$fh>) {
                    265: 		next if ($line =~ /^\#/);
                    266: 		chomp($line);
                    267:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   268:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   269:             }
                    270:             close($fh);
                    271:         }
                    272: 
1.15      harris41  273:     }
1.12      harris41  274: # ------------------------------------------------------------------ file types
                    275:     {
1.158     raeburn   276:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    277:                '/filetypes.tab';
1.1075.2.128  raeburn   278:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  279:             while (my $line = <$fh>) {
                    280: 		next if ($line =~ /^\#/);
                    281: 		chomp($line);
                    282:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   283:                 if ($descr ne '') {
                    284:                     $fe{$ending}=lc($emb);
                    285:                     $fd{$ending}=$descr;
1.351     www       286:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   287:                 }
                    288:             }
                    289:             close($fh);
                    290:         }
1.12      harris41  291:     }
1.22      www       292:     &Apache::lonnet::logthis(
1.705     tempelho  293:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       294:     $readit=1;
1.46      matthew   295:     }  # end of unless($readit) 
1.32      matthew   296:     
                    297: }
1.112     bowersj2  298: 
1.42      matthew   299: ###############################################################
                    300: ##           HTML and Javascript Helper Functions            ##
                    301: ###############################################################
                    302: 
                    303: =pod 
                    304: 
1.112     bowersj2  305: =head1 HTML and Javascript Functions
1.42      matthew   306: 
1.112     bowersj2  307: =over 4
                    308: 
1.648     raeburn   309: =item * &browser_and_searcher_javascript()
1.112     bowersj2  310: 
                    311: X<browsing, javascript>X<searching, javascript>Returns a string
                    312: containing javascript with two functions, C<openbrowser> and
                    313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    314: tags.
1.42      matthew   315: 
1.648     raeburn   316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   317: 
                    318: inputs: formname, elementname, only, omit
                    319: 
                    320: formname and elementname indicate the name of the html form and name of
                    321: the element that the results of the browsing selection are to be placed in. 
                    322: 
                    323: Specifying 'only' will restrict the browser to displaying only files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
                    326: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
1.648     raeburn   329: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   330: 
                    331: Inputs: formname, elementname
                    332: 
                    333: formname and elementname specify the name of the html form and the name
                    334: of the element the selection from the search results will be placed in.
1.542     raeburn   335: 
1.42      matthew   336: =cut
                    337: 
                    338: sub browser_and_searcher_javascript {
1.199     albertel  339:     my ($mode)=@_;
                    340:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  341:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   342:     return <<END;
1.219     albertel  343: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   344:     var editbrowser = null;
1.135     albertel  345:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       346:         var url = '$resurl/?';
1.42      matthew   347:         if (editbrowser == null) {
                    348:             url += 'launch=1&';
                    349:         }
                    350:         url += 'catalogmode=interactive&';
1.199     albertel  351:         url += 'mode=$mode&';
1.611     albertel  352:         url += 'inhibitmenu=yes&';
1.42      matthew   353:         url += 'form=' + formname + '&';
                    354:         if (only != null) {
                    355:             url += 'only=' + only + '&';
1.217     albertel  356:         } else {
                    357:             url += 'only=&';
                    358: 	}
1.42      matthew   359:         if (omit != null) {
                    360:             url += 'omit=' + omit + '&';
1.217     albertel  361:         } else {
                    362:             url += 'omit=&';
                    363: 	}
1.135     albertel  364:         if (titleelement != null) {
                    365:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  366:         } else {
                    367: 	    url += 'titleelement=&';
                    368: 	}
1.42      matthew   369:         url += 'element=' + elementname + '';
                    370:         var title = 'Browser';
1.435     albertel  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   372:         options += ',width=700,height=600';
                    373:         editbrowser = open(url,title,options,'1');
                    374:         editbrowser.focus();
                    375:     }
                    376:     var editsearcher;
1.135     albertel  377:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   378:         var url = '/adm/searchcat?';
                    379:         if (editsearcher == null) {
                    380:             url += 'launch=1&';
                    381:         }
                    382:         url += 'catalogmode=interactive&';
1.199     albertel  383:         url += 'mode=$mode&';
1.42      matthew   384:         url += 'form=' + formname + '&';
1.135     albertel  385:         if (titleelement != null) {
                    386:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  387:         } else {
                    388: 	    url += 'titleelement=&';
                    389: 	}
1.42      matthew   390:         url += 'element=' + elementname + '';
                    391:         var title = 'Search';
1.435     albertel  392:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   393:         options += ',width=700,height=600';
                    394:         editsearcher = open(url,title,options,'1');
                    395:         editsearcher.focus();
                    396:     }
1.219     albertel  397: // END LON-CAPA Internal -->
1.42      matthew   398: END
1.170     www       399: }
                    400: 
                    401: sub lastresurl {
1.258     albertel  402:     if ($env{'environment.lastresurl'}) {
                    403: 	return $env{'environment.lastresurl'}
1.170     www       404:     } else {
                    405: 	return '/res';
                    406:     }
                    407: }
                    408: 
                    409: sub storeresurl {
                    410:     my $resurl=&Apache::lonnet::clutter(shift);
                    411:     unless ($resurl=~/^\/res/) { return 0; }
                    412:     $resurl=~s/\/$//;
                    413:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   414:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       415:     return 1;
1.42      matthew   416: }
                    417: 
1.74      www       418: sub studentbrowser_javascript {
1.111     www       419:    unless (
1.258     albertel  420:             (($env{'request.course.id'}) && 
1.302     albertel  421:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    422: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    423: 					  '/'.$env{'request.course.sec'})
                    424: 	      ))
1.258     albertel  425:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       426:           ) { return ''; }  
1.74      www       427:    return (<<'ENDSTDBRW');
1.776     bisitz    428: <script type="text/javascript" language="Javascript">
1.824     bisitz    429: // <![CDATA[
1.74      www       430:     var stdeditbrowser;
1.1075.2.143  raeburn   431:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       432:         var url = '/adm/pickstudent?';
                    433:         var filter;
1.558     albertel  434: 	if (!ignorefilter) {
                    435: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    436: 	}
1.74      www       437:         if (filter != null) {
                    438:            if (filter != '') {
                    439:                url += 'filter='+filter+'&';
                    440: 	   }
                    441:         }
                    442:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       443:                                     '&udomelement='+udom+
                    444:                                     '&clicker='+clicker;
1.111     www       445: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   446:         if (courseadv == 'condition') {
                    447:             if (document.getElementById('courseadv')) {
                    448:                 courseadv = document.getElementById('courseadv').value;
                    449:             }
                    450:         }
                    451:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       452:         var title = 'Student_Browser';
1.74      www       453:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    454:         options += ',width=700,height=600';
                    455:         stdeditbrowser = open(url,title,options,'1');
                    456:         stdeditbrowser.focus();
                    457:     }
1.824     bisitz    458: // ]]>
1.74      www       459: </script>
                    460: ENDSTDBRW
                    461: }
1.42      matthew   462: 
1.1003    www       463: sub resourcebrowser_javascript {
                    464:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       465:    return (<<'ENDRESBRW');
1.1003    www       466: <script type="text/javascript" language="Javascript">
                    467: // <![CDATA[
                    468:     var reseditbrowser;
1.1004    www       469:     function openresbrowser(formname,reslink) {
1.1005    www       470:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       471:         var title = 'Resource_Browser';
                    472:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       473:         options += ',width=700,height=500';
1.1004    www       474:         reseditbrowser = open(url,title,options,'1');
                    475:         reseditbrowser.focus();
1.1003    www       476:     }
                    477: // ]]>
                    478: </script>
1.1004    www       479: ENDRESBRW
1.1003    www       480: }
                    481: 
1.74      www       482: sub selectstudent_link {
1.1075.2.143  raeburn   483:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       484:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    485:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    486:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  487:    if ($env{'request.course.id'}) {  
1.302     albertel  488:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    489: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    490: 					'/'.$env{'request.course.sec'})) {
1.111     www       491: 	   return '';
                    492:        }
1.999     www       493:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   494:        if ($courseadv eq 'only') {
                    495:            $callargs .= ",'',1,'$courseadv'";
                    496:        } elsif ($courseadv eq 'none') {
                    497:            $callargs .= ",'','','$courseadv'";
                    498:        } elsif ($courseadv eq 'condition') {
                    499:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   500:        }
                    501:        return '<span class="LC_nobreak">'.
                    502:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    503:               &mt('Select User').'</a></span>';
1.74      www       504:    }
1.258     albertel  505:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       506:        $callargs .= ",'',1"; 
1.793     raeburn   507:        return '<span class="LC_nobreak">'.
                    508:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    509:               &mt('Select User').'</a></span>';
1.111     www       510:    }
                    511:    return '';
1.91      www       512: }
                    513: 
1.1004    www       514: sub selectresource_link {
                    515:    my ($form,$reslink,$arg)=@_;
                    516:    
                    517:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    518:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    519:    unless ($env{'request.course.id'}) { return $arg; }
                    520:    return '<span class="LC_nobreak">'.
                    521:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    522:               $arg.'</a></span>';
                    523: }
                    524: 
                    525: 
                    526: 
1.653     raeburn   527: sub authorbrowser_javascript {
                    528:     return <<"ENDAUTHORBRW";
1.776     bisitz    529: <script type="text/javascript" language="JavaScript">
1.824     bisitz    530: // <![CDATA[
1.653     raeburn   531: var stdeditbrowser;
                    532: 
                    533: function openauthorbrowser(formname,udom) {
                    534:     var url = '/adm/pickauthor?';
                    535:     url += 'form='+formname+'&roledom='+udom;
                    536:     var title = 'Author_Browser';
                    537:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    538:     options += ',width=700,height=600';
                    539:     stdeditbrowser = open(url,title,options,'1');
                    540:     stdeditbrowser.focus();
                    541: }
                    542: 
1.824     bisitz    543: // ]]>
1.653     raeburn   544: </script>
                    545: ENDAUTHORBRW
                    546: }
                    547: 
1.91      www       548: sub coursebrowser_javascript {
1.1075.2.31  raeburn   549:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   550:         $credits_element,$instcode) = @_;
1.932     raeburn   551:     my $wintitle = 'Course_Browser';
1.931     raeburn   552:     if ($crstype eq 'Community') {
1.932     raeburn   553:         $wintitle = 'Community_Browser';
1.909     raeburn   554:     }
1.876     raeburn   555:     my $id_functions = &javascript_index_functions();
                    556:     my $output = '
1.776     bisitz    557: <script type="text/javascript" language="JavaScript">
1.824     bisitz    558: // <![CDATA[
1.468     raeburn   559:     var stdeditbrowser;'."\n";
1.876     raeburn   560: 
                    561:     $output .= <<"ENDSTDBRW";
1.909     raeburn   562:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       563:         var url = '/adm/pickcourse?';
1.895     raeburn   564:         var formid = getFormIdByName(formname);
1.876     raeburn   565:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  566:         if (domainfilter != null) {
                    567:            if (domainfilter != '') {
                    568:                url += 'domainfilter='+domainfilter+'&';
                    569: 	   }
                    570:         }
1.91      www       571:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  572: 	                            '&cdomelement='+udom+
                    573:                                     '&cnameelement='+desc;
1.468     raeburn   574:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   575:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   576:                 url += '&roleelement='+extra_element;
                    577:                 if (domainfilter == null || domainfilter == '') {
                    578:                     url += '&domainfilter='+extra_element;
                    579:                 }
1.234     raeburn   580:             }
1.468     raeburn   581:             else {
                    582:                 if (formname == 'portform') {
                    583:                     url += '&setroles='+extra_element;
1.800     raeburn   584:                 } else {
                    585:                     if (formname == 'rules') {
                    586:                         url += '&fixeddom='+extra_element; 
                    587:                     }
1.468     raeburn   588:                 }
                    589:             }     
1.230     raeburn   590:         }
1.909     raeburn   591:         if (type != null && type != '') {
                    592:             url += '&type='+type;
                    593:         }
                    594:         if (type_elem != null && type_elem != '') {
                    595:             url += '&typeelement='+type_elem;
                    596:         }
1.872     raeburn   597:         if (formname == 'ccrs') {
                    598:             var ownername = document.forms[formid].ccuname.value;
                    599:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   600:             url += '&cloner='+ownername+':'+ownerdom;
                    601:             if (type == 'Course') {
                    602:                 url += '&crscode='+document.forms[formid].crscode.value;
                    603:             }
1.1075.2.95  raeburn   604:         }
                    605:         if (formname == 'requestcrs') {
                    606:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   607:         }
1.293     raeburn   608:         if (multflag !=null && multflag != '') {
                    609:             url += '&multiple='+multflag;
                    610:         }
1.909     raeburn   611:         var title = '$wintitle';
1.91      www       612:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    613:         options += ',width=700,height=600';
                    614:         stdeditbrowser = open(url,title,options,'1');
                    615:         stdeditbrowser.focus();
                    616:     }
1.876     raeburn   617: $id_functions
                    618: ENDSTDBRW
1.1075.2.31  raeburn   619:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    620:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    621:                                       $credits_element);
1.876     raeburn   622:     }
                    623:     $output .= '
                    624: // ]]>
                    625: </script>';
                    626:     return $output;
                    627: }
                    628: 
                    629: sub javascript_index_functions {
                    630:     return <<"ENDJS";
                    631: 
                    632: function getFormIdByName(formname) {
                    633:     for (var i=0;i<document.forms.length;i++) {
                    634:         if (document.forms[i].name == formname) {
                    635:             return i;
                    636:         }
                    637:     }
                    638:     return -1;
                    639: }
                    640: 
                    641: function getIndexByName(formid,item) {
                    642:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    643:         if (document.forms[formid].elements[i].name == item) {
                    644:             return i;
                    645:         }
                    646:     }
                    647:     return -1;
                    648: }
1.468     raeburn   649: 
1.876     raeburn   650: function getDomainFromSelectbox(formname,udom) {
                    651:     var userdom;
                    652:     var formid = getFormIdByName(formname);
                    653:     if (formid > -1) {
                    654:         var domid = getIndexByName(formid,udom);
                    655:         if (domid > -1) {
                    656:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    657:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    658:             }
                    659:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    660:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   661:             }
                    662:         }
                    663:     }
1.876     raeburn   664:     return userdom;
                    665: }
                    666: 
                    667: ENDJS
1.468     raeburn   668: 
1.876     raeburn   669: }
                    670: 
1.1017    raeburn   671: sub javascript_array_indexof {
1.1018    raeburn   672:     return <<ENDJS;
1.1017    raeburn   673: <script type="text/javascript" language="JavaScript">
                    674: // <![CDATA[
                    675: 
                    676: if (!Array.prototype.indexOf) {
                    677:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    678:         "use strict";
                    679:         if (this === void 0 || this === null) {
                    680:             throw new TypeError();
                    681:         }
                    682:         var t = Object(this);
                    683:         var len = t.length >>> 0;
                    684:         if (len === 0) {
                    685:             return -1;
                    686:         }
                    687:         var n = 0;
                    688:         if (arguments.length > 0) {
                    689:             n = Number(arguments[1]);
                    690:             if (n !== n) { // shortcut for verifying if it's NaN
                    691:                 n = 0;
                    692:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    693:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    694:             }
                    695:         }
                    696:         if (n >= len) {
                    697:             return -1;
                    698:         }
                    699:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    700:         for (; k < len; k++) {
                    701:             if (k in t && t[k] === searchElement) {
                    702:                 return k;
                    703:             }
                    704:         }
                    705:         return -1;
                    706:     }
                    707: }
                    708: 
                    709: // ]]>
                    710: </script>
                    711: 
                    712: ENDJS
                    713: 
                    714: }
                    715: 
1.876     raeburn   716: sub userbrowser_javascript {
                    717:     my $id_functions = &javascript_index_functions();
                    718:     return <<"ENDUSERBRW";
                    719: 
1.888     raeburn   720: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   721:     var url = '/adm/pickuser?';
                    722:     var userdom = getDomainFromSelectbox(formname,udom);
                    723:     if (userdom != null) {
                    724:        if (userdom != '') {
                    725:            url += 'srchdom='+userdom+'&';
                    726:        }
                    727:     }
                    728:     url += 'form=' + formname + '&unameelement='+uname+
                    729:                                 '&udomelement='+udom+
                    730:                                 '&ulastelement='+ulast+
                    731:                                 '&ufirstelement='+ufirst+
                    732:                                 '&uemailelement='+uemail+
1.881     raeburn   733:                                 '&hideudomelement='+hideudom+
                    734:                                 '&coursedom='+crsdom;
1.888     raeburn   735:     if ((caller != null) && (caller != undefined)) {
                    736:         url += '&caller='+caller;
                    737:     }
1.876     raeburn   738:     var title = 'User_Browser';
                    739:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    740:     options += ',width=700,height=600';
                    741:     var stdeditbrowser = open(url,title,options,'1');
                    742:     stdeditbrowser.focus();
                    743: }
                    744: 
1.888     raeburn   745: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   746:     var formid = getFormIdByName(formname);
                    747:     if (formid > -1) {
1.888     raeburn   748:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   749:         var domid = getIndexByName(formid,udom);
                    750:         var hidedomid = getIndexByName(formid,origdom);
                    751:         if (hidedomid > -1) {
                    752:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   753:             var unameval = document.forms[formid].elements[unameid].value;
                    754:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    755:                 if (domid > -1) {
                    756:                     var slct = document.forms[formid].elements[domid];
                    757:                     if (slct.type == 'select-one') {
                    758:                         var i;
                    759:                         for (i=0;i<slct.length;i++) {
                    760:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    761:                         }
                    762:                     }
                    763:                     if (slct.type == 'hidden') {
                    764:                         slct.value = fixeddom;
1.876     raeburn   765:                     }
                    766:                 }
1.468     raeburn   767:             }
                    768:         }
                    769:     }
1.876     raeburn   770:     return;
                    771: }
                    772: 
                    773: $id_functions
                    774: ENDUSERBRW
1.468     raeburn   775: }
                    776: 
                    777: sub setsec_javascript {
1.1075.2.31  raeburn   778:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   779:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    780:         $communityrolestr);
                    781:     if ($role_element ne '') {
                    782:         my @allroles = ('st','ta','ep','in','ad');
                    783:         foreach my $crstype ('Course','Community') {
                    784:             if ($crstype eq 'Community') {
                    785:                 foreach my $role (@allroles) {
                    786:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    787:                 }
                    788:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    789:             } else {
                    790:                 foreach my $role (@allroles) {
                    791:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    792:                 }
                    793:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    794:             }
                    795:         }
                    796:         $rolestr = '"'.join('","',@allroles).'"';
                    797:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    798:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    799:     }
1.468     raeburn   800:     my $setsections = qq|
                    801: function setSect(sectionlist) {
1.629     raeburn   802:     var sectionsArray = new Array();
                    803:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    804:         sectionsArray = sectionlist.split(",");
                    805:     }
1.468     raeburn   806:     var numSections = sectionsArray.length;
                    807:     document.$formname.$sec_element.length = 0;
                    808:     if (numSections == 0) {
                    809:         document.$formname.$sec_element.multiple=false;
                    810:         document.$formname.$sec_element.size=1;
                    811:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    812:     } else {
                    813:         if (numSections == 1) {
                    814:             document.$formname.$sec_element.multiple=false;
                    815:             document.$formname.$sec_element.size=1;
                    816:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    817:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    818:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    819:         } else {
                    820:             for (var i=0; i<numSections; i++) {
                    821:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    822:             }
                    823:             document.$formname.$sec_element.multiple=true
                    824:             if (numSections < 3) {
                    825:                 document.$formname.$sec_element.size=numSections;
                    826:             } else {
                    827:                 document.$formname.$sec_element.size=3;
                    828:             }
                    829:             document.$formname.$sec_element.options[0].selected = false
                    830:         }
                    831:     }
1.91      www       832: }
1.905     raeburn   833: 
                    834: function setRole(crstype) {
1.468     raeburn   835: |;
1.905     raeburn   836:     if ($role_element eq '') {
                    837:         $setsections .= '    return;
                    838: }
                    839: ';
                    840:     } else {
                    841:         $setsections .= qq|
                    842:     var elementLength = document.$formname.$role_element.length;
                    843:     var allroles = Array($rolestr);
                    844:     var courserolenames = Array($courserolestr);
                    845:     var communityrolenames = Array($communityrolestr);
                    846:     if (elementLength != undefined) {
                    847:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    848:             if (crstype == 'Course') {
                    849:                 return;
                    850:             } else {
                    851:                 allroles[5] = 'co';
                    852:                 for (var i=0; i<6; i++) {
                    853:                     document.$formname.$role_element.options[i].value = allroles[i];
                    854:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    855:                 }
                    856:             }
                    857:         } else {
                    858:             if (crstype == 'Community') {
                    859:                 return;
                    860:             } else {
                    861:                 allroles[5] = 'cc';
                    862:                 for (var i=0; i<6; i++) {
                    863:                     document.$formname.$role_element.options[i].value = allroles[i];
                    864:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    865:                 }
                    866:             }
                    867:         }
                    868:     }
                    869:     return;
                    870: }
                    871: |;
                    872:     }
1.1075.2.31  raeburn   873:     if ($credits_element) {
                    874:         $setsections .= qq|
                    875: function setCredits(defaultcredits) {
                    876:     document.$formname.$credits_element.value = defaultcredits;
                    877:     return;
                    878: }
                    879: |;
                    880:     }
1.468     raeburn   881:     return $setsections;
                    882: }
                    883: 
1.91      www       884: sub selectcourse_link {
1.909     raeburn   885:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    886:        $typeelement) = @_;
                    887:    my $type = $selecttype;
1.871     raeburn   888:    my $linktext = &mt('Select Course');
                    889:    if ($selecttype eq 'Community') {
1.909     raeburn   890:        $linktext = &mt('Select Community');
1.906     raeburn   891:    } elsif ($selecttype eq 'Course/Community') {
                    892:        $linktext = &mt('Select Course/Community');
1.909     raeburn   893:        $type = '';
1.1019    raeburn   894:    } elsif ($selecttype eq 'Select') {
                    895:        $linktext = &mt('Select');
                    896:        $type = '';
1.871     raeburn   897:    }
1.787     bisitz    898:    return '<span class="LC_nobreak">'
                    899:          ."<a href='"
                    900:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    901:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   902:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   903:          ."'>".$linktext.'</a>'
1.787     bisitz    904:          .'</span>';
1.74      www       905: }
1.42      matthew   906: 
1.653     raeburn   907: sub selectauthor_link {
                    908:    my ($form,$udom)=@_;
                    909:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    910:           &mt('Select Author').'</a>';
                    911: }
                    912: 
1.876     raeburn   913: sub selectuser_link {
1.881     raeburn   914:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   915:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   916:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   917:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   918:            ');">'.$linktext.'</a>';
1.876     raeburn   919: }
                    920: 
1.273     raeburn   921: sub check_uncheck_jscript {
                    922:     my $jscript = <<"ENDSCRT";
                    923: function checkAll(field) {
                    924:     if (field.length > 0) {
                    925:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   926:             if (!field[i].disabled) {
                    927:                 field[i].checked = true;
                    928:             }
1.273     raeburn   929:         }
                    930:     } else {
1.1075.2.14  raeburn   931:         if (!field.disabled) {
                    932:             field.checked = true;
                    933:         }
1.273     raeburn   934:     }
                    935: }
                    936:  
                    937: function uncheckAll(field) {
                    938:     if (field.length > 0) {
                    939:         for (i = 0; i < field.length; i++) {
                    940:             field[i].checked = false ;
1.543     albertel  941:         }
                    942:     } else {
1.273     raeburn   943:         field.checked = false ;
                    944:     }
                    945: }
                    946: ENDSCRT
                    947:     return $jscript;
                    948: }
                    949: 
1.656     www       950: sub select_timezone {
1.1075.2.115  raeburn   951:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    952:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   953:    if ($includeempty) {
                    954:        $output .= '<option value=""';
                    955:        if (($selected eq '') || ($selected eq 'local')) {
                    956:            $output .= ' selected="selected" ';
                    957:        }
                    958:        $output .= '> </option>';
                    959:    }
1.657     raeburn   960:    my @timezones = DateTime::TimeZone->all_names;
                    961:    foreach my $tzone (@timezones) {
                    962:        $output.= '<option value="'.$tzone.'"';
                    963:        if ($tzone eq $selected) {
                    964:            $output.=' selected="selected"';
                    965:        }
                    966:        $output.=">$tzone</option>\n";
1.656     www       967:    }
                    968:    $output.="</select>";
                    969:    return $output;
                    970: }
1.273     raeburn   971: 
1.687     raeburn   972: sub select_datelocale {
1.1075.2.115  raeburn   973:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    974:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   975:     if ($includeempty) {
                    976:         $output .= '<option value=""';
                    977:         if ($selected eq '') {
                    978:             $output .= ' selected="selected" ';
                    979:         }
                    980:         $output .= '> </option>';
                    981:     }
1.1075.2.102  raeburn   982:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   983:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   984:     my @locales = DateTime::Locale->ids();
                    985:     foreach my $id (@locales) {
                    986:         if ($id ne '') {
                    987:             my ($en_terr,$native_terr);
                    988:             my $loc = DateTime::Locale->load($id);
                    989:             if (ref($loc)) {
                    990:                 $en_terr = $loc->name();
                    991:                 $native_terr = $loc->native_name();
1.687     raeburn   992:                 if (grep(/^en$/,@languages) || !@languages) {
                    993:                     if ($en_terr ne '') {
                    994:                         $locale_names{$id} = '('.$en_terr.')';
                    995:                     } elsif ($native_terr ne '') {
                    996:                         $locale_names{$id} = $native_terr;
                    997:                     }
                    998:                 } else {
                    999:                     if ($native_terr ne '') {
                   1000:                         $locale_names{$id} = $native_terr.' ';
                   1001:                     } elsif ($en_terr ne '') {
                   1002:                         $locale_names{$id} = '('.$en_terr.')';
                   1003:                     }
                   1004:                 }
1.1075.2.94  raeburn  1005:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1006:                 push(@possibles,$id);
1.687     raeburn  1007:             }
                   1008:         }
                   1009:     }
                   1010:     foreach my $item (sort(@possibles)) {
                   1011:         $output.= '<option value="'.$item.'"';
                   1012:         if ($item eq $selected) {
                   1013:             $output.=' selected="selected"';
                   1014:         }
                   1015:         $output.=">$item";
                   1016:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1017:             $output.='  '.$locale_names{$item};
1.687     raeburn  1018:         }
                   1019:         $output.="</option>\n";
                   1020:     }
                   1021:     $output.="</select>";
                   1022:     return $output;
                   1023: }
                   1024: 
1.792     raeburn  1025: sub select_language {
1.1075.2.115  raeburn  1026:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1027:     my %langchoices;
                   1028:     if ($includeempty) {
1.1075.2.32  raeburn  1029:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1030:     }
                   1031:     foreach my $id (&languageids()) {
                   1032:         my $code = &supportedlanguagecode($id);
                   1033:         if ($code) {
                   1034:             $langchoices{$code} = &plainlanguagedescription($id);
                   1035:         }
                   1036:     }
1.1075.2.32  raeburn  1037:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1038:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1039: }
                   1040: 
1.42      matthew  1041: =pod
1.36      matthew  1042: 
1.648     raeburn  1043: =item * &linked_select_forms(...)
1.36      matthew  1044: 
                   1045: linked_select_forms returns a string containing a <script></script> block
                   1046: and html for two <select> menus.  The select menus will be linked in that
                   1047: changing the value of the first menu will result in new values being placed
                   1048: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1049: order unless a defined order is provided.
1.36      matthew  1050: 
                   1051: linked_select_forms takes the following ordered inputs:
                   1052: 
                   1053: =over 4
                   1054: 
1.112     bowersj2 1055: =item * $formname, the name of the <form> tag
1.36      matthew  1056: 
1.112     bowersj2 1057: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1058: 
1.112     bowersj2 1059: =item * $firstdefault, the default value for the first menu
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1066: 
1.609     raeburn  1067: =item * $menuorder, the order of values in the first menu
                   1068: 
1.1075.2.31  raeburn  1069: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1070:         event for the first <select> tag
                   1071: 
                   1072: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1073:         event for the second <select> tag
                   1074: 
1.41      ng       1075: =back 
                   1076: 
1.36      matthew  1077: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1078: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1079: values for the first select menu.  The text that coincides with the 
1.41      ng       1080: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1081: and text for the second menu are given in the hash pointed to by 
                   1082: $menu{$choice1}->{'select2'}.  
                   1083: 
1.112     bowersj2 1084:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1085:                        default => "B3",
                   1086:                        select2 => { 
                   1087:                            B1 => "Choice B1",
                   1088:                            B2 => "Choice B2",
                   1089:                            B3 => "Choice B3",
                   1090:                            B4 => "Choice B4"
1.609     raeburn  1091:                            },
                   1092:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1093:                    },
                   1094:                A2 => { text =>"Choice A2" ,
                   1095:                        default => "C2",
                   1096:                        select2 => { 
                   1097:                            C1 => "Choice C1",
                   1098:                            C2 => "Choice C2",
                   1099:                            C3 => "Choice C3"
1.609     raeburn  1100:                            },
                   1101:                        order => ['C2','C1','C3'],
1.112     bowersj2 1102:                    },
                   1103:                A3 => { text =>"Choice A3" ,
                   1104:                        default => "D6",
                   1105:                        select2 => { 
                   1106:                            D1 => "Choice D1",
                   1107:                            D2 => "Choice D2",
                   1108:                            D3 => "Choice D3",
                   1109:                            D4 => "Choice D4",
                   1110:                            D5 => "Choice D5",
                   1111:                            D6 => "Choice D6",
                   1112:                            D7 => "Choice D7"
1.609     raeburn  1113:                            },
                   1114:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1115:                    }
                   1116:                );
1.36      matthew  1117: 
                   1118: =cut
                   1119: 
                   1120: sub linked_select_forms {
                   1121:     my ($formname,
                   1122:         $middletext,
                   1123:         $firstdefault,
                   1124:         $firstselectname,
                   1125:         $secondselectname, 
1.609     raeburn  1126:         $hashref,
                   1127:         $menuorder,
1.1075.2.31  raeburn  1128:         $onchangefirst,
                   1129:         $onchangesecond
1.36      matthew  1130:         ) = @_;
                   1131:     my $second = "document.$formname.$secondselectname";
                   1132:     my $first = "document.$formname.$firstselectname";
                   1133:     # output the javascript to do the changing
                   1134:     my $result = '';
1.776     bisitz   1135:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1136:     $result.="// <![CDATA[\n";
1.36      matthew  1137:     $result.="var select2data = new Object();\n";
                   1138:     $" = '","';
                   1139:     my $debug = '';
                   1140:     foreach my $s1 (sort(keys(%$hashref))) {
                   1141:         $result.="select2data.d_$s1 = new Object();\n";        
                   1142:         $result.="select2data.d_$s1.def = new String('".
                   1143:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1144:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1145:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1146:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1147:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1148:         }
1.36      matthew  1149:         $result.="\"@s2values\");\n";
                   1150:         $result.="select2data.d_$s1.texts = new Array(";        
                   1151:         my @s2texts;
                   1152:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1153:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1154:         }
                   1155:         $result.="\"@s2texts\");\n";
                   1156:     }
                   1157:     $"=' ';
                   1158:     $result.= <<"END";
                   1159: 
                   1160: function select1_changed() {
                   1161:     // Determine new choice
                   1162:     var newvalue = "d_" + $first.value;
                   1163:     // update select2
                   1164:     var values     = select2data[newvalue].values;
                   1165:     var texts      = select2data[newvalue].texts;
                   1166:     var select2def = select2data[newvalue].def;
                   1167:     var i;
                   1168:     // out with the old
                   1169:     for (i = 0; i < $second.options.length; i++) {
                   1170:         $second.options[i] = null;
                   1171:     }
                   1172:     // in with the nuclear
                   1173:     for (i=0;i<values.length; i++) {
                   1174:         $second.options[i] = new Option(values[i]);
1.143     matthew  1175:         $second.options[i].value = values[i];
1.36      matthew  1176:         $second.options[i].text = texts[i];
                   1177:         if (values[i] == select2def) {
                   1178:             $second.options[i].selected = true;
                   1179:         }
                   1180:     }
                   1181: }
1.824     bisitz   1182: // ]]>
1.36      matthew  1183: </script>
                   1184: END
                   1185:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1186:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1187:     my @order = sort(keys(%{$hashref}));
                   1188:     if (ref($menuorder) eq 'ARRAY') {
                   1189:         @order = @{$menuorder};
                   1190:     }
                   1191:     foreach my $value (@order) {
1.36      matthew  1192:         $result.="    <option value=\"$value\" ";
1.253     albertel 1193:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1194:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1195:     }
                   1196:     $result .= "</select>\n";
                   1197:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1198:     $result .= $middletext;
1.1075.2.31  raeburn  1199:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1200:     if ($onchangesecond) {
                   1201:         $result .= ' onchange="'.$onchangesecond.'"';
                   1202:     }
                   1203:     $result .= ">\n";
1.36      matthew  1204:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1205:     
                   1206:     my @secondorder = sort(keys(%select2));
                   1207:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1208:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1209:     }
                   1210:     foreach my $value (@secondorder) {
1.36      matthew  1211:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1212:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1213:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1214:     }
                   1215:     $result .= "</select>\n";
                   1216:     #    return $debug;
                   1217:     return $result;
                   1218: }   #  end of sub linked_select_forms {
                   1219: 
1.45      matthew  1220: =pod
1.44      bowersj2 1221: 
1.973     raeburn  1222: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1223: 
1.112     bowersj2 1224: Returns a string corresponding to an HTML link to the given help
                   1225: $topic, where $topic corresponds to the name of a .tex file in
                   1226: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1227: spaces. 
                   1228: 
                   1229: $text will optionally be linked to the same topic, allowing you to
                   1230: link text in addition to the graphic. If you do not want to link
                   1231: text, but wish to specify one of the later parameters, pass an
                   1232: empty string. 
                   1233: 
                   1234: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1235: the link will not open a new window. If false, the link will open
                   1236: a new window using Javascript. (Default is false.) 
                   1237: 
                   1238: $width and $height are optional numerical parameters that will
                   1239: override the width and height of the popped up window, which may
1.973     raeburn  1240: be useful for certain help topics with big pictures included.
                   1241: 
                   1242: $imgid is the id of the img tag used for the help icon. This may be
                   1243: used in a javascript call to switch the image src.  See 
                   1244: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1245: 
                   1246: =cut
                   1247: 
                   1248: sub help_open_topic {
1.973     raeburn  1249:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1250:     $text = "" if (not defined $text);
1.44      bowersj2 1251:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1252:     $width = 500 if (not defined $width);
1.44      bowersj2 1253:     $height = 400 if (not defined $height);
                   1254:     my $filename = $topic;
                   1255:     $filename =~ s/ /_/g;
                   1256: 
1.48      bowersj2 1257:     my $template = "";
                   1258:     my $link;
1.572     banghart 1259:     
1.159     www      1260:     $topic=~s/\W/\_/g;
1.44      bowersj2 1261: 
1.572     banghart 1262:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1263:         if ($env{'browser.mobile'}) {
                   1264: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1265:         } else {
                   1266:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1267:         }
1.1037    www      1268:     } elsif ($stayOnPage eq 'popup') {
                   1269:         $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 1270:     } else {
1.48      bowersj2 1271: 	$link = "/adm/help/${filename}.hlp";
                   1272:     }
                   1273: 
                   1274:     # Add the text
1.755     neumanie 1275:     if ($text ne "") {	
1.763     bisitz   1276: 	$template.='<span class="LC_help_open_topic">'
                   1277:                   .'<a target="_top" href="'.$link.'">'
                   1278:                   .$text.'</a>';
1.48      bowersj2 1279:     }
                   1280: 
1.763     bisitz   1281:     # (Always) Add the graphic
1.179     matthew  1282:     my $title = &mt('Online Help');
1.667     raeburn  1283:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1284:     if ($imgid ne '') {
                   1285:         $imgid = ' id="'.$imgid.'"';
                   1286:     }
1.763     bisitz   1287:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1288:               .'<img src="'.$helpicon.'" border="0"'
                   1289:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1290:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1291:               .' /></a>';
                   1292:     if ($text ne "") {	
                   1293:         $template.='</span>';
                   1294:     }
1.44      bowersj2 1295:     return $template;
                   1296: 
1.106     bowersj2 1297: }
                   1298: 
                   1299: # This is a quicky function for Latex cheatsheet editing, since it 
                   1300: # appears in at least four places
                   1301: sub helpLatexCheatsheet {
1.1037    www      1302:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1303:     my $out;
1.106     bowersj2 1304:     my $addOther = '';
1.732     raeburn  1305:     if ($topic) {
1.1037    www      1306: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1307:     }
                   1308:     $out = '<span>' # Start cheatsheet
                   1309: 	  .$addOther
                   1310:           .'<span>'
1.1037    www      1311: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1312: 	  .'</span> <span>'
1.1037    www      1313: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span>';
1.732     raeburn  1315:     unless ($not_author) {
1.763     bisitz   1316:         $out .= ' <span>'
1.1037    www      1317: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1318: 	       .'</span> <span>'
1.1075.2.78  raeburn  1319:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1320:                .'</span>';
1.732     raeburn  1321:     }
1.763     bisitz   1322:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1323:     return $out;
1.172     www      1324: }
                   1325: 
1.430     albertel 1326: sub general_help {
                   1327:     my $helptopic='Student_Intro';
                   1328:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1329: 	$helptopic='Authoring_Intro';
1.907     raeburn  1330:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1331: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1332:     } elsif ($env{'request.role'}=~/^dc/) {
                   1333:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1334:     }
                   1335:     return $helptopic;
                   1336: }
                   1337: 
                   1338: sub update_help_link {
                   1339:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1340:     my $origurl = $ENV{'REQUEST_URI'};
                   1341:     $origurl=~s|^/~|/priv/|;
                   1342:     my $timestamp = time;
                   1343:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1344:         $$datum = &escape($$datum);
                   1345:     }
                   1346: 
                   1347:     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";
                   1348:     my $output .= <<"ENDOUTPUT";
                   1349: <script type="text/javascript">
1.824     bisitz   1350: // <![CDATA[
1.430     albertel 1351: banner_link = '$banner_link';
1.824     bisitz   1352: // ]]>
1.430     albertel 1353: </script>
                   1354: ENDOUTPUT
                   1355:     return $output;
                   1356: }
                   1357: 
                   1358: # now just updates the help link and generates a blue icon
1.193     raeburn  1359: sub help_open_menu {
1.430     albertel 1360:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1361: 	= @_;    
1.949     droeschl 1362:     $stayOnPage = 1;
1.430     albertel 1363:     my $output;
                   1364:     if ($component_help) {
                   1365: 	if (!$text) {
                   1366: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1367: 				       $width,$height);
                   1368: 	} else {
                   1369: 	    my $help_text;
                   1370: 	    $help_text=&unescape($topic);
                   1371: 	    $output='<table><tr><td>'.
                   1372: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1373: 				 $width,$height).'</td></tr></table>';
                   1374: 	}
                   1375:     }
                   1376:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1377:     return $output.$banner_link;
                   1378: }
                   1379: 
                   1380: sub top_nav_help {
                   1381:     my ($text) = @_;
1.436     albertel 1382:     $text = &mt($text);
1.1075.2.60  raeburn  1383:     my $stay_on_page;
                   1384:     unless ($env{'environment.remote'} eq 'on') {
                   1385:         $stay_on_page = 1;
                   1386:     }
1.1075.2.61  raeburn  1387:     my ($link,$banner_link);
                   1388:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1389:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1390: 	                         : "javascript:helpMenu('open')";
                   1391:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1392:     }
1.201     raeburn  1393:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1394:     if ($link) {
                   1395:         return <<"END";
1.436     albertel 1396: $banner_link
1.1075.2.56  raeburn  1397: <a href="$link" title="$title">$text</a>
1.436     albertel 1398: END
1.1075.2.61  raeburn  1399:     } else {
                   1400:         return '&nbsp;'.$text.'&nbsp;';
                   1401:     }
1.436     albertel 1402: }
                   1403: 
                   1404: sub help_menu_js {
1.1075.2.52  raeburn  1405:     my ($httphost) = @_;
1.949     droeschl 1406:     my $stayOnPage = 1;
1.436     albertel 1407:     my $width = 620;
                   1408:     my $height = 600;
1.430     albertel 1409:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1410:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1411:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1412:     my $start_page =
                   1413:         &Apache::loncommon::start_page('Help Menu', undef,
                   1414: 				       {'frameset'    => 1,
                   1415: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1416:                                         'use_absolute' => $httphost,
1.331     albertel 1417: 					'add_entries' => {
                   1418: 					    'border' => '0',
1.579     raeburn  1419: 					    'rows'   => "110,*",},});
1.331     albertel 1420:     my $end_page =
                   1421:         &Apache::loncommon::end_page({'frameset' => 1,
                   1422: 				      'js_ready' => 1,});
                   1423: 
1.436     albertel 1424:     my $template .= <<"ENDTEMPLATE";
                   1425: <script type="text/javascript">
1.877     bisitz   1426: // <![CDATA[
1.253     albertel 1427: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1428: var banner_link = '';
1.243     raeburn  1429: function helpMenu(target) {
                   1430:     var caller = this;
                   1431:     if (target == 'open') {
                   1432:         var newWindow = null;
                   1433:         try {
1.262     albertel 1434:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1435:         }
                   1436:         catch(error) {
                   1437:             writeHelp(caller);
                   1438:             return;
                   1439:         }
                   1440:         if (newWindow) {
                   1441:             caller = newWindow;
                   1442:         }
1.193     raeburn  1443:     }
1.243     raeburn  1444:     writeHelp(caller);
                   1445:     return;
                   1446: }
                   1447: function writeHelp(caller) {
1.1075.2.61  raeburn  1448:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1449:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1450:     caller.document.close();
                   1451:     caller.focus();
1.193     raeburn  1452: }
1.877     bisitz   1453: // END LON-CAPA Internal -->
1.253     albertel 1454: // ]]>
1.436     albertel 1455: </script>
1.193     raeburn  1456: ENDTEMPLATE
                   1457:     return $template;
                   1458: }
                   1459: 
1.172     www      1460: sub help_open_bug {
                   1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1462:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1463:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1464:     $text = "" if (not defined $text);
                   1465: 	$stayOnPage=1;
1.184     albertel 1466:     $width = 600 if (not defined $width);
                   1467:     $height = 600 if (not defined $height);
1.172     www      1468: 
                   1469:     $topic=~s/\W+/\+/g;
                   1470:     my $link='';
                   1471:     my $template='';
1.379     albertel 1472:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1473: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1474:     if (!$stayOnPage)
                   1475:     {
                   1476: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1477:     }
                   1478:     else
                   1479:     {
                   1480: 	$link = $url;
                   1481:     }
                   1482:     # Add the text
                   1483:     if ($text ne "")
                   1484:     {
                   1485: 	$template .= 
                   1486:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1487:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1488:     }
                   1489: 
                   1490:     # Add the graphic
1.179     matthew  1491:     my $title = &mt('Report a Bug');
1.215     albertel 1492:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1493:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1494:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1495: ENDTEMPLATE
                   1496:     if ($text ne '') { $template.='</td></tr></table>' };
                   1497:     return $template;
                   1498: 
                   1499: }
                   1500: 
                   1501: sub help_open_faq {
                   1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1503:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1504:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1505:     $text = "" if (not defined $text);
                   1506: 	$stayOnPage=1;
                   1507:     $width = 350 if (not defined $width);
                   1508:     $height = 400 if (not defined $height);
                   1509: 
                   1510:     $topic=~s/\W+/\+/g;
                   1511:     my $link='';
                   1512:     my $template='';
                   1513:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1514:     if (!$stayOnPage)
                   1515:     {
                   1516: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1517:     }
                   1518:     else
                   1519:     {
                   1520: 	$link = $url;
                   1521:     }
                   1522: 
                   1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
1.173     www      1527:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1528:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('View the FAQ');
1.215     albertel 1533:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1535:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
1.44      bowersj2 1540: }
1.37      matthew  1541: 
1.180     matthew  1542: ###############################################################
                   1543: ###############################################################
                   1544: 
1.45      matthew  1545: =pod
                   1546: 
1.648     raeburn  1547: =item * &change_content_javascript():
1.256     matthew  1548: 
                   1549: This and the next function allow you to create small sections of an
                   1550: otherwise static HTML page that you can update on the fly with
                   1551: Javascript, even in Netscape 4.
                   1552: 
                   1553: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1554: must be written to the HTML page once. It will prove the Javascript
                   1555: function "change(name, content)". Calling the change function with the
                   1556: name of the section 
                   1557: you want to update, matching the name passed to C<changable_area>, and
                   1558: the new content you want to put in there, will put the content into
                   1559: that area.
                   1560: 
                   1561: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1562: to contain room for the original contents. You need to "make space"
                   1563: for whatever changes you wish to make, and be B<sure> to check your
                   1564: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1565: it's adequate for updating a one-line status display, but little more.
                   1566: This script will set the space to 100% width, so you only need to
                   1567: worry about height in Netscape 4.
                   1568: 
                   1569: Modern browsers are much less limiting, and if you can commit to the
                   1570: user not using Netscape 4, this feature may be used freely with
                   1571: pretty much any HTML.
                   1572: 
                   1573: =cut
                   1574: 
                   1575: sub change_content_javascript {
                   1576:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1577:     if ($env{'browser.type'} eq 'netscape' &&
                   1578: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1579: 	return (<<NETSCAPE4);
                   1580: 	function change(name, content) {
                   1581: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1582: 	    doc.open();
                   1583: 	    doc.write(content);
                   1584: 	    doc.close();
                   1585: 	}
                   1586: NETSCAPE4
                   1587:     } else {
                   1588: 	# Otherwise, we need to use semi-standards-compliant code
                   1589: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1590: 	# is really scary, and every useful browser supports it
                   1591: 	return (<<DOMBASED);
                   1592: 	function change(name, content) {
                   1593: 	    element = document.getElementById(name);
                   1594: 	    element.innerHTML = content;
                   1595: 	}
                   1596: DOMBASED
                   1597:     }
                   1598: }
                   1599: 
                   1600: =pod
                   1601: 
1.648     raeburn  1602: =item * &changable_area($name,$origContent):
1.256     matthew  1603: 
                   1604: This provides a "changable area" that can be modified on the fly via
                   1605: the Javascript code provided in C<change_content_javascript>. $name is
                   1606: the name you will use to reference the area later; do not repeat the
                   1607: same name on a given HTML page more then once. $origContent is what
                   1608: the area will originally contain, which can be left blank.
                   1609: 
                   1610: =cut
                   1611: 
                   1612: sub changable_area {
                   1613:     my ($name, $origContent) = @_;
                   1614: 
1.258     albertel 1615:     if ($env{'browser.type'} eq 'netscape' &&
                   1616: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1617: 	# If this is netscape 4, we need to use the Layer tag
                   1618: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1619:     } else {
                   1620: 	return "<span id='$name'>$origContent</span>";
                   1621:     }
                   1622: }
                   1623: 
                   1624: =pod
                   1625: 
1.648     raeburn  1626: =item * &viewport_geometry_js 
1.590     raeburn  1627: 
                   1628: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1629: 
                   1630: =cut
                   1631: 
                   1632: 
                   1633: sub viewport_geometry_js { 
                   1634:     return <<"GEOMETRY";
                   1635: var Geometry = {};
                   1636: function init_geometry() {
                   1637:     if (Geometry.init) { return };
                   1638:     Geometry.init=1;
                   1639:     if (window.innerHeight) {
                   1640:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1641:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1642:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1643:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1644:     }
                   1645:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1646:         Geometry.getViewportHeight =
                   1647:             function() { return document.documentElement.clientHeight; };
                   1648:         Geometry.getViewportWidth =
                   1649:             function() { return document.documentElement.clientWidth; };
                   1650: 
                   1651:         Geometry.getHorizontalScroll =
                   1652:             function() { return document.documentElement.scrollLeft; };
                   1653:         Geometry.getVerticalScroll =
                   1654:             function() { return document.documentElement.scrollTop; };
                   1655:     }
                   1656:     else if (document.body.clientHeight) {
                   1657:         Geometry.getViewportHeight =
                   1658:             function() { return document.body.clientHeight; };
                   1659:         Geometry.getViewportWidth =
                   1660:             function() { return document.body.clientWidth; };
                   1661:         Geometry.getHorizontalScroll =
                   1662:             function() { return document.body.scrollLeft; };
                   1663:         Geometry.getVerticalScroll =
                   1664:             function() { return document.body.scrollTop; };
                   1665:     }
                   1666: }
                   1667: 
                   1668: GEOMETRY
                   1669: }
                   1670: 
                   1671: =pod
                   1672: 
1.648     raeburn  1673: =item * &viewport_size_js()
1.590     raeburn  1674: 
                   1675: 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. 
                   1676: 
                   1677: =cut
                   1678: 
                   1679: sub viewport_size_js {
                   1680:     my $geometry = &viewport_geometry_js();
                   1681:     return <<"DIMS";
                   1682: 
                   1683: $geometry
                   1684: 
                   1685: function getViewportDims(width,height) {
                   1686:     init_geometry();
                   1687:     width.value = Geometry.getViewportWidth();
                   1688:     height.value = Geometry.getViewportHeight();
                   1689:     return;
                   1690: }
                   1691: 
                   1692: DIMS
                   1693: }
                   1694: 
                   1695: =pod
                   1696: 
1.648     raeburn  1697: =item * &resize_textarea_js()
1.565     albertel 1698: 
                   1699: emits the needed javascript to resize a textarea to be as big as possible
                   1700: 
                   1701: creates a function resize_textrea that takes two IDs first should be
                   1702: the id of the element to resize, second should be the id of a div that
                   1703: surrounds everything that comes after the textarea, this routine needs
                   1704: to be attached to the <body> for the onload and onresize events.
                   1705: 
1.648     raeburn  1706: =back
1.565     albertel 1707: 
                   1708: =cut
                   1709: 
                   1710: sub resize_textarea_js {
1.590     raeburn  1711:     my $geometry = &viewport_geometry_js();
1.565     albertel 1712:     return <<"RESIZE";
                   1713:     <script type="text/javascript">
1.824     bisitz   1714: // <![CDATA[
1.590     raeburn  1715: $geometry
1.565     albertel 1716: 
1.588     albertel 1717: function getX(element) {
                   1718:     var x = 0;
                   1719:     while (element) {
                   1720: 	x += element.offsetLeft;
                   1721: 	element = element.offsetParent;
                   1722:     }
                   1723:     return x;
                   1724: }
                   1725: function getY(element) {
                   1726:     var y = 0;
                   1727:     while (element) {
                   1728: 	y += element.offsetTop;
                   1729: 	element = element.offsetParent;
                   1730:     }
                   1731:     return y;
                   1732: }
                   1733: 
                   1734: 
1.565     albertel 1735: function resize_textarea(textarea_id,bottom_id) {
                   1736:     init_geometry();
                   1737:     var textarea        = document.getElementById(textarea_id);
                   1738:     //alert(textarea);
                   1739: 
1.588     albertel 1740:     var textarea_top    = getY(textarea);
1.565     albertel 1741:     var textarea_height = textarea.offsetHeight;
                   1742:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1743:     var bottom_top      = getY(bottom);
1.565     albertel 1744:     var bottom_height   = bottom.offsetHeight;
                   1745:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1746:     var fudge           = 23;
1.565     albertel 1747:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1748:     if (new_height < 300) {
                   1749: 	new_height = 300;
                   1750:     }
                   1751:     textarea.style.height=new_height+'px';
                   1752: }
1.824     bisitz   1753: // ]]>
1.565     albertel 1754: </script>
                   1755: RESIZE
                   1756: 
                   1757: }
                   1758: 
1.1075.2.112  raeburn  1759: sub colorfuleditor_js {
                   1760:     return <<"COLORFULEDIT"
                   1761: <script type="text/javascript">
                   1762: // <![CDATA[>
                   1763:     function fold_box(curDepth, lastresource){
                   1764: 
                   1765:     // we need a list because there can be several blocks you need to fold in one tag
                   1766:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1767:     // but there is only one folding button per tag
                   1768:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1769: 
                   1770:         if(block.item(0).style.display == 'none'){
                   1771: 
                   1772:             foldbutton.value = '@{[&mt("Hide")]}';
                   1773:             for (i = 0; i < block.length; i++){
                   1774:                 block.item(i).style.display = '';
                   1775:             }
                   1776:         }else{
                   1777: 
                   1778:             foldbutton.value = '@{[&mt("Show")]}';
                   1779:             for (i = 0; i < block.length; i++){
                   1780:                 // block.item(i).style.visibility = 'collapse';
                   1781:                 block.item(i).style.display = 'none';
                   1782:             }
                   1783:         };
                   1784:         saveState(lastresource);
                   1785:     }
                   1786: 
                   1787:     function saveState (lastresource) {
                   1788: 
                   1789:         var tag_list = getTagList();
                   1790:         if(tag_list != null){
                   1791:             var timestamp = new Date().getTime();
                   1792:             var key = lastresource;
                   1793: 
                   1794:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1795:             // starting with timestamp
                   1796:             var value = timestamp+';';
                   1797: 
                   1798:             // building the list of key-value pairs
                   1799:             for(var i = 0; i < tag_list.length; i++){
                   1800:                 value += tag_list[i]+',';
                   1801:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1802:             }
                   1803: 
                   1804:             // only iterate whole storage if nothing to override
                   1805:             if(localStorage.getItem(key) == null){
                   1806: 
                   1807:                 // prevent storage from growing large
                   1808:                 if(localStorage.length > 50){
                   1809:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1810:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1811:                     var oldest_key;
                   1812: 
                   1813:                     for(var i = 1; i < localStorage.length; i++){
                   1814:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1815:                             oldest_key = localStorage.key(i);
                   1816:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1817:                         }
                   1818:                     }
                   1819:                     localStorage.removeItem(oldest_key);
                   1820:                 }
                   1821:             }
                   1822:             localStorage.setItem(key,value);
                   1823:         }
                   1824:     }
                   1825: 
                   1826:     // restore folding status of blocks (on page load)
                   1827:     function restoreState (lastresource) {
                   1828:         if(localStorage.getItem(lastresource) != null){
                   1829:             var key = lastresource;
                   1830:             var value = localStorage.getItem(key);
                   1831:             var regex_delTimestamp = /^\d+;/;
                   1832: 
                   1833:             value.replace(regex_delTimestamp, '');
                   1834: 
                   1835:             var valueArr = value.split(';');
                   1836:             var pairs;
                   1837:             var elements;
                   1838:             for (var i = 0; i < valueArr.length; i++){
                   1839:                 pairs = valueArr[i].split(',');
                   1840:                 elements = document.getElementsByName(pairs[0]);
                   1841: 
                   1842:                 for (var j = 0; j < elements.length; j++){
                   1843:                     elements[j].style.display = pairs[1];
                   1844:                     if (pairs[1] == "none"){
                   1845:                         var regex_id = /([_\\d]+)\$/;
                   1846:                         regex_id.exec(pairs[0]);
                   1847:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1848:                     }
                   1849:                 }
                   1850:             }
                   1851:         }
                   1852:     }
                   1853: 
                   1854:     function getTagList () {
                   1855: 
                   1856:         var stringToSearch = document.lonhomework.innerHTML;
                   1857: 
                   1858:         var ret = new Array();
                   1859:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1860:         var tag_list = stringToSearch.match(regex_findBlock);
                   1861: 
                   1862:         if(tag_list != null){
                   1863:             for(var i = 0; i < tag_list.length; i++){
                   1864:                 ret.push(tag_list[i].replace(/"/, ''));
                   1865:             }
                   1866:         }
                   1867:         return ret;
                   1868:     }
                   1869: 
                   1870:     function saveScrollPosition (resource) {
                   1871:         var tag_list = getTagList();
                   1872: 
                   1873:         // we dont always want to jump to the first block
                   1874:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1875:         if(\$(window).scrollTop() > 170){
                   1876:             if(tag_list != null){
                   1877:                 var result;
                   1878:                 for(var i = 0; i < tag_list.length; i++){
                   1879:                     if(isElementInViewport(tag_list[i])){
                   1880:                         result += tag_list[i]+';';
                   1881:                     }
                   1882:                 }
                   1883:                 sessionStorage.setItem('anchor_'+resource, result);
                   1884:             }
                   1885:         } else {
                   1886:             // we dont need to save zero, just delete the item to leave everything tidy
                   1887:             sessionStorage.removeItem('anchor_'+resource);
                   1888:         }
                   1889:     }
                   1890: 
                   1891:     function restoreScrollPosition(resource){
                   1892: 
                   1893:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1894:         if(elem != null){
                   1895:             var tag_list = elem.split(';');
                   1896:             var elem_list;
                   1897: 
                   1898:             for(var i = 0; i < tag_list.length; i++){
                   1899:                 elem_list = document.getElementsByName(tag_list[i]);
                   1900: 
                   1901:                 if(elem_list.length > 0){
                   1902:                     elem = elem_list[0];
                   1903:                     break;
                   1904:                 }
                   1905:             }
                   1906:             elem.scrollIntoView();
                   1907:         }
                   1908:     }
                   1909: 
                   1910:     function isElementInViewport(el) {
                   1911: 
                   1912:         // change to last element instead of first
                   1913:         var elem = document.getElementsByName(el);
                   1914:         var rect = elem[0].getBoundingClientRect();
                   1915: 
                   1916:         return (
                   1917:             rect.top >= 0 &&
                   1918:             rect.left >= 0 &&
                   1919:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1920:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1921:         );
                   1922:     }
                   1923: 
                   1924:     function autosize(depth){
                   1925:         var cmInst = window['cm'+depth];
                   1926:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1927: 
                   1928:         // is fixed size, switching to dynamic
                   1929:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1930:             cmInst.setSize("","auto");
                   1931:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1932:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1933: 
                   1934:         // is dynamic size, switching to fixed
                   1935:         } else {
                   1936:             cmInst.setSize("","300px");
                   1937:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1938:             sessionStorage.removeItem("autosized_"+depth);
                   1939:         }
                   1940:     }
                   1941: 
                   1942: 
                   1943: 
                   1944: // ]]>
                   1945: </script>
                   1946: COLORFULEDIT
                   1947: }
                   1948: 
                   1949: sub xmleditor_js {
                   1950:     return <<XMLEDIT
                   1951: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1952: <script type="text/javascript">
                   1953: // <![CDATA[>
                   1954: 
                   1955:     function saveScrollPosition (resource) {
                   1956: 
                   1957:         var scrollPos = \$(window).scrollTop();
                   1958:         sessionStorage.setItem(resource,scrollPos);
                   1959:     }
                   1960: 
                   1961:     function restoreScrollPosition(resource){
                   1962: 
                   1963:         var scrollPos = sessionStorage.getItem(resource);
                   1964:         \$(window).scrollTop(scrollPos);
                   1965:     }
                   1966: 
                   1967:     // unless internet explorer
                   1968:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1969: 
                   1970:         \$(document).ready(function() {
                   1971:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1972:         });
                   1973:     }
                   1974: 
                   1975:     // inserts text at cursor position into codemirror (xml editor only)
                   1976:     function insertText(text){
                   1977:         cm.focus();
                   1978:         var curPos = cm.getCursor();
                   1979:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1980:     }
                   1981: // ]]>
                   1982: </script>
                   1983: XMLEDIT
                   1984: }
                   1985: 
                   1986: sub insert_folding_button {
                   1987:     my $curDepth = $Apache::lonxml::curdepth;
                   1988:     my $lastresource = $env{'request.ambiguous'};
                   1989: 
                   1990:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1991:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1992: }
                   1993: 
                   1994: 
1.565     albertel 1995: =pod
                   1996: 
1.256     matthew  1997: =head1 Excel and CSV file utility routines
                   1998: 
                   1999: =cut
                   2000: 
                   2001: ###############################################################
                   2002: ###############################################################
                   2003: 
                   2004: =pod
                   2005: 
1.1075.2.56  raeburn  2006: =over 4
                   2007: 
1.648     raeburn  2008: =item * &csv_translate($text) 
1.37      matthew  2009: 
1.185     www      2010: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2011: format.
                   2012: 
                   2013: =cut
                   2014: 
1.180     matthew  2015: ###############################################################
                   2016: ###############################################################
1.37      matthew  2017: sub csv_translate {
                   2018:     my $text = shift;
                   2019:     $text =~ s/\"/\"\"/g;
1.209     albertel 2020:     $text =~ s/\n/ /g;
1.37      matthew  2021:     return $text;
                   2022: }
1.180     matthew  2023: 
                   2024: ###############################################################
                   2025: ###############################################################
                   2026: 
                   2027: =pod
                   2028: 
1.648     raeburn  2029: =item * &define_excel_formats()
1.180     matthew  2030: 
                   2031: Define some commonly used Excel cell formats.
                   2032: 
                   2033: Currently supported formats:
                   2034: 
                   2035: =over 4
                   2036: 
                   2037: =item header
                   2038: 
                   2039: =item bold
                   2040: 
                   2041: =item h1
                   2042: 
                   2043: =item h2
                   2044: 
                   2045: =item h3
                   2046: 
1.256     matthew  2047: =item h4
                   2048: 
                   2049: =item i
                   2050: 
1.180     matthew  2051: =item date
                   2052: 
                   2053: =back
                   2054: 
                   2055: Inputs: $workbook
                   2056: 
                   2057: Returns: $format, a hash reference.
                   2058: 
1.1057    foxr     2059: 
1.180     matthew  2060: =cut
                   2061: 
                   2062: ###############################################################
                   2063: ###############################################################
                   2064: sub define_excel_formats {
                   2065:     my ($workbook) = @_;
                   2066:     my $format;
                   2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2068:                                                 bottom    => 1,
                   2069:                                                 align     => 'center');
                   2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2076:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2077:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2078:     return $format;
                   2079: }
                   2080: 
                   2081: ###############################################################
                   2082: ###############################################################
1.113     bowersj2 2083: 
                   2084: =pod
                   2085: 
1.648     raeburn  2086: =item * &create_workbook()
1.255     matthew  2087: 
                   2088: Create an Excel worksheet.  If it fails, output message on the
                   2089: request object and return undefs.
                   2090: 
                   2091: Inputs: Apache request object
                   2092: 
                   2093: Returns (undef) on failure, 
                   2094:     Excel worksheet object, scalar with filename, and formats 
                   2095:     from &Apache::loncommon::define_excel_formats on success
                   2096: 
                   2097: =cut
                   2098: 
                   2099: ###############################################################
                   2100: ###############################################################
                   2101: sub create_workbook {
                   2102:     my ($r) = @_;
                   2103:         #
                   2104:     # Create the excel spreadsheet
                   2105:     my $filename = '/prtspool/'.
1.258     albertel 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2107:         time.'_'.rand(1000000000).'.xls';
                   2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2109:     if (! defined($workbook)) {
                   2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2111:         $r->print(
                   2112:             '<p class="LC_error">'
                   2113:            .&mt('Problems occurred in creating the new Excel file.')
                   2114:            .' '.&mt('This error has been logged.')
                   2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2116:            .'</p>'
                   2117:         );
1.255     matthew  2118:         return (undef);
                   2119:     }
                   2120:     #
1.1014    foxr     2121:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2122:     #
                   2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2124:     return ($workbook,$filename,$format);
                   2125: }
                   2126: 
                   2127: ###############################################################
                   2128: ###############################################################
                   2129: 
                   2130: =pod
                   2131: 
1.648     raeburn  2132: =item * &create_text_file()
1.113     bowersj2 2133: 
1.542     raeburn  2134: Create a file to write to and eventually make available to the user.
1.256     matthew  2135: If file creation fails, outputs an error message on the request object and 
                   2136: return undefs.
1.113     bowersj2 2137: 
1.256     matthew  2138: Inputs: Apache request object, and file suffix
1.113     bowersj2 2139: 
1.256     matthew  2140: Returns (undef) on failure, 
                   2141:     Filehandle and filename on success.
1.113     bowersj2 2142: 
                   2143: =cut
                   2144: 
1.256     matthew  2145: ###############################################################
                   2146: ###############################################################
                   2147: sub create_text_file {
                   2148:     my ($r,$suffix) = @_;
                   2149:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2150:     my $fh;
                   2151:     my $filename = '/prtspool/'.
1.258     albertel 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2153:         time.'_'.rand(1000000000).'.'.$suffix;
                   2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2155:     if (! defined($fh)) {
                   2156:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2157:         $r->print(
                   2158:             '<p class="LC_error">'
                   2159:            .&mt('Problems occurred in creating the output file.')
                   2160:            .' '.&mt('This error has been logged.')
                   2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2162:            .'</p>'
                   2163:         );
1.113     bowersj2 2164:     }
1.256     matthew  2165:     return ($fh,$filename)
1.113     bowersj2 2166: }
                   2167: 
                   2168: 
1.256     matthew  2169: =pod 
1.113     bowersj2 2170: 
                   2171: =back
                   2172: 
                   2173: =cut
1.37      matthew  2174: 
                   2175: ###############################################################
1.33      matthew  2176: ##        Home server <option> list generating code          ##
                   2177: ###############################################################
1.35      matthew  2178: 
1.169     www      2179: # ------------------------------------------
                   2180: 
                   2181: sub domain_select {
                   2182:     my ($name,$value,$multiple)=@_;
                   2183:     my %domains=map { 
1.514     albertel 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2185:     } &Apache::lonnet::all_domains();
1.169     www      2186:     if ($multiple) {
                   2187: 	$domains{''}=&mt('Any domain');
1.550     albertel 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2189: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2190:     } else {
1.550     albertel 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2192: 	return &select_form($name,$value,\%domains);
1.169     www      2193:     }
                   2194: }
                   2195: 
1.282     albertel 2196: #-------------------------------------------
                   2197: 
                   2198: =pod
                   2199: 
1.519     raeburn  2200: =head1 Routines for form select boxes
                   2201: 
                   2202: =over 4
                   2203: 
1.648     raeburn  2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2205: 
                   2206: Returns a string containing a <select> element int multiple mode
                   2207: 
                   2208: 
                   2209: Args:
                   2210:   $name - name of the <select> element
1.506     raeburn  2211:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2212:   $size - number of rows long the select element is
1.283     albertel 2213:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2214:           (shown text should already have been &mt())
1.506     raeburn  2215:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2216: 
1.282     albertel 2217: =cut
                   2218: 
                   2219: #-------------------------------------------
1.169     www      2220: sub multiple_select_form {
1.284     albertel 2221:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2223:     my $output='';
1.191     matthew  2224:     if (! defined($size)) {
                   2225:         $size = 4;
1.283     albertel 2226:         if (scalar(keys(%$hash))<4) {
                   2227:             $size = scalar(keys(%$hash));
1.191     matthew  2228:         }
                   2229:     }
1.734     bisitz   2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2231:     my @order;
1.506     raeburn  2232:     if (ref($order) eq 'ARRAY')  {
                   2233:         @order = @{$order};
                   2234:     } else {
                   2235:         @order = sort(keys(%$hash));
1.501     banghart 2236:     }
                   2237:     if (exists($$hash{'select_form_order'})) {
                   2238:         @order = @{$$hash{'select_form_order'}};
                   2239:     }
                   2240:         
1.284     albertel 2241:     foreach my $key (@order) {
1.356     albertel 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2243:         $output.='selected="selected" ' if ($selected{$key});
                   2244:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2245:     }
                   2246:     $output.="</select>\n";
                   2247:     return $output;
                   2248: }
                   2249: 
1.88      www      2250: #-------------------------------------------
                   2251: 
                   2252: =pod
                   2253: 
1.1075.2.115  raeburn  2254: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2255: 
                   2256: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2257: allow a user to select options from a ref to a hash containing:
                   2258: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2259: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2260: An optional arg -- $readonly -- if true will cause the select form
                   2261: to be disabled, e.g., for the case where an instructor has a section-
                   2262: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2263: 
1.88      www      2264: See lonrights.pm for an example invocation and use.
                   2265: 
                   2266: =cut
                   2267: 
                   2268: #-------------------------------------------
                   2269: sub select_form {
1.1075.2.115  raeburn  2270:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2271:     return unless (ref($hashref) eq 'HASH');
                   2272:     if ($onchange) {
                   2273:         $onchange = ' onchange="'.$onchange.'"';
                   2274:     }
1.1075.2.129  raeburn  2275:     my $disabled;
                   2276:     if ($readonly) {
                   2277:         $disabled = ' disabled="disabled"';
                   2278:     }
                   2279:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2280:     my @keys;
1.970     raeburn  2281:     if (exists($hashref->{'select_form_order'})) {
                   2282: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2283:     } else {
1.970     raeburn  2284: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2285:     }
1.356     albertel 2286:     foreach my $key (@keys) {
                   2287:         $selectform.=
                   2288: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2289:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2290:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2291:     }
                   2292:     $selectform.="</select>";
                   2293:     return $selectform;
                   2294: }
                   2295: 
1.475     www      2296: # For display filters
                   2297: 
                   2298: sub display_filter {
1.1074    raeburn  2299:     my ($context) = @_;
1.475     www      2300:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2301:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2302:     my $phraseinput = 'hidden';
                   2303:     my $includeinput = 'hidden';
                   2304:     my ($checked,$includetypestext);
                   2305:     if ($env{'form.displayfilter'} eq 'containing') {
                   2306:         $phraseinput = 'text'; 
                   2307:         if ($context eq 'parmslog') {
                   2308:             $includeinput = 'checkbox';
                   2309:             if ($env{'form.includetypes'}) {
                   2310:                 $checked = ' checked="checked"';
                   2311:             }
                   2312:             $includetypestext = &mt('Include parameter types');
                   2313:         }
                   2314:     } else {
                   2315:         $includetypestext = '&nbsp;';
                   2316:     }
                   2317:     my ($additional,$secondid,$thirdid);
                   2318:     if ($context eq 'parmslog') {
                   2319:         $additional = 
                   2320:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2321:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2322:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2323:             '</label>';
                   2324:         $secondid = 'includetypes';
                   2325:         $thirdid = 'includetypestext';
                   2326:     }
                   2327:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2328:                                                     '$secondid','$thirdid')";
                   2329:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2330: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2331: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2332: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2333:            &mt('Filter: [_1]',
1.477     www      2334: 	   &select_form($env{'form.displayfilter'},
                   2335: 			'displayfilter',
1.970     raeburn  2336: 			{'currentfolder' => 'Current folder/page',
1.477     www      2337: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2338: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2339: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2340:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2341:                          '" />'.$additional;
                   2342: }
                   2343: 
                   2344: sub display_filter_js {
                   2345:     my $includetext = &mt('Include parameter types');
                   2346:     return <<"ENDJS";
                   2347:   
                   2348: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2349:     var firstType = 'hidden';
                   2350:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2351:         firstType = 'text';
                   2352:     }
                   2353:     firstObject = document.getElementById(firstid);
                   2354:     if (typeof(firstObject) == 'object') {
                   2355:         if (firstObject.type != firstType) {
                   2356:             changeInputType(firstObject,firstType);
                   2357:         }
                   2358:     }
                   2359:     if (context == 'parmslog') {
                   2360:         var secondType = 'hidden';
                   2361:         if (firstType == 'text') {
                   2362:             secondType = 'checkbox';
                   2363:         }
                   2364:         secondObject = document.getElementById(secondid);  
                   2365:         if (typeof(secondObject) == 'object') {
                   2366:             if (secondObject.type != secondType) {
                   2367:                 changeInputType(secondObject,secondType);
                   2368:             }
                   2369:         }
                   2370:         var textItem = document.getElementById(thirdid);
                   2371:         var currtext = textItem.innerHTML;
                   2372:         var newtext;
                   2373:         if (firstType == 'text') {
                   2374:             newtext = '$includetext';
                   2375:         } else {
                   2376:             newtext = '&nbsp;';
                   2377:         }
                   2378:         if (currtext != newtext) {
                   2379:             textItem.innerHTML = newtext;
                   2380:         }
                   2381:     }
                   2382:     return;
                   2383: }
                   2384: 
                   2385: function changeInputType(oldObject,newType) {
                   2386:     var newObject = document.createElement('input');
                   2387:     newObject.type = newType;
                   2388:     if (oldObject.size) {
                   2389:         newObject.size = oldObject.size;
                   2390:     }
                   2391:     if (oldObject.value) {
                   2392:         newObject.value = oldObject.value;
                   2393:     }
                   2394:     if (oldObject.name) {
                   2395:         newObject.name = oldObject.name;
                   2396:     }
                   2397:     if (oldObject.id) {
                   2398:         newObject.id = oldObject.id;
                   2399:     }
                   2400:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2401:     return;
                   2402: }
                   2403: 
                   2404: ENDJS
1.475     www      2405: }
                   2406: 
1.167     www      2407: sub gradeleveldescription {
                   2408:     my $gradelevel=shift;
                   2409:     my %gradelevels=(0 => 'Not specified',
                   2410: 		     1 => 'Grade 1',
                   2411: 		     2 => 'Grade 2',
                   2412: 		     3 => 'Grade 3',
                   2413: 		     4 => 'Grade 4',
                   2414: 		     5 => 'Grade 5',
                   2415: 		     6 => 'Grade 6',
                   2416: 		     7 => 'Grade 7',
                   2417: 		     8 => 'Grade 8',
                   2418: 		     9 => 'Grade 9',
                   2419: 		     10 => 'Grade 10',
                   2420: 		     11 => 'Grade 11',
                   2421: 		     12 => 'Grade 12',
                   2422: 		     13 => 'Grade 13',
                   2423: 		     14 => '100 Level',
                   2424: 		     15 => '200 Level',
                   2425: 		     16 => '300 Level',
                   2426: 		     17 => '400 Level',
                   2427: 		     18 => 'Graduate Level');
                   2428:     return &mt($gradelevels{$gradelevel});
                   2429: }
                   2430: 
1.163     www      2431: sub select_level_form {
                   2432:     my ($deflevel,$name)=@_;
                   2433:     unless ($deflevel) { $deflevel=0; }
1.167     www      2434:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2435:     for (my $i=0; $i<=18; $i++) {
                   2436:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2437:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2438:                 ">".&gradeleveldescription($i)."</option>\n";
                   2439:     }
                   2440:     $selectform.="</select>";
                   2441:     return $selectform;
1.163     www      2442: }
1.167     www      2443: 
1.35      matthew  2444: #-------------------------------------------
                   2445: 
1.45      matthew  2446: =pod
                   2447: 
1.1075.2.115  raeburn  2448: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2449: 
                   2450: Returns a string containing a <select name='$name' size='1'> form to 
                   2451: allow a user to select the domain to preform an operation in.  
                   2452: See loncreateuser.pm for an example invocation and use.
                   2453: 
1.90      www      2454: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2455: selected");
                   2456: 
1.743     raeburn  2457: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2458: 
1.910     raeburn  2459: 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.
                   2460: 
1.1075.2.36  raeburn  2461: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2462: 
1.1075.2.115  raeburn  2463: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2464: 
                   2465: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2466: 
1.35      matthew  2467: =cut
                   2468: 
                   2469: #-------------------------------------------
1.34      matthew  2470: sub select_dom_form {
1.1075.2.115  raeburn  2471:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2472:     if ($onchange) {
1.874     raeburn  2473:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2474:     }
1.1075.2.115  raeburn  2475:     if ($disabled) {
                   2476:         $disabled = ' disabled="disabled"';
                   2477:     }
1.1075.2.36  raeburn  2478:     my (@domains,%exclude);
1.910     raeburn  2479:     if (ref($incdoms) eq 'ARRAY') {
                   2480:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2481:     } else {
                   2482:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2483:     }
1.90      www      2484:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2485:     if (ref($excdoms) eq 'ARRAY') {
                   2486:         map { $exclude{$_} = 1; } @{$excdoms};
                   2487:     }
1.1075.2.115  raeburn  2488:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2489:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2490:         next if ($exclude{$dom});
1.356     albertel 2491:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2492:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2493:         if ($showdomdesc) {
                   2494:             if ($dom ne '') {
                   2495:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2496:                 if ($domdesc ne '') {
                   2497:                     $selectdomain .= ' ('.$domdesc.')';
                   2498:                 }
                   2499:             } 
                   2500:         }
                   2501:         $selectdomain .= "</option>\n";
1.34      matthew  2502:     }
                   2503:     $selectdomain.="</select>";
                   2504:     return $selectdomain;
                   2505: }
                   2506: 
1.35      matthew  2507: #-------------------------------------------
                   2508: 
1.45      matthew  2509: =pod
                   2510: 
1.648     raeburn  2511: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2512: 
1.586     raeburn  2513: input: 4 arguments (two required, two optional) - 
                   2514:     $domain - domain of new user
                   2515:     $name - name of form element
                   2516:     $default - Value of 'default' causes a default item to be first 
                   2517:                             option, and selected by default. 
                   2518:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2519:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2520: output: returns 2 items: 
1.586     raeburn  2521: (a) form element which contains either:
                   2522:    (i) <select name="$name">
                   2523:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2524:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2525:        </select>
                   2526:        form item if there are multiple library servers in $domain, or
                   2527:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2528:        if there is only one library server in $domain.
                   2529: 
                   2530: (b) number of library servers found.
                   2531: 
                   2532: See loncreateuser.pm for example of use.
1.35      matthew  2533: 
                   2534: =cut
                   2535: 
                   2536: #-------------------------------------------
1.586     raeburn  2537: sub home_server_form_item {
                   2538:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2539:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2540:     my $result;
                   2541:     my $numlib = keys(%servers);
                   2542:     if ($numlib > 1) {
                   2543:         $result .= '<select name="'.$name.'" />'."\n";
                   2544:         if ($default) {
1.804     bisitz   2545:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2546:                        '</option>'."\n";
                   2547:         }
                   2548:         foreach my $hostid (sort(keys(%servers))) {
                   2549:             $result.= '<option value="'.$hostid.'">'.
                   2550: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2551:         }
                   2552:         $result .= '</select>'."\n";
                   2553:     } elsif ($numlib == 1) {
                   2554:         my $hostid;
                   2555:         foreach my $item (keys(%servers)) {
                   2556:             $hostid = $item;
                   2557:         }
                   2558:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2559:                    $hostid.'" />';
                   2560:                    if (!$hide) {
                   2561:                        $result .= $hostid.' '.$servers{$hostid};
                   2562:                    }
                   2563:                    $result .= "\n";
                   2564:     } elsif ($default) {
                   2565:         $result .= '<input type="hidden" name="'.$name.
                   2566:                    '" value="default" />';
                   2567:                    if (!$hide) {
                   2568:                        $result .= &mt('default');
                   2569:                    }
                   2570:                    $result .= "\n";
1.33      matthew  2571:     }
1.586     raeburn  2572:     return ($result,$numlib);
1.33      matthew  2573: }
1.112     bowersj2 2574: 
                   2575: =pod
                   2576: 
1.534     albertel 2577: =back 
                   2578: 
1.112     bowersj2 2579: =cut
1.87      matthew  2580: 
                   2581: ###############################################################
1.112     bowersj2 2582: ##                  Decoding User Agent                      ##
1.87      matthew  2583: ###############################################################
                   2584: 
                   2585: =pod
                   2586: 
1.112     bowersj2 2587: =head1 Decoding the User Agent
                   2588: 
                   2589: =over 4
                   2590: 
                   2591: =item * &decode_user_agent()
1.87      matthew  2592: 
                   2593: Inputs: $r
                   2594: 
                   2595: Outputs:
                   2596: 
                   2597: =over 4
                   2598: 
1.112     bowersj2 2599: =item * $httpbrowser
1.87      matthew  2600: 
1.112     bowersj2 2601: =item * $clientbrowser
1.87      matthew  2602: 
1.112     bowersj2 2603: =item * $clientversion
1.87      matthew  2604: 
1.112     bowersj2 2605: =item * $clientmathml
1.87      matthew  2606: 
1.112     bowersj2 2607: =item * $clientunicode
1.87      matthew  2608: 
1.112     bowersj2 2609: =item * $clientos
1.87      matthew  2610: 
1.1075.2.42  raeburn  2611: =item * $clientmobile
                   2612: 
                   2613: =item * $clientinfo
                   2614: 
1.1075.2.77  raeburn  2615: =item * $clientosversion
                   2616: 
1.87      matthew  2617: =back
                   2618: 
1.157     matthew  2619: =back 
                   2620: 
1.87      matthew  2621: =cut
                   2622: 
                   2623: ###############################################################
                   2624: ###############################################################
                   2625: sub decode_user_agent {
1.247     albertel 2626:     my ($r)=@_;
1.87      matthew  2627:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2628:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2629:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2630:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2631:     my $clientbrowser='unknown';
                   2632:     my $clientversion='0';
                   2633:     my $clientmathml='';
                   2634:     my $clientunicode='0';
1.1075.2.42  raeburn  2635:     my $clientmobile=0;
1.1075.2.77  raeburn  2636:     my $clientosversion='';
1.87      matthew  2637:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2638:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2639: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2640: 	    $clientbrowser=$bname;
                   2641:             $httpbrowser=~/$vreg/i;
                   2642: 	    $clientversion=$1;
                   2643:             $clientmathml=($clientversion>=$minv);
                   2644:             $clientunicode=($clientversion>=$univ);
                   2645: 	}
                   2646:     }
                   2647:     my $clientos='unknown';
1.1075.2.42  raeburn  2648:     my $clientinfo;
1.87      matthew  2649:     if (($httpbrowser=~/linux/i) ||
                   2650:         ($httpbrowser=~/unix/i) ||
                   2651:         ($httpbrowser=~/ux/i) ||
                   2652:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2653:     if (($httpbrowser=~/vax/i) ||
                   2654:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2655:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2656:     if (($httpbrowser=~/mac/i) ||
                   2657:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2658:     if ($httpbrowser=~/win/i) {
                   2659:         $clientos='win';
                   2660:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2661:             $clientosversion = $1;
                   2662:         }
                   2663:     }
1.87      matthew  2664:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2665:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2666:         $clientmobile=lc($1);
                   2667:     }
                   2668:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2669:         $clientinfo = 'firefox-'.$1;
                   2670:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2671:         $clientinfo = 'chromeframe-'.$1;
                   2672:     }
1.87      matthew  2673:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2674:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2675:             $clientosversion);
1.87      matthew  2676: }
                   2677: 
1.32      matthew  2678: ###############################################################
                   2679: ##    Authentication changing form generation subroutines    ##
                   2680: ###############################################################
                   2681: ##
                   2682: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2683: ## hash, and have reasonable default values.
                   2684: ##
                   2685: ##    formname = the name given in the <form> tag.
1.35      matthew  2686: #-------------------------------------------
                   2687: 
1.45      matthew  2688: =pod
                   2689: 
1.112     bowersj2 2690: =head1 Authentication Routines
                   2691: 
                   2692: =over 4
                   2693: 
1.648     raeburn  2694: =item * &authform_xxxxxx()
1.35      matthew  2695: 
                   2696: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2697: handle some of the conveniences required for authentication forms.  
                   2698: This is not an optimal method, but it works.  
                   2699: 
                   2700: =over 4
                   2701: 
1.112     bowersj2 2702: =item * authform_header
1.35      matthew  2703: 
1.112     bowersj2 2704: =item * authform_authorwarning
1.35      matthew  2705: 
1.112     bowersj2 2706: =item * authform_nochange
1.35      matthew  2707: 
1.112     bowersj2 2708: =item * authform_kerberos
1.35      matthew  2709: 
1.112     bowersj2 2710: =item * authform_internal
1.35      matthew  2711: 
1.112     bowersj2 2712: =item * authform_filesystem
1.35      matthew  2713: 
                   2714: =back
                   2715: 
1.648     raeburn  2716: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2717: 
1.35      matthew  2718: =cut
                   2719: 
                   2720: #-------------------------------------------
1.32      matthew  2721: sub authform_header{  
                   2722:     my %in = (
                   2723:         formname => 'cu',
1.80      albertel 2724:         kerb_def_dom => '',
1.32      matthew  2725:         @_,
                   2726:     );
                   2727:     $in{'formname'} = 'document.' . $in{'formname'};
                   2728:     my $result='';
1.80      albertel 2729: 
                   2730: #---------------------------------------------- Code for upper case translation
                   2731:     my $Javascript_toUpperCase;
                   2732:     unless ($in{kerb_def_dom}) {
                   2733:         $Javascript_toUpperCase =<<"END";
                   2734:         switch (choice) {
                   2735:            case 'krb': currentform.elements[choicearg].value =
                   2736:                currentform.elements[choicearg].value.toUpperCase();
                   2737:                break;
                   2738:            default:
                   2739:         }
                   2740: END
                   2741:     } else {
                   2742:         $Javascript_toUpperCase = "";
                   2743:     }
                   2744: 
1.165     raeburn  2745:     my $radioval = "'nochange'";
1.591     raeburn  2746:     if (defined($in{'curr_authtype'})) {
                   2747:         if ($in{'curr_authtype'} ne '') {
                   2748:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2749:         }
1.174     matthew  2750:     }
1.165     raeburn  2751:     my $argfield = 'null';
1.591     raeburn  2752:     if (defined($in{'mode'})) {
1.165     raeburn  2753:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2754:             if (defined($in{'curr_autharg'})) {
                   2755:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2756:                     $argfield = "'$in{'curr_autharg'}'";
                   2757:                 }
                   2758:             }
                   2759:         }
                   2760:     }
                   2761: 
1.32      matthew  2762:     $result.=<<"END";
                   2763: var current = new Object();
1.165     raeburn  2764: current.radiovalue = $radioval;
                   2765: current.argfield = $argfield;
1.32      matthew  2766: 
                   2767: function changed_radio(choice,currentform) {
                   2768:     var choicearg = choice + 'arg';
                   2769:     // If a radio button in changed, we need to change the argfield
                   2770:     if (current.radiovalue != choice) {
                   2771:         current.radiovalue = choice;
                   2772:         if (current.argfield != null) {
                   2773:             currentform.elements[current.argfield].value = '';
                   2774:         }
                   2775:         if (choice == 'nochange') {
                   2776:             current.argfield = null;
                   2777:         } else {
                   2778:             current.argfield = choicearg;
                   2779:             switch(choice) {
                   2780:                 case 'krb': 
                   2781:                     currentform.elements[current.argfield].value = 
                   2782:                         "$in{'kerb_def_dom'}";
                   2783:                 break;
                   2784:               default:
                   2785:                 break;
                   2786:             }
                   2787:         }
                   2788:     }
                   2789:     return;
                   2790: }
1.22      www      2791: 
1.32      matthew  2792: function changed_text(choice,currentform) {
                   2793:     var choicearg = choice + 'arg';
                   2794:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2795:         $Javascript_toUpperCase
1.32      matthew  2796:         // clear old field
                   2797:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2798:             currentform.elements[current.argfield].value = '';
                   2799:         }
                   2800:         current.argfield = choicearg;
                   2801:     }
                   2802:     set_auth_radio_buttons(choice,currentform);
                   2803:     return;
1.20      www      2804: }
1.32      matthew  2805: 
                   2806: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2807:     var numauthchoices = currentform.login.length;
                   2808:     if (typeof numauthchoices  == "undefined") {
                   2809:         return;
                   2810:     } 
1.32      matthew  2811:     var i=0;
1.986     raeburn  2812:     while (i < numauthchoices) {
1.32      matthew  2813:         if (currentform.login[i].value == newvalue) { break; }
                   2814:         i++;
                   2815:     }
1.986     raeburn  2816:     if (i == numauthchoices) {
1.32      matthew  2817:         return;
                   2818:     }
                   2819:     current.radiovalue = newvalue;
                   2820:     currentform.login[i].checked = true;
                   2821:     return;
                   2822: }
                   2823: END
                   2824:     return $result;
                   2825: }
                   2826: 
1.1075.2.20  raeburn  2827: sub authform_authorwarning {
1.32      matthew  2828:     my $result='';
1.144     matthew  2829:     $result='<i>'.
                   2830:         &mt('As a general rule, only authors or co-authors should be '.
                   2831:             'filesystem authenticated '.
                   2832:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2833:     return $result;
                   2834: }
                   2835: 
1.1075.2.20  raeburn  2836: sub authform_nochange {
1.32      matthew  2837:     my %in = (
                   2838:               formname => 'document.cu',
                   2839:               kerb_def_dom => 'MSU.EDU',
                   2840:               @_,
                   2841:           );
1.1075.2.20  raeburn  2842:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2843:     my $result;
1.1075.2.20  raeburn  2844:     if (!$authnum) {
                   2845:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2846:     } else {
                   2847:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2848:                   '<input type="radio" name="login" value="nochange" '.
                   2849:                   'checked="checked" onclick="'.
1.281     albertel 2850:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2851: 	    '</label>';
1.586     raeburn  2852:     }
1.32      matthew  2853:     return $result;
                   2854: }
                   2855: 
1.591     raeburn  2856: sub authform_kerberos {
1.32      matthew  2857:     my %in = (
                   2858:               formname => 'document.cu',
                   2859:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2860:               kerb_def_auth => 'krb4',
1.32      matthew  2861:               @_,
                   2862:               );
1.586     raeburn  2863:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2864:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2865:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2866:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2867:        $check5 = ' checked="checked"';
1.80      albertel 2868:     } else {
1.772     bisitz   2869:        $check4 = ' checked="checked"';
1.80      albertel 2870:     }
1.1075.2.117  raeburn  2871:     if ($in{'readonly'}) {
                   2872:         $disabled = ' disabled="disabled"';
                   2873:     }
1.165     raeburn  2874:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2875:     if (defined($in{'curr_authtype'})) {
                   2876:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2877:             $krbcheck = ' checked="checked"';
1.623     raeburn  2878:             if (defined($in{'mode'})) {
                   2879:                 if ($in{'mode'} eq 'modifyuser') {
                   2880:                     $krbcheck = '';
                   2881:                 }
                   2882:             }
1.591     raeburn  2883:             if (defined($in{'curr_kerb_ver'})) {
                   2884:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2885:                     $check5 = ' checked="checked"';
1.591     raeburn  2886:                     $check4 = '';
                   2887:                 } else {
1.772     bisitz   2888:                     $check4 = ' checked="checked"';
1.591     raeburn  2889:                     $check5 = '';
                   2890:                 }
1.586     raeburn  2891:             }
1.591     raeburn  2892:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2893:                 $krbarg = $in{'curr_autharg'};
                   2894:             }
1.586     raeburn  2895:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2896:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2897:                     $result = 
                   2898:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2899:         $in{'curr_autharg'},$krbver);
                   2900:                 } else {
                   2901:                     $result =
                   2902:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2903:                 }
                   2904:                 return $result; 
                   2905:             }
                   2906:         }
                   2907:     } else {
                   2908:         if ($authnum == 1) {
1.784     bisitz   2909:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2910:         }
                   2911:     }
1.586     raeburn  2912:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2913:         return;
1.587     raeburn  2914:     } elsif ($authtype eq '') {
1.591     raeburn  2915:         if (defined($in{'mode'})) {
1.587     raeburn  2916:             if ($in{'mode'} eq 'modifycourse') {
                   2917:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2918:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2919:                 }
                   2920:             }
                   2921:         }
1.586     raeburn  2922:     }
                   2923:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2924:     if ($authtype eq '') {
                   2925:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2926:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2927:                     $krbcheck.$disabled.' />';
1.586     raeburn  2928:     }
                   2929:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2930:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2931:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2932:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2933:          $in{'curr_authtype'} eq 'krb4')) {
                   2934:         $result .= &mt
1.144     matthew  2935:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2936:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2937:          '<label>'.$authtype,
1.281     albertel 2938:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2939:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2940:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2941:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2942:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2943: 	 '</label>');
1.586     raeburn  2944:     } elsif ($can_assign{'krb4'}) {
                   2945:         $result .= &mt
                   2946:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2947:          '[_3] Version 4 [_4]',
                   2948:          '<label>'.$authtype,
                   2949:          '</label><input type="text" size="10" name="krbarg" '.
                   2950:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2951:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2952:          '<label><input type="hidden" name="krbver" value="4" />',
                   2953:          '</label>');
                   2954:     } elsif ($can_assign{'krb5'}) {
                   2955:         $result .= &mt
                   2956:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2957:          '[_3] Version 5 [_4]',
                   2958:          '<label>'.$authtype,
                   2959:          '</label><input type="text" size="10" name="krbarg" '.
                   2960:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2961:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2962:          '<label><input type="hidden" name="krbver" value="5" />',
                   2963:          '</label>');
                   2964:     }
1.32      matthew  2965:     return $result;
                   2966: }
                   2967: 
1.1075.2.20  raeburn  2968: sub authform_internal {
1.586     raeburn  2969:     my %in = (
1.32      matthew  2970:                 formname => 'document.cu',
                   2971:                 kerb_def_dom => 'MSU.EDU',
                   2972:                 @_,
                   2973:                 );
1.1075.2.117  raeburn  2974:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2975:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2976:     if ($in{'readonly'}) {
                   2977:         $disabled = ' disabled="disabled"';
                   2978:     }
1.591     raeburn  2979:     if (defined($in{'curr_authtype'})) {
                   2980:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2981:             if ($can_assign{'int'}) {
1.772     bisitz   2982:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2983:                 if (defined($in{'mode'})) {
                   2984:                     if ($in{'mode'} eq 'modifyuser') {
                   2985:                         $intcheck = '';
                   2986:                     }
                   2987:                 }
1.591     raeburn  2988:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2989:                     $intarg = $in{'curr_autharg'};
                   2990:                 }
                   2991:             } else {
                   2992:                 $result = &mt('Currently internally authenticated.');
                   2993:                 return $result;
1.165     raeburn  2994:             }
                   2995:         }
1.586     raeburn  2996:     } else {
                   2997:         if ($authnum == 1) {
1.784     bisitz   2998:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2999:         }
                   3000:     }
                   3001:     if (!$can_assign{'int'}) {
                   3002:         return;
1.587     raeburn  3003:     } elsif ($authtype eq '') {
1.591     raeburn  3004:         if (defined($in{'mode'})) {
1.587     raeburn  3005:             if ($in{'mode'} eq 'modifycourse') {
                   3006:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3007:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3008:                 }
                   3009:             }
                   3010:         }
1.165     raeburn  3011:     }
1.586     raeburn  3012:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3013:     if ($authtype eq '') {
                   3014:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3015:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3016:     }
1.605     bisitz   3017:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3018:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3019:     $result = &mt
1.144     matthew  3020:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3021:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3022:     $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  3023:     return $result;
                   3024: }
                   3025: 
1.1075.2.20  raeburn  3026: sub authform_local {
1.32      matthew  3027:     my %in = (
                   3028:               formname => 'document.cu',
                   3029:               kerb_def_dom => 'MSU.EDU',
                   3030:               @_,
                   3031:               );
1.1075.2.117  raeburn  3032:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3033:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3034:     if ($in{'readonly'}) {
                   3035:         $disabled = ' disabled="disabled"';
                   3036:     }
1.591     raeburn  3037:     if (defined($in{'curr_authtype'})) {
                   3038:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3039:             if ($can_assign{'loc'}) {
1.772     bisitz   3040:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3041:                 if (defined($in{'mode'})) {
                   3042:                     if ($in{'mode'} eq 'modifyuser') {
                   3043:                         $loccheck = '';
                   3044:                     }
                   3045:                 }
1.591     raeburn  3046:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3047:                     $locarg = $in{'curr_autharg'};
                   3048:                 }
                   3049:             } else {
                   3050:                 $result = &mt('Currently using local (institutional) authentication.');
                   3051:                 return $result;
1.165     raeburn  3052:             }
                   3053:         }
1.586     raeburn  3054:     } else {
                   3055:         if ($authnum == 1) {
1.784     bisitz   3056:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3057:         }
                   3058:     }
                   3059:     if (!$can_assign{'loc'}) {
                   3060:         return;
1.587     raeburn  3061:     } elsif ($authtype eq '') {
1.591     raeburn  3062:         if (defined($in{'mode'})) {
1.587     raeburn  3063:             if ($in{'mode'} eq 'modifycourse') {
                   3064:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3065:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3066:                 }
                   3067:             }
                   3068:         }
1.165     raeburn  3069:     }
1.586     raeburn  3070:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3071:     if ($authtype eq '') {
                   3072:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3073:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3074:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3075:     }
                   3076:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3077:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3078:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3079:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3080:     return $result;
                   3081: }
                   3082: 
1.1075.2.20  raeburn  3083: sub authform_filesystem {
1.32      matthew  3084:     my %in = (
                   3085:               formname => 'document.cu',
                   3086:               kerb_def_dom => 'MSU.EDU',
                   3087:               @_,
                   3088:               );
1.1075.2.117  raeburn  3089:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3090:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3091:     if ($in{'readonly'}) {
                   3092:         $disabled = ' disabled="disabled"';
                   3093:     }
1.591     raeburn  3094:     if (defined($in{'curr_authtype'})) {
                   3095:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3096:             if ($can_assign{'fsys'}) {
1.772     bisitz   3097:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3098:                 if (defined($in{'mode'})) {
                   3099:                     if ($in{'mode'} eq 'modifyuser') {
                   3100:                         $fsyscheck = '';
                   3101:                     }
                   3102:                 }
1.586     raeburn  3103:             } else {
                   3104:                 $result = &mt('Currently Filesystem Authenticated.');
                   3105:                 return $result;
                   3106:             }           
                   3107:         }
                   3108:     } else {
                   3109:         if ($authnum == 1) {
1.784     bisitz   3110:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3111:         }
                   3112:     }
                   3113:     if (!$can_assign{'fsys'}) {
                   3114:         return;
1.587     raeburn  3115:     } elsif ($authtype eq '') {
1.591     raeburn  3116:         if (defined($in{'mode'})) {
1.587     raeburn  3117:             if ($in{'mode'} eq 'modifycourse') {
                   3118:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3119:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3120:                 }
                   3121:             }
                   3122:         }
1.586     raeburn  3123:     }
                   3124:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3125:     if ($authtype eq '') {
                   3126:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3127:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3128:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3129:     }
                   3130:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3131:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3132:     $result = &mt
1.144     matthew  3133:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3134:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3135:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3136:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3137:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3138:     return $result;
                   3139: }
                   3140: 
1.586     raeburn  3141: sub get_assignable_auth {
                   3142:     my ($dom) = @_;
                   3143:     if ($dom eq '') {
                   3144:         $dom = $env{'request.role.domain'};
                   3145:     }
                   3146:     my %can_assign = (
                   3147:                           krb4 => 1,
                   3148:                           krb5 => 1,
                   3149:                           int  => 1,
                   3150:                           loc  => 1,
                   3151:                      );
                   3152:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3153:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3154:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3155:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3156:             my $context;
                   3157:             if ($env{'request.role'} =~ /^au/) {
                   3158:                 $context = 'author';
1.1075.2.117  raeburn  3159:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3160:                 $context = 'domain';
                   3161:             } elsif ($env{'request.course.id'}) {
                   3162:                 $context = 'course';
                   3163:             }
                   3164:             if ($context) {
                   3165:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3166:                    %can_assign = %{$authhash->{$context}}; 
                   3167:                 }
                   3168:             }
                   3169:         }
                   3170:     }
                   3171:     my $authnum = 0;
                   3172:     foreach my $key (keys(%can_assign)) {
                   3173:         if ($can_assign{$key}) {
                   3174:             $authnum ++;
                   3175:         }
                   3176:     }
                   3177:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3178:         $authnum --;
                   3179:     }
                   3180:     return ($authnum,%can_assign);
                   3181: }
                   3182: 
1.1075.2.137  raeburn  3183: sub check_passwd_rules {
                   3184:     my ($domain,$plainpass) = @_;
                   3185:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3186:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3187:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3188:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3189:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3190:             if ($passwdconf{'min'} > $min) {
                   3191:                 $min = $passwdconf{'min'};
                   3192:             }
1.1075.2.137  raeburn  3193:         }
                   3194:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3195:             $max = $passwdconf{'max'};
                   3196:         }
                   3197:         @chars = @{$passwdconf{'chars'}};
                   3198:     }
                   3199:     if (($min) && (length($plainpass) < $min)) {
                   3200:         push(@brokerule,'min');
                   3201:     }
                   3202:     if (($max) && (length($plainpass) > $max)) {
                   3203:         push(@brokerule,'max');
                   3204:     }
                   3205:     if (@chars) {
                   3206:         my %rules;
                   3207:         map { $rules{$_} = 1; } @chars;
                   3208:         if ($rules{'uc'}) {
                   3209:             unless ($plainpass =~ /[A-Z]/) {
                   3210:                 push(@brokerule,'uc');
                   3211:             }
                   3212:         }
                   3213:         if ($rules{'lc'}) {
                   3214:             unless ($plainpass =~ /[a-z]/) {
                   3215:                 push(@brokerule,'lc');
                   3216:             }
                   3217:         }
                   3218:         if ($rules{'num'}) {
                   3219:             unless ($plainpass =~ /\d/) {
                   3220:                 push(@brokerule,'num');
                   3221:             }
                   3222:         }
                   3223:         if ($rules{'spec'}) {
                   3224:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3225:                 push(@brokerule,'spec');
                   3226:             }
                   3227:         }
                   3228:     }
                   3229:     if (@brokerule) {
                   3230:         my %rulenames = &Apache::lonlocal::texthash(
                   3231:             uc   => 'At least one upper case letter',
                   3232:             lc   => 'At least one lower case letter',
                   3233:             num  => 'At least one number',
                   3234:             spec => 'At least one non-alphanumeric',
                   3235:         );
                   3236:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3237:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3238:         $rulenames{'num'} .= ': 0123456789';
                   3239:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3240:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3241:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3242:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3243:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3244:             if (grep(/^$rule$/,@brokerule)) {
                   3245:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3246:             }
                   3247:         }
                   3248:         $warning .= '</ul>';
                   3249:     }
                   3250:     if (wantarray) {
                   3251:         return @brokerule;
                   3252:     }
                   3253:     return $warning;
                   3254: }
                   3255: 
1.80      albertel 3256: ###############################################################
                   3257: ##    Get Kerberos Defaults for Domain                 ##
                   3258: ###############################################################
                   3259: ##
                   3260: ## Returns default kerberos version and an associated argument
                   3261: ## as listed in file domain.tab. If not listed, provides
                   3262: ## appropriate default domain and kerberos version.
                   3263: ##
                   3264: #-------------------------------------------
                   3265: 
                   3266: =pod
                   3267: 
1.648     raeburn  3268: =item * &get_kerberos_defaults()
1.80      albertel 3269: 
                   3270: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3271: version and domain. If not found, it defaults to version 4 and the 
                   3272: domain of the server.
1.80      albertel 3273: 
1.648     raeburn  3274: =over 4
                   3275: 
1.80      albertel 3276: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3277: 
1.648     raeburn  3278: =back
                   3279: 
                   3280: =back
                   3281: 
1.80      albertel 3282: =cut
                   3283: 
                   3284: #-------------------------------------------
                   3285: sub get_kerberos_defaults {
                   3286:     my $domain=shift;
1.641     raeburn  3287:     my ($krbdef,$krbdefdom);
                   3288:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3289:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3290:         $krbdef = $domdefaults{'auth_def'};
                   3291:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3292:     } else {
1.80      albertel 3293:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3294:         my $krbdefdom=$1;
                   3295:         $krbdefdom=~tr/a-z/A-Z/;
                   3296:         $krbdef = "krb4";
                   3297:     }
                   3298:     return ($krbdef,$krbdefdom);
                   3299: }
1.112     bowersj2 3300: 
1.32      matthew  3301: 
1.46      matthew  3302: ###############################################################
                   3303: ##                Thesaurus Functions                        ##
                   3304: ###############################################################
1.20      www      3305: 
1.46      matthew  3306: =pod
1.20      www      3307: 
1.112     bowersj2 3308: =head1 Thesaurus Functions
                   3309: 
                   3310: =over 4
                   3311: 
1.648     raeburn  3312: =item * &initialize_keywords()
1.46      matthew  3313: 
                   3314: Initializes the package variable %Keywords if it is empty.  Uses the
                   3315: package variable $thesaurus_db_file.
                   3316: 
                   3317: =cut
                   3318: 
                   3319: ###################################################
                   3320: 
                   3321: sub initialize_keywords {
                   3322:     return 1 if (scalar keys(%Keywords));
                   3323:     # If we are here, %Keywords is empty, so fill it up
                   3324:     #   Make sure the file we need exists...
                   3325:     if (! -e $thesaurus_db_file) {
                   3326:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3327:                                  " failed because it does not exist");
                   3328:         return 0;
                   3329:     }
                   3330:     #   Set up the hash as a database
                   3331:     my %thesaurus_db;
                   3332:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3333:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3334:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3335:                                  $thesaurus_db_file);
                   3336:         return 0;
                   3337:     } 
                   3338:     #  Get the average number of appearances of a word.
                   3339:     my $avecount = $thesaurus_db{'average.count'};
                   3340:     #  Put keywords (those that appear > average) into %Keywords
                   3341:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3342:         my ($count,undef) = split /:/,$data;
                   3343:         $Keywords{$word}++ if ($count > $avecount);
                   3344:     }
                   3345:     untie %thesaurus_db;
                   3346:     # Remove special values from %Keywords.
1.356     albertel 3347:     foreach my $value ('total.count','average.count') {
                   3348:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3349:   }
1.46      matthew  3350:     return 1;
                   3351: }
                   3352: 
                   3353: ###################################################
                   3354: 
                   3355: =pod
                   3356: 
1.648     raeburn  3357: =item * &keyword($word)
1.46      matthew  3358: 
                   3359: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3360: than the average number of times in the thesaurus database.  Calls 
                   3361: &initialize_keywords
                   3362: 
                   3363: =cut
                   3364: 
                   3365: ###################################################
1.20      www      3366: 
                   3367: sub keyword {
1.46      matthew  3368:     return if (!&initialize_keywords());
                   3369:     my $word=lc(shift());
                   3370:     $word=~s/\W//g;
                   3371:     return exists($Keywords{$word});
1.20      www      3372: }
1.46      matthew  3373: 
                   3374: ###############################################################
                   3375: 
                   3376: =pod 
1.20      www      3377: 
1.648     raeburn  3378: =item * &get_related_words()
1.46      matthew  3379: 
1.160     matthew  3380: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3381: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3382: will be returned.  The order of the words returned is determined by the
                   3383: database which holds them.
                   3384: 
                   3385: Uses global $thesaurus_db_file.
                   3386: 
1.1057    foxr     3387: 
1.46      matthew  3388: =cut
                   3389: 
                   3390: ###############################################################
                   3391: sub get_related_words {
                   3392:     my $keyword = shift;
                   3393:     my %thesaurus_db;
                   3394:     if (! -e $thesaurus_db_file) {
                   3395:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3396:                                  "failed because the file does not exist");
                   3397:         return ();
                   3398:     }
                   3399:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3400:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3401:         return ();
                   3402:     } 
                   3403:     my @Words=();
1.429     www      3404:     my $count=0;
1.46      matthew  3405:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3406: 	# The first element is the number of times
                   3407: 	# the word appears.  We do not need it now.
1.429     www      3408: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3409: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3410: 	my $threshold=$mostfrequentcount/10;
                   3411:         foreach my $possibleword (@RelatedWords) {
                   3412:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3413:             if ($wordcount>$threshold) {
                   3414: 		push(@Words,$word);
                   3415:                 $count++;
                   3416:                 if ($count>10) { last; }
                   3417: 	    }
1.20      www      3418:         }
                   3419:     }
1.46      matthew  3420:     untie %thesaurus_db;
                   3421:     return @Words;
1.14      harris41 3422: }
1.46      matthew  3423: 
1.112     bowersj2 3424: =pod
                   3425: 
                   3426: =back
                   3427: 
                   3428: =cut
1.61      www      3429: 
                   3430: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3431: =pod
                   3432: 
1.112     bowersj2 3433: =head1 User Name Functions
                   3434: 
                   3435: =over 4
                   3436: 
1.648     raeburn  3437: =item * &plainname($uname,$udom,$first)
1.81      albertel 3438: 
1.112     bowersj2 3439: Takes a users logon name and returns it as a string in
1.226     albertel 3440: "first middle last generation" form 
                   3441: if $first is set to 'lastname' then it returns it as
                   3442: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3443: 
                   3444: =cut
1.61      www      3445: 
1.295     www      3446: 
1.81      albertel 3447: ###############################################################
1.61      www      3448: sub plainname {
1.226     albertel 3449:     my ($uname,$udom,$first)=@_;
1.537     albertel 3450:     return if (!defined($uname) || !defined($udom));
1.295     www      3451:     my %names=&getnames($uname,$udom);
1.226     albertel 3452:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3453: 					  $names{'middlename'},
                   3454: 					  $names{'lastname'},
                   3455: 					  $names{'generation'},$first);
                   3456:     $name=~s/^\s+//;
1.62      www      3457:     $name=~s/\s+$//;
                   3458:     $name=~s/\s+/ /g;
1.353     albertel 3459:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3460:     return $name;
1.61      www      3461: }
1.66      www      3462: 
                   3463: # -------------------------------------------------------------------- Nickname
1.81      albertel 3464: =pod
                   3465: 
1.648     raeburn  3466: =item * &nickname($uname,$udom)
1.81      albertel 3467: 
                   3468: Gets a users name and returns it as a string as
                   3469: 
                   3470: "&quot;nickname&quot;"
1.66      www      3471: 
1.81      albertel 3472: if the user has a nickname or
                   3473: 
                   3474: "first middle last generation"
                   3475: 
                   3476: if the user does not
                   3477: 
                   3478: =cut
1.66      www      3479: 
                   3480: sub nickname {
                   3481:     my ($uname,$udom)=@_;
1.537     albertel 3482:     return if (!defined($uname) || !defined($udom));
1.295     www      3483:     my %names=&getnames($uname,$udom);
1.68      albertel 3484:     my $name=$names{'nickname'};
1.66      www      3485:     if ($name) {
                   3486:        $name='&quot;'.$name.'&quot;'; 
                   3487:     } else {
                   3488:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3489: 	     $names{'lastname'}.' '.$names{'generation'};
                   3490:        $name=~s/\s+$//;
                   3491:        $name=~s/\s+/ /g;
                   3492:     }
                   3493:     return $name;
                   3494: }
                   3495: 
1.295     www      3496: sub getnames {
                   3497:     my ($uname,$udom)=@_;
1.537     albertel 3498:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3499:     if ($udom eq 'public' && $uname eq 'public') {
                   3500: 	return ('lastname' => &mt('Public'));
                   3501:     }
1.295     www      3502:     my $id=$uname.':'.$udom;
                   3503:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3504:     if ($cached) {
                   3505: 	return %{$names};
                   3506:     } else {
                   3507: 	my %loadnames=&Apache::lonnet::get('environment',
                   3508:                     ['firstname','middlename','lastname','generation','nickname'],
                   3509: 					 $udom,$uname);
                   3510: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3511: 	return %loadnames;
                   3512:     }
                   3513: }
1.61      www      3514: 
1.542     raeburn  3515: # -------------------------------------------------------------------- getemails
1.648     raeburn  3516: 
1.542     raeburn  3517: =pod
                   3518: 
1.648     raeburn  3519: =item * &getemails($uname,$udom)
1.542     raeburn  3520: 
                   3521: Gets a user's email information and returns it as a hash with keys:
                   3522: notification, critnotification, permanentemail
                   3523: 
                   3524: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3525: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3526:  
1.648     raeburn  3527: 
1.542     raeburn  3528: =cut
                   3529: 
1.648     raeburn  3530: 
1.466     albertel 3531: sub getemails {
                   3532:     my ($uname,$udom)=@_;
                   3533:     if ($udom eq 'public' && $uname eq 'public') {
                   3534: 	return;
                   3535:     }
1.467     www      3536:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3537:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3538:     my $id=$uname.':'.$udom;
                   3539:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3540:     if ($cached) {
                   3541: 	return %{$names};
                   3542:     } else {
                   3543: 	my %loadnames=&Apache::lonnet::get('environment',
                   3544:                     			   ['notification','critnotification',
                   3545: 					    'permanentemail'],
                   3546: 					   $udom,$uname);
                   3547: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3548: 	return %loadnames;
                   3549:     }
                   3550: }
                   3551: 
1.551     albertel 3552: sub flush_email_cache {
                   3553:     my ($uname,$udom)=@_;
                   3554:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3555:     if (!$uname) { $uname=$env{'user.name'};   }
                   3556:     return if ($udom eq 'public' && $uname eq 'public');
                   3557:     my $id=$uname.':'.$udom;
                   3558:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3559: }
                   3560: 
1.728     raeburn  3561: # -------------------------------------------------------------------- getlangs
                   3562: 
                   3563: =pod
                   3564: 
                   3565: =item * &getlangs($uname,$udom)
                   3566: 
                   3567: Gets a user's language preference and returns it as a hash with key:
                   3568: language.
                   3569: 
                   3570: =cut
                   3571: 
                   3572: 
                   3573: sub getlangs {
                   3574:     my ($uname,$udom) = @_;
                   3575:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3576:     if (!$uname) { $uname=$env{'user.name'};   }
                   3577:     my $id=$uname.':'.$udom;
                   3578:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3579:     if ($cached) {
                   3580:         return %{$langs};
                   3581:     } else {
                   3582:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3583:                                            $udom,$uname);
                   3584:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3585:         return %loadlangs;
                   3586:     }
                   3587: }
                   3588: 
                   3589: sub flush_langs_cache {
                   3590:     my ($uname,$udom)=@_;
                   3591:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3592:     if (!$uname) { $uname=$env{'user.name'};   }
                   3593:     return if ($udom eq 'public' && $uname eq 'public');
                   3594:     my $id=$uname.':'.$udom;
                   3595:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3596: }
                   3597: 
1.61      www      3598: # ------------------------------------------------------------------ Screenname
1.81      albertel 3599: 
                   3600: =pod
                   3601: 
1.648     raeburn  3602: =item * &screenname($uname,$udom)
1.81      albertel 3603: 
                   3604: Gets a users screenname and returns it as a string
                   3605: 
                   3606: =cut
1.61      www      3607: 
                   3608: sub screenname {
                   3609:     my ($uname,$udom)=@_;
1.258     albertel 3610:     if ($uname eq $env{'user.name'} &&
                   3611: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3612:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3613:     return $names{'screenname'};
1.62      www      3614: }
                   3615: 
1.212     albertel 3616: 
1.802     bisitz   3617: # ------------------------------------------------------------- Confirm Wrapper
                   3618: =pod
                   3619: 
1.1075.2.42  raeburn  3620: =item * &confirmwrapper($message)
1.802     bisitz   3621: 
                   3622: Wrap messages about completion of operation in box
                   3623: 
                   3624: =cut
                   3625: 
                   3626: sub confirmwrapper {
                   3627:     my ($message)=@_;
                   3628:     if ($message) {
                   3629:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3630:                .$message."\n"
                   3631:                .'</div>'."\n";
                   3632:     } else {
                   3633:         return $message;
                   3634:     }
                   3635: }
                   3636: 
1.62      www      3637: # ------------------------------------------------------------- Message Wrapper
                   3638: 
                   3639: sub messagewrapper {
1.369     www      3640:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3641:     return 
1.441     albertel 3642:         '<a href="/adm/email?compose=individual&amp;'.
                   3643:         'recname='.$username.'&amp;recdom='.$domain.
                   3644: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3645:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3646: }
1.802     bisitz   3647: 
1.74      www      3648: # --------------------------------------------------------------- Notes Wrapper
                   3649: 
                   3650: sub noteswrapper {
                   3651:     my ($link,$un,$do)=@_;
                   3652:     return 
1.896     amueller 3653: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3654: }
1.802     bisitz   3655: 
1.62      www      3656: # ------------------------------------------------------------- Aboutme Wrapper
                   3657: 
                   3658: sub aboutmewrapper {
1.1070    raeburn  3659:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3660:     if (!defined($username)  && !defined($domain)) {
                   3661:         return;
                   3662:     }
1.1075.2.15  raeburn  3663:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3664: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3665: }
                   3666: 
                   3667: # ------------------------------------------------------------ Syllabus Wrapper
                   3668: 
                   3669: sub syllabuswrapper {
1.707     bisitz   3670:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3671:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3672: }
1.14      harris41 3673: 
1.802     bisitz   3674: # -----------------------------------------------------------------------------
                   3675: 
1.208     matthew  3676: sub track_student_link {
1.887     raeburn  3677:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3678:     my $link ="/adm/trackstudent?";
1.208     matthew  3679:     my $title = 'View recent activity';
                   3680:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3681:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3682:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3683:         $title .= ' of this student';
1.268     albertel 3684:     } 
1.208     matthew  3685:     if (defined($target) && $target !~ /^\s*$/) {
                   3686:         $target = qq{target="$target"};
                   3687:     } else {
                   3688:         $target = '';
                   3689:     }
1.268     albertel 3690:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3691:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3692:     $title = &mt($title);
                   3693:     $linktext = &mt($linktext);
1.448     albertel 3694:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3695: 	&help_open_topic('View_recent_activity');
1.208     matthew  3696: }
                   3697: 
1.781     raeburn  3698: sub slot_reservations_link {
                   3699:     my ($linktext,$sname,$sdom,$target) = @_;
                   3700:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3701:     my $title = 'View slot reservation history';
                   3702:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3703:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3704:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3705:         $title .= ' of this student';
                   3706:     }
                   3707:     if (defined($target) && $target !~ /^\s*$/) {
                   3708:         $target = qq{target="$target"};
                   3709:     } else {
                   3710:         $target = '';
                   3711:     }
                   3712:     $title = &mt($title);
                   3713:     $linktext = &mt($linktext);
                   3714:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3715: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3716: 
                   3717: }
                   3718: 
1.508     www      3719: # ===================================================== Display a student photo
                   3720: 
                   3721: 
1.509     albertel 3722: sub student_image_tag {
1.508     www      3723:     my ($domain,$user)=@_;
                   3724:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3725:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3726: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3727:     } else {
                   3728: 	return '';
                   3729:     }
                   3730: }
                   3731: 
1.112     bowersj2 3732: =pod
                   3733: 
                   3734: =back
                   3735: 
                   3736: =head1 Access .tab File Data
                   3737: 
                   3738: =over 4
                   3739: 
1.648     raeburn  3740: =item * &languageids() 
1.112     bowersj2 3741: 
                   3742: returns list of all language ids
                   3743: 
                   3744: =cut
                   3745: 
1.14      harris41 3746: sub languageids {
1.16      harris41 3747:     return sort(keys(%language));
1.14      harris41 3748: }
                   3749: 
1.112     bowersj2 3750: =pod
                   3751: 
1.648     raeburn  3752: =item * &languagedescription() 
1.112     bowersj2 3753: 
                   3754: returns description of a specified language id
                   3755: 
                   3756: =cut
                   3757: 
1.14      harris41 3758: sub languagedescription {
1.125     www      3759:     my $code=shift;
                   3760:     return  ($supported_language{$code}?'* ':'').
                   3761:             $language{$code}.
1.126     www      3762: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3763: }
                   3764: 
1.1048    foxr     3765: =pod
                   3766: 
                   3767: =item * &plainlanguagedescription
                   3768: 
                   3769: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3770: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3771: 
                   3772: =cut
                   3773: 
1.145     www      3774: sub plainlanguagedescription {
                   3775:     my $code=shift;
                   3776:     return $language{$code};
                   3777: }
                   3778: 
1.1048    foxr     3779: =pod
                   3780: 
                   3781: =item * &supportedlanguagecode
                   3782: 
                   3783: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3784: code.
                   3785: 
                   3786: =cut
                   3787: 
1.145     www      3788: sub supportedlanguagecode {
                   3789:     my $code=shift;
                   3790:     return $supported_language{$code};
1.97      www      3791: }
                   3792: 
1.112     bowersj2 3793: =pod
                   3794: 
1.1048    foxr     3795: =item * &latexlanguage()
                   3796: 
                   3797: Given a language key code returns the correspondnig language to use
                   3798: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3799: is no supported hyphenation for the language code.
                   3800: 
                   3801: =cut
                   3802: 
                   3803: sub latexlanguage {
                   3804:     my $code = shift;
                   3805:     return $latex_language{$code};
                   3806: }
                   3807: 
                   3808: =pod
                   3809: 
                   3810: =item * &latexhyphenation()
                   3811: 
                   3812: Same as above but what's supplied is the language as it might be stored
                   3813: in the metadata.
                   3814: 
                   3815: =cut
                   3816: 
                   3817: sub latexhyphenation {
                   3818:     my $key = shift;
                   3819:     return $latex_language_bykey{$key};
                   3820: }
                   3821: 
                   3822: =pod
                   3823: 
1.648     raeburn  3824: =item * &copyrightids() 
1.112     bowersj2 3825: 
                   3826: returns list of all copyrights
                   3827: 
                   3828: =cut
                   3829: 
                   3830: sub copyrightids {
                   3831:     return sort(keys(%cprtag));
                   3832: }
                   3833: 
                   3834: =pod
                   3835: 
1.648     raeburn  3836: =item * &copyrightdescription() 
1.112     bowersj2 3837: 
                   3838: returns description of a specified copyright id
                   3839: 
                   3840: =cut
                   3841: 
                   3842: sub copyrightdescription {
1.166     www      3843:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3844: }
1.197     matthew  3845: 
                   3846: =pod
                   3847: 
1.648     raeburn  3848: =item * &source_copyrightids() 
1.192     taceyjo1 3849: 
                   3850: returns list of all source copyrights
                   3851: 
                   3852: =cut
                   3853: 
                   3854: sub source_copyrightids {
                   3855:     return sort(keys(%scprtag));
                   3856: }
                   3857: 
                   3858: =pod
                   3859: 
1.648     raeburn  3860: =item * &source_copyrightdescription() 
1.192     taceyjo1 3861: 
                   3862: returns description of a specified source copyright id
                   3863: 
                   3864: =cut
                   3865: 
                   3866: sub source_copyrightdescription {
                   3867:     return &mt($scprtag{shift(@_)});
                   3868: }
1.112     bowersj2 3869: 
                   3870: =pod
                   3871: 
1.648     raeburn  3872: =item * &filecategories() 
1.112     bowersj2 3873: 
                   3874: returns list of all file categories
                   3875: 
                   3876: =cut
                   3877: 
                   3878: sub filecategories {
                   3879:     return sort(keys(%category_extensions));
                   3880: }
                   3881: 
                   3882: =pod
                   3883: 
1.648     raeburn  3884: =item * &filecategorytypes() 
1.112     bowersj2 3885: 
                   3886: returns list of file types belonging to a given file
                   3887: category
                   3888: 
                   3889: =cut
                   3890: 
                   3891: sub filecategorytypes {
1.356     albertel 3892:     my ($cat) = @_;
                   3893:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3894: }
                   3895: 
                   3896: =pod
                   3897: 
1.648     raeburn  3898: =item * &fileembstyle() 
1.112     bowersj2 3899: 
                   3900: returns embedding style for a specified file type
                   3901: 
                   3902: =cut
                   3903: 
                   3904: sub fileembstyle {
                   3905:     return $fe{lc(shift(@_))};
1.169     www      3906: }
                   3907: 
1.351     www      3908: sub filemimetype {
                   3909:     return $fm{lc(shift(@_))};
                   3910: }
                   3911: 
1.169     www      3912: 
                   3913: sub filecategoryselect {
                   3914:     my ($name,$value)=@_;
1.189     matthew  3915:     return &select_form($value,$name,
1.970     raeburn  3916:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3917: }
                   3918: 
                   3919: =pod
                   3920: 
1.648     raeburn  3921: =item * &filedescription() 
1.112     bowersj2 3922: 
                   3923: returns description for a specified file type
                   3924: 
                   3925: =cut
                   3926: 
                   3927: sub filedescription {
1.188     matthew  3928:     my $file_description = $fd{lc(shift())};
                   3929:     $file_description =~ s:([\[\]]):~$1:g;
                   3930:     return &mt($file_description);
1.112     bowersj2 3931: }
                   3932: 
                   3933: =pod
                   3934: 
1.648     raeburn  3935: =item * &filedescriptionex() 
1.112     bowersj2 3936: 
                   3937: returns description for a specified file type with
                   3938: extra formatting
                   3939: 
                   3940: =cut
                   3941: 
                   3942: sub filedescriptionex {
                   3943:     my $ex=shift;
1.188     matthew  3944:     my $file_description = $fd{lc($ex)};
                   3945:     $file_description =~ s:([\[\]]):~$1:g;
                   3946:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3947: }
                   3948: 
                   3949: # End of .tab access
                   3950: =pod
                   3951: 
                   3952: =back
                   3953: 
                   3954: =cut
                   3955: 
                   3956: # ------------------------------------------------------------------ File Types
                   3957: sub fileextensions {
                   3958:     return sort(keys(%fe));
                   3959: }
                   3960: 
1.97      www      3961: # ----------------------------------------------------------- Display Languages
                   3962: # returns a hash with all desired display languages
                   3963: #
                   3964: 
                   3965: sub display_languages {
                   3966:     my %languages=();
1.695     raeburn  3967:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3968: 	$languages{$lang}=1;
1.97      www      3969:     }
                   3970:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3971:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3972: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3973: 	    $languages{$lang}=1;
1.97      www      3974:         }
                   3975:     }
                   3976:     return %languages;
1.14      harris41 3977: }
                   3978: 
1.582     albertel 3979: sub languages {
                   3980:     my ($possible_langs) = @_;
1.695     raeburn  3981:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3982:     if (!ref($possible_langs)) {
                   3983: 	if( wantarray ) {
                   3984: 	    return @preferred_langs;
                   3985: 	} else {
                   3986: 	    return $preferred_langs[0];
                   3987: 	}
                   3988:     }
                   3989:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3990:     my @preferred_possibilities;
                   3991:     foreach my $preferred_lang (@preferred_langs) {
                   3992: 	if (exists($possibilities{$preferred_lang})) {
                   3993: 	    push(@preferred_possibilities, $preferred_lang);
                   3994: 	}
                   3995:     }
                   3996:     if( wantarray ) {
                   3997: 	return @preferred_possibilities;
                   3998:     }
                   3999:     return $preferred_possibilities[0];
                   4000: }
                   4001: 
1.742     raeburn  4002: sub user_lang {
                   4003:     my ($touname,$toudom,$fromcid) = @_;
                   4004:     my @userlangs;
                   4005:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4006:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4007:                     $env{'course.'.$fromcid.'.languages'}));
                   4008:     } else {
                   4009:         my %langhash = &getlangs($touname,$toudom);
                   4010:         if ($langhash{'languages'} ne '') {
                   4011:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4012:         } else {
                   4013:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4014:             if ($domdefs{'lang_def'} ne '') {
                   4015:                 @userlangs = ($domdefs{'lang_def'});
                   4016:             }
                   4017:         }
                   4018:     }
                   4019:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4020:     my $user_lh = Apache::localize->get_handle(@languages);
                   4021:     return $user_lh;
                   4022: }
                   4023: 
                   4024: 
1.112     bowersj2 4025: ###############################################################
                   4026: ##               Student Answer Attempts                     ##
                   4027: ###############################################################
                   4028: 
                   4029: =pod
                   4030: 
                   4031: =head1 Alternate Problem Views
                   4032: 
                   4033: =over 4
                   4034: 
1.648     raeburn  4035: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4036:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4037: 
                   4038: Return string with previous attempt on problem. Arguments:
                   4039: 
                   4040: =over 4
                   4041: 
                   4042: =item * $symb: Problem, including path
                   4043: 
                   4044: =item * $username: username of the desired student
                   4045: 
                   4046: =item * $domain: domain of the desired student
1.14      harris41 4047: 
1.112     bowersj2 4048: =item * $course: Course ID
1.14      harris41 4049: 
1.112     bowersj2 4050: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4051:     something
1.14      harris41 4052: 
1.112     bowersj2 4053: =item * $regexp: if string matches this regexp, the string will be
                   4054:     sent to $gradesub
1.14      harris41 4055: 
1.112     bowersj2 4056: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4057: 
1.1075.2.86  raeburn  4058: =item * $usec: section of the desired student
                   4059: 
                   4060: =item * $identifier: counter for student (multiple students one problem) or
                   4061:     problem (one student; whole sequence).
                   4062: 
1.112     bowersj2 4063: =back
1.14      harris41 4064: 
1.112     bowersj2 4065: The output string is a table containing all desired attempts, if any.
1.16      harris41 4066: 
1.112     bowersj2 4067: =cut
1.1       albertel 4068: 
                   4069: sub get_previous_attempt {
1.1075.2.86  raeburn  4070:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4071:   my $prevattempts='';
1.43      ng       4072:   no strict 'refs';
1.1       albertel 4073:   if ($symb) {
1.3       albertel 4074:     my (%returnhash)=
                   4075:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4076:     if ($returnhash{'version'}) {
                   4077:       my %lasthash=();
                   4078:       my $version;
                   4079:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4080:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4081:             if ($key =~ /\.rawrndseed$/) {
                   4082:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4083:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4084:             } else {
                   4085:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4086:             }
1.19      harris41 4087:         }
1.1       albertel 4088:       }
1.596     albertel 4089:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4090:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4091:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4092:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4093:       foreach my $key (sort(keys(%lasthash))) {
                   4094: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4095: 	if ($#parts > 0) {
1.31      albertel 4096: 	  my $data=$parts[-1];
1.989     raeburn  4097:           next if ($data eq 'foilorder');
1.31      albertel 4098: 	  pop(@parts);
1.1010    www      4099:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4100:           if ($data eq 'type') {
                   4101:               unless ($showsurv) {
                   4102:                   my $id = join(',',@parts);
                   4103:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4104:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4105:                       $lasthidden{$ign.'.'.$id} = 1;
                   4106:                   }
1.945     raeburn  4107:               }
1.1075.2.86  raeburn  4108:               if ($identifier ne '') {
                   4109:                   my $id = join(',',@parts);
                   4110:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4111:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4112:                       $hidestatus{$ign.'.'.$id} = 1;
                   4113:                   }
                   4114:               }
                   4115:           } elsif ($data eq 'regrader') {
                   4116:               if (($identifier ne '') && (@parts)) {
                   4117:                   my $id = join(',',@parts);
                   4118:                   $regraded{$ign.'.'.$id} = 1;
                   4119:               }
1.1010    www      4120:           } 
1.31      albertel 4121: 	} else {
1.41      ng       4122: 	  if ($#parts == 0) {
                   4123: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4124: 	  } else {
                   4125: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4126: 	  }
1.31      albertel 4127: 	}
1.16      harris41 4128:       }
1.596     albertel 4129:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4130:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4131:         my (%solved,%resets,%probstatus);
                   4132:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4133:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4134:                 foreach my $id (keys(%regraded)) {
                   4135:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4136:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4137:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4138:                         push(@{$resets{$id}},$version);
                   4139:                     }
                   4140:                 }
                   4141:             }
                   4142:         }
1.40      ng       4143: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4144:             my (@hidden,@unsolved);
1.945     raeburn  4145:             if (%typeparts) {
                   4146:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4147:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4148:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4149:                         push(@hidden,$id);
1.1075.2.86  raeburn  4150:                     } elsif ($identifier ne '') {
                   4151:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4152:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4153:                                 ($hidestatus{$id})) {
                   4154:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4155:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4156:                                 push(@{$solved{$id}},$version);
                   4157:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4158:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4159:                                 my $skip;
                   4160:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4161:                                     foreach my $reset (@{$resets{$id}}) {
                   4162:                                         if ($reset > $solved{$id}[-1]) {
                   4163:                                             $skip=1;
                   4164:                                             last;
                   4165:                                         }
                   4166:                                     }
                   4167:                                 }
                   4168:                                 unless ($skip) {
                   4169:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4170:                                     push(@unsolved,$partslist);
                   4171:                                 }
                   4172:                             }
                   4173:                         }
1.945     raeburn  4174:                     }
                   4175:                 }
                   4176:             }
                   4177:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4178:                            '<td>'.&mt('Transaction [_1]',$version);
                   4179:             if (@unsolved) {
                   4180:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4181:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4182:                                  &mt('Hide').'</label></span>';
                   4183:             }
                   4184:             $prevattempts .= '</td>';
1.945     raeburn  4185:             if (@hidden) {
                   4186:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4187:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4188:                     my $hide;
                   4189:                     foreach my $id (@hidden) {
                   4190:                         if ($key =~ /^\Q$id\E/) {
                   4191:                             $hide = 1;
                   4192:                             last;
                   4193:                         }
                   4194:                     }
                   4195:                     if ($hide) {
                   4196:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4197:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4198:                             my $value = &format_previous_attempt_value($key,
                   4199:                                              $returnhash{$version.':'.$key});
                   4200:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4201:                         } else {
                   4202:                             $prevattempts.='<td>&nbsp;</td>';
                   4203:                         }
                   4204:                     } else {
                   4205:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4206:                             my $value = $returnhash{$version.':'.$key};
                   4207:                             if ($key =~ /\.rndseed$/) {
                   4208:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4209:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4210:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4211:                                 }
                   4212:                             }
                   4213:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4214:                                            '&nbsp;</td>';
1.945     raeburn  4215:                         } else {
                   4216:                             $prevattempts.='<td>&nbsp;</td>';
                   4217:                         }
                   4218:                     }
                   4219:                 }
                   4220:             } else {
                   4221: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4222:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4223:                     my $value = $returnhash{$version.':'.$key};
                   4224:                     if ($key =~ /\.rndseed$/) {
                   4225:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4226:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4227:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4228:                         }
                   4229:                     }
                   4230:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4231:                                    '&nbsp;</td>';
1.945     raeburn  4232: 	        }
                   4233:             }
                   4234: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4235: 	 }
1.1       albertel 4236:       }
1.945     raeburn  4237:       my @currhidden = keys(%lasthidden);
1.596     albertel 4238:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4239:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4240:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4241:           if (%typeparts) {
                   4242:               my $hidden;
                   4243:               foreach my $id (@currhidden) {
                   4244:                   if ($key =~ /^\Q$id\E/) {
                   4245:                       $hidden = 1;
                   4246:                       last;
                   4247:                   }
                   4248:               }
                   4249:               if ($hidden) {
                   4250:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4251:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4252:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4253:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4254:                           $value = &$gradesub($value);
                   4255:                       }
                   4256:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4257:                   } else {
                   4258:                       $prevattempts.='<td>&nbsp;</td>';
                   4259:                   }
                   4260:               } else {
                   4261:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4262:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4263:                       $value = &$gradesub($value);
                   4264:                   }
                   4265:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4266:               }
                   4267:           } else {
                   4268: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4269: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4270:                   $value = &$gradesub($value);
                   4271:               }
                   4272: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4273:           }
1.16      harris41 4274:       }
1.596     albertel 4275:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4276:     } else {
1.596     albertel 4277:       $prevattempts=
                   4278: 	  &start_data_table().&start_data_table_row().
                   4279: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4280: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4281:     }
                   4282:   } else {
1.596     albertel 4283:     $prevattempts=
                   4284: 	  &start_data_table().&start_data_table_row().
                   4285: 	  '<td>'.&mt('No data.').'</td>'.
                   4286: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4287:   }
1.10      albertel 4288: }
                   4289: 
1.581     albertel 4290: sub format_previous_attempt_value {
                   4291:     my ($key,$value) = @_;
1.1011    www      4292:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4293: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4294:     } elsif (ref($value) eq 'ARRAY') {
                   4295: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4296:     } elsif ($key =~ /answerstring$/) {
                   4297:         my %answers = &Apache::lonnet::str2hash($value);
                   4298:         my @anskeys = sort(keys(%answers));
                   4299:         if (@anskeys == 1) {
                   4300:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4301:             if ($answer =~ m{\0}) {
                   4302:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4303:             }
                   4304:             my $tag_internal_answer_name = 'INTERNAL';
                   4305:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4306:                 $value = $answer; 
                   4307:             } else {
                   4308:                 $value = $anskeys[0].'='.$answer;
                   4309:             }
                   4310:         } else {
                   4311:             foreach my $ans (@anskeys) {
                   4312:                 my $answer = $answers{$ans};
1.1001    raeburn  4313:                 if ($answer =~ m{\0}) {
                   4314:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4315:                 }
                   4316:                 $value .=  $ans.'='.$answer.'<br />';;
                   4317:             } 
                   4318:         }
1.581     albertel 4319:     } else {
                   4320: 	$value = &unescape($value);
                   4321:     }
                   4322:     return $value;
                   4323: }
                   4324: 
                   4325: 
1.107     albertel 4326: sub relative_to_absolute {
                   4327:     my ($url,$output)=@_;
                   4328:     my $parser=HTML::TokeParser->new(\$output);
                   4329:     my $token;
                   4330:     my $thisdir=$url;
                   4331:     my @rlinks=();
                   4332:     while ($token=$parser->get_token) {
                   4333: 	if ($token->[0] eq 'S') {
                   4334: 	    if ($token->[1] eq 'a') {
                   4335: 		if ($token->[2]->{'href'}) {
                   4336: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4337: 		}
                   4338: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4339: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4340: 	    } elsif ($token->[1] eq 'base') {
                   4341: 		$thisdir=$token->[2]->{'href'};
                   4342: 	    }
                   4343: 	}
                   4344:     }
                   4345:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4346:     foreach my $link (@rlinks) {
1.726     raeburn  4347: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4348: 		($link=~/^\//) ||
                   4349: 		($link=~/^javascript:/i) ||
                   4350: 		($link=~/^mailto:/i) ||
                   4351: 		($link=~/^\#/)) {
                   4352: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4353: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4354: 	}
                   4355:     }
                   4356: # -------------------------------------------------- Deal with Applet codebases
                   4357:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4358:     return $output;
                   4359: }
                   4360: 
1.112     bowersj2 4361: =pod
                   4362: 
1.648     raeburn  4363: =item * &get_student_view()
1.112     bowersj2 4364: 
                   4365: show a snapshot of what student was looking at
                   4366: 
                   4367: =cut
                   4368: 
1.10      albertel 4369: sub get_student_view {
1.186     albertel 4370:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4371:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4372:   my (%form);
1.10      albertel 4373:   my @elements=('symb','courseid','domain','username');
                   4374:   foreach my $element (@elements) {
1.186     albertel 4375:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4376:   }
1.186     albertel 4377:   if (defined($moreenv)) {
                   4378:       %form=(%form,%{$moreenv});
                   4379:   }
1.236     albertel 4380:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4381:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4382:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4383:   $userview=~s/\<body[^\>]*\>//gi;
                   4384:   $userview=~s/\<\/body\>//gi;
                   4385:   $userview=~s/\<html\>//gi;
                   4386:   $userview=~s/\<\/html\>//gi;
                   4387:   $userview=~s/\<head\>//gi;
                   4388:   $userview=~s/\<\/head\>//gi;
                   4389:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4390:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4391:   if (wantarray) {
                   4392:      return ($userview,$response);
                   4393:   } else {
                   4394:      return $userview;
                   4395:   }
                   4396: }
                   4397: 
                   4398: sub get_student_view_with_retries {
                   4399:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4400: 
                   4401:     my $ok = 0;                 # True if we got a good response.
                   4402:     my $content;
                   4403:     my $response;
                   4404: 
                   4405:     # Try to get the student_view done. within the retries count:
                   4406:     
                   4407:     do {
                   4408:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4409:          $ok      = $response->is_success;
                   4410:          if (!$ok) {
                   4411:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4412:          }
                   4413:          $retries--;
                   4414:     } while (!$ok && ($retries > 0));
                   4415:     
                   4416:     if (!$ok) {
                   4417:        $content = '';          # On error return an empty content.
                   4418:     }
1.651     www      4419:     if (wantarray) {
                   4420:        return ($content, $response);
                   4421:     } else {
                   4422:        return $content;
                   4423:     }
1.11      albertel 4424: }
                   4425: 
1.1075.2.149! raeburn  4426: sub css_links {
        !          4427:     my ($currsymb,$level) = @_;
        !          4428:     my ($links,@symbs,%cssrefs,%httpref);
        !          4429:     if ($level eq 'map') {
        !          4430:         my $navmap = Apache::lonnavmaps::navmap->new();
        !          4431:         if (ref($navmap)) {
        !          4432:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
        !          4433:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
        !          4434:             foreach my $res (@resources) {
        !          4435:                 if (ref($res) && $res->symb()) {
        !          4436:                     push(@symbs,$res->symb());
        !          4437:                 }
        !          4438:             }
        !          4439:         }
        !          4440:     } else {
        !          4441:         @symbs = ($currsymb);
        !          4442:     }
        !          4443:     foreach my $symb (@symbs) {
        !          4444:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
        !          4445:         if ($css_href =~ /\S/) {
        !          4446:             unless ($css_href =~ m{https?://}) {
        !          4447:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
        !          4448:                 my $proburl =  &Apache::lonnet::clutter($url);
        !          4449:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
        !          4450:                 unless ($css_href =~ m{^/}) {
        !          4451:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
        !          4452:                 }
        !          4453:                 if ($css_href =~ m{^/(res|uploaded)/}) {
        !          4454:                     unless (($httpref{'httpref.'.$css_href}) ||
        !          4455:                             (&Apache::lonnet::is_on_map($css_href))) {
        !          4456:                         my $thisurl = $proburl;
        !          4457:                         if ($env{'httpref.'.$proburl}) {
        !          4458:                             $thisurl = $env{'httpref.'.$proburl};
        !          4459:                         }
        !          4460:                         $httpref{'httpref.'.$css_href} = $thisurl;
        !          4461:                     }
        !          4462:                 }
        !          4463:             }
        !          4464:             $cssrefs{$css_href} = 1;
        !          4465:         }
        !          4466:     }
        !          4467:     if (keys(%httpref)) {
        !          4468:         &Apache::lonnet::appenv(\%httpref);
        !          4469:     }
        !          4470:     if (keys(%cssrefs)) {
        !          4471:         foreach my $css_href (keys(%cssrefs)) {
        !          4472:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
        !          4473:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
        !          4474:         }
        !          4475:     }
        !          4476:     return $links;
        !          4477: }
        !          4478: 
1.112     bowersj2 4479: =pod
                   4480: 
1.648     raeburn  4481: =item * &get_student_answers() 
1.112     bowersj2 4482: 
                   4483: show a snapshot of how student was answering problem
                   4484: 
                   4485: =cut
                   4486: 
1.11      albertel 4487: sub get_student_answers {
1.100     sakharuk 4488:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4489:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4490:   my (%moreenv);
1.11      albertel 4491:   my @elements=('symb','courseid','domain','username');
                   4492:   foreach my $element (@elements) {
1.186     albertel 4493:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4494:   }
1.186     albertel 4495:   $moreenv{'grade_target'}='answer';
                   4496:   %moreenv=(%form,%moreenv);
1.497     raeburn  4497:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4498:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4499:   return $userview;
1.1       albertel 4500: }
1.116     albertel 4501: 
                   4502: =pod
                   4503: 
                   4504: =item * &submlink()
                   4505: 
1.242     albertel 4506: Inputs: $text $uname $udom $symb $target
1.116     albertel 4507: 
                   4508: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4509: 
                   4510: =cut
                   4511: 
                   4512: ###############################################
                   4513: sub submlink {
1.242     albertel 4514:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4515:     if (!($uname && $udom)) {
                   4516: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4517: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4518: 	if (!$symb) { $symb=$cursymb; }
                   4519:     }
1.254     matthew  4520:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4521:     $symb=&escape($symb);
1.960     bisitz   4522:     if ($target) { $target=" target=\"$target\""; }
                   4523:     return
                   4524:         '<a href="/adm/grades?command=submission'.
                   4525:         '&amp;symb='.$symb.
                   4526:         '&amp;student='.$uname.
                   4527:         '&amp;userdom='.$udom.'"'.
                   4528:         $target.'>'.$text.'</a>';
1.242     albertel 4529: }
                   4530: ##############################################
                   4531: 
                   4532: =pod
                   4533: 
                   4534: =item * &pgrdlink()
                   4535: 
                   4536: Inputs: $text $uname $udom $symb $target
                   4537: 
                   4538: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4539: 
                   4540: =cut
                   4541: 
                   4542: ###############################################
                   4543: sub pgrdlink {
                   4544:     my $link=&submlink(@_);
                   4545:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4546:     return $link;
                   4547: }
                   4548: ##############################################
                   4549: 
                   4550: =pod
                   4551: 
                   4552: =item * &pprmlink()
                   4553: 
                   4554: Inputs: $text $uname $udom $symb $target
                   4555: 
                   4556: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4557: student and a specific resource
1.242     albertel 4558: 
                   4559: =cut
                   4560: 
                   4561: ###############################################
                   4562: sub pprmlink {
                   4563:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4564:     if (!($uname && $udom)) {
                   4565: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4566: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4567: 	if (!$symb) { $symb=$cursymb; }
                   4568:     }
1.254     matthew  4569:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4570:     $symb=&escape($symb);
1.242     albertel 4571:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4572:     return '<a href="/adm/parmset?command=set&amp;'.
                   4573: 	'symb='.$symb.'&amp;uname='.$uname.
                   4574: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4575: }
                   4576: ##############################################
1.37      matthew  4577: 
1.112     bowersj2 4578: =pod
                   4579: 
                   4580: =back
                   4581: 
                   4582: =cut
                   4583: 
1.37      matthew  4584: ###############################################
1.51      www      4585: 
                   4586: 
                   4587: sub timehash {
1.687     raeburn  4588:     my ($thistime) = @_;
                   4589:     my $timezone = &Apache::lonlocal::gettimezone();
                   4590:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4591:                      ->set_time_zone($timezone);
                   4592:     my $wday = $dt->day_of_week();
                   4593:     if ($wday == 7) { $wday = 0; }
                   4594:     return ( 'second' => $dt->second(),
                   4595:              'minute' => $dt->minute(),
                   4596:              'hour'   => $dt->hour(),
                   4597:              'day'     => $dt->day_of_month(),
                   4598:              'month'   => $dt->month(),
                   4599:              'year'    => $dt->year(),
                   4600:              'weekday' => $wday,
                   4601:              'dayyear' => $dt->day_of_year(),
                   4602:              'dlsav'   => $dt->is_dst() );
1.51      www      4603: }
                   4604: 
1.370     www      4605: sub utc_string {
                   4606:     my ($date)=@_;
1.371     www      4607:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4608: }
                   4609: 
1.51      www      4610: sub maketime {
                   4611:     my %th=@_;
1.687     raeburn  4612:     my ($epoch_time,$timezone,$dt);
                   4613:     $timezone = &Apache::lonlocal::gettimezone();
                   4614:     eval {
                   4615:         $dt = DateTime->new( year   => $th{'year'},
                   4616:                              month  => $th{'month'},
                   4617:                              day    => $th{'day'},
                   4618:                              hour   => $th{'hour'},
                   4619:                              minute => $th{'minute'},
                   4620:                              second => $th{'second'},
                   4621:                              time_zone => $timezone,
                   4622:                          );
                   4623:     };
                   4624:     if (!$@) {
                   4625:         $epoch_time = $dt->epoch;
                   4626:         if ($epoch_time) {
                   4627:             return $epoch_time;
                   4628:         }
                   4629:     }
1.51      www      4630:     return POSIX::mktime(
                   4631:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4632:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4633: }
                   4634: 
                   4635: #########################################
1.51      www      4636: 
                   4637: sub findallcourses {
1.482     raeburn  4638:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4639:     my %roles;
                   4640:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4641:     my %courses;
1.51      www      4642:     my $now=time;
1.482     raeburn  4643:     if (!defined($uname)) {
                   4644:         $uname = $env{'user.name'};
                   4645:     }
                   4646:     if (!defined($udom)) {
                   4647:         $udom = $env{'user.domain'};
                   4648:     }
                   4649:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4650:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4651:         if (!%roles) {
                   4652:             %roles = (
                   4653:                        cc => 1,
1.907     raeburn  4654:                        co => 1,
1.482     raeburn  4655:                        in => 1,
                   4656:                        ep => 1,
                   4657:                        ta => 1,
                   4658:                        cr => 1,
                   4659:                        st => 1,
                   4660:              );
                   4661:         }
                   4662:         foreach my $entry (keys(%roleshash)) {
                   4663:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4664:             if ($trole =~ /^cr/) { 
                   4665:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4666:             } else {
                   4667:                 next if (!exists($roles{$trole}));
                   4668:             }
                   4669:             if ($tend) {
                   4670:                 next if ($tend < $now);
                   4671:             }
                   4672:             if ($tstart) {
                   4673:                 next if ($tstart > $now);
                   4674:             }
1.1058    raeburn  4675:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4676:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4677:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4678:             if ($secpart eq '') {
                   4679:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4680:                 $sec = 'none';
1.1058    raeburn  4681:                 $value .= $cnum.'/';
1.482     raeburn  4682:             } else {
                   4683:                 $cnum = $cnumpart;
                   4684:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4685:                 $value .= $cnum.'/'.$sec;
                   4686:             }
                   4687:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4688:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4689:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4690:                 }
                   4691:             } else {
                   4692:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4693:             }
1.482     raeburn  4694:         }
                   4695:     } else {
                   4696:         foreach my $key (keys(%env)) {
1.483     albertel 4697: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4698:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4699: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4700: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4701: 	        next if (%roles && !exists($roles{$role}));
                   4702: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4703:                 my $active=1;
                   4704:                 if ($starttime) {
                   4705: 		    if ($now<$starttime) { $active=0; }
                   4706:                 }
                   4707:                 if ($endtime) {
                   4708:                     if ($now>$endtime) { $active=0; }
                   4709:                 }
                   4710:                 if ($active) {
1.1058    raeburn  4711:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4712:                     if ($sec eq '') {
                   4713:                         $sec = 'none';
1.1058    raeburn  4714:                     } else {
                   4715:                         $value .= $sec;
                   4716:                     }
                   4717:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4718:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4719:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4720:                         }
                   4721:                     } else {
                   4722:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4723:                     }
1.474     raeburn  4724:                 }
                   4725:             }
1.51      www      4726:         }
                   4727:     }
1.474     raeburn  4728:     return %courses;
1.51      www      4729: }
1.37      matthew  4730: 
1.54      www      4731: ###############################################
1.474     raeburn  4732: 
                   4733: sub blockcheck {
1.1075.2.147  raeburn  4734:     my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  4735: 
1.1075.2.73  raeburn  4736:     if (defined($udom) && defined($uname)) {
                   4737:         # If uname and udom are for a course, check for blocks in the course.
                   4738:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4739:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  4740:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  4741:             return ($startblock,$endblock,$triggerblock);
                   4742:         }
                   4743:     } else {
1.490     raeburn  4744:         $udom = $env{'user.domain'};
                   4745:         $uname = $env{'user.name'};
                   4746:     }
                   4747: 
1.502     raeburn  4748:     my $startblock = 0;
                   4749:     my $endblock = 0;
1.1062    raeburn  4750:     my $triggerblock = '';
1.482     raeburn  4751:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4752: 
1.490     raeburn  4753:     # If uname is for a user, and activity is course-specific, i.e.,
                   4754:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4755: 
1.490     raeburn  4756:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4757:          $activity eq 'groups' || $activity eq 'printout') &&
                   4758:         ($env{'request.course.id'})) {
1.490     raeburn  4759:         foreach my $key (keys(%live_courses)) {
                   4760:             if ($key ne $env{'request.course.id'}) {
                   4761:                 delete($live_courses{$key});
                   4762:             }
                   4763:         }
                   4764:     }
                   4765: 
                   4766:     my $otheruser = 0;
                   4767:     my %own_courses;
                   4768:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4769:         # Resource belongs to user other than current user.
                   4770:         $otheruser = 1;
                   4771:         # Gather courses for current user
                   4772:         %own_courses = 
                   4773:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4774:     }
                   4775: 
                   4776:     # Gather active course roles - course coordinator, instructor, 
                   4777:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4778: 
                   4779:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4780:         my ($cdom,$cnum);
                   4781:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4782:             $cdom = $env{'course.'.$course.'.domain'};
                   4783:             $cnum = $env{'course.'.$course.'.num'};
                   4784:         } else {
1.490     raeburn  4785:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4786:         }
                   4787:         my $no_ownblock = 0;
                   4788:         my $no_userblock = 0;
1.533     raeburn  4789:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4790:             # Check if current user has 'evb' priv for this
                   4791:             if (defined($own_courses{$course})) {
                   4792:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4793:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4794:                     if ($sec ne 'none') {
                   4795:                         $checkrole .= '/'.$sec;
                   4796:                     }
                   4797:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4798:                         $no_ownblock = 1;
                   4799:                         last;
                   4800:                     }
                   4801:                 }
                   4802:             }
                   4803:             # if they have 'evb' priv and are currently not playing student
                   4804:             next if (($no_ownblock) &&
                   4805:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4806:         }
1.474     raeburn  4807:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4808:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4809:             if ($sec ne 'none') {
1.482     raeburn  4810:                 $checkrole .= '/'.$sec;
1.474     raeburn  4811:             }
1.490     raeburn  4812:             if ($otheruser) {
                   4813:                 # Resource belongs to user other than current user.
                   4814:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4815:                 my (%allroles,%userroles);
                   4816:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4817:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4818:                         my ($trole,$tdom,$tnum,$tsec);
                   4819:                         if ($entry =~ /^cr/) {
                   4820:                             ($trole,$tdom,$tnum,$tsec) = 
                   4821:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4822:                         } else {
                   4823:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4824:                         }
                   4825:                         my ($spec,$area,$trest);
                   4826:                         $area = '/'.$tdom.'/'.$tnum;
                   4827:                         $trest = $tnum;
                   4828:                         if ($tsec ne '') {
                   4829:                             $area .= '/'.$tsec;
                   4830:                             $trest .= '/'.$tsec;
                   4831:                         }
                   4832:                         $spec = $trole.'.'.$area;
                   4833:                         if ($trole =~ /^cr/) {
                   4834:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4835:                                                               $tdom,$spec,$trest,$area);
                   4836:                         } else {
                   4837:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4838:                                                                 $tdom,$spec,$trest,$area);
                   4839:                         }
                   4840:                     }
1.1075.2.124  raeburn  4841:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4842:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4843:                         if ($1) {
                   4844:                             $no_userblock = 1;
                   4845:                             last;
                   4846:                         }
1.486     raeburn  4847:                     }
                   4848:                 }
1.490     raeburn  4849:             } else {
                   4850:                 # Resource belongs to current user
                   4851:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4852:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4853:                     $no_ownblock = 1;
                   4854:                     last;
                   4855:                 }
1.474     raeburn  4856:             }
                   4857:         }
                   4858:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4859:         next if (($no_ownblock) &&
1.491     albertel 4860:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4861:         next if ($no_userblock);
1.474     raeburn  4862: 
1.1075.2.128  raeburn  4863:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4864:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4865:         
1.1062    raeburn  4866:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  4867:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  4868:         if (($start != 0) && 
                   4869:             (($startblock == 0) || ($startblock > $start))) {
                   4870:             $startblock = $start;
1.1062    raeburn  4871:             if ($trigger ne '') {
                   4872:                 $triggerblock = $trigger;
                   4873:             }
1.502     raeburn  4874:         }
                   4875:         if (($end != 0)  &&
                   4876:             (($endblock == 0) || ($endblock < $end))) {
                   4877:             $endblock = $end;
1.1062    raeburn  4878:             if ($trigger ne '') {
                   4879:                 $triggerblock = $trigger;
                   4880:             }
1.502     raeburn  4881:         }
1.490     raeburn  4882:     }
1.1062    raeburn  4883:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4884: }
                   4885: 
                   4886: sub get_blocks {
1.1075.2.147  raeburn  4887:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  4888:     my $startblock = 0;
                   4889:     my $endblock = 0;
1.1062    raeburn  4890:     my $triggerblock = '';
1.490     raeburn  4891:     my $course = $cdom.'_'.$cnum;
                   4892:     $setters->{$course} = {};
                   4893:     $setters->{$course}{'staff'} = [];
                   4894:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4895:     $setters->{$course}{'triggers'} = [];
                   4896:     my (@blockers,%triggered);
                   4897:     my $now = time;
                   4898:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4899:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  4900:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  4901:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   4902:             $blocked = 1;
                   4903:             $nosymbcache = 1;
1.1075.2.148  raeburn  4904:             $noenccheck = 1;
1.1075.2.147  raeburn  4905:         }
1.1075.2.148  raeburn  4906:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  4907:         foreach my $block (@blockers) {
                   4908:             if ($block =~ /^firstaccess____(.+)$/) {
                   4909:                 my $item = $1;
                   4910:                 my $type = 'map';
                   4911:                 my $timersymb = $item;
                   4912:                 if ($item eq 'course') {
                   4913:                     $type = 'course';
                   4914:                 } elsif ($item =~ /___\d+___/) {
                   4915:                     $type = 'resource';
                   4916:                 } else {
                   4917:                     $timersymb = &Apache::lonnet::symbread($item);
                   4918:                 }
                   4919:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4920:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4921:                 $triggered{$block} = {
                   4922:                                        start => $start,
                   4923:                                        end   => $end,
                   4924:                                        type  => $type,
                   4925:                                      };
                   4926:             }
                   4927:         }
                   4928:     } else {
                   4929:         foreach my $block (keys(%commblocks)) {
                   4930:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4931:                 my ($start,$end) = ($1,$2);
                   4932:                 if ($start <= time && $end >= time) {
                   4933:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4934:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4935:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4936:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4937:                                     push(@blockers,$block);
                   4938:                                 }
                   4939:                             }
                   4940:                         }
                   4941:                     }
                   4942:                 }
                   4943:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4944:                 my $item = $1;
                   4945:                 my $timersymb = $item; 
                   4946:                 my $type = 'map';
                   4947:                 if ($item eq 'course') {
                   4948:                     $type = 'course';
                   4949:                 } elsif ($item =~ /___\d+___/) {
                   4950:                     $type = 'resource';
                   4951:                 } else {
                   4952:                     $timersymb = &Apache::lonnet::symbread($item);
                   4953:                 }
                   4954:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4955:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4956:                 if ($start && $end) {
                   4957:                     if (($start <= time) && ($end >= time)) {
                   4958:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4959:                             push(@blockers,$block);
                   4960:                             $triggered{$block} = {
                   4961:                                                    start => $start,
                   4962:                                                    end   => $end,
                   4963:                                                    type  => $type,
                   4964:                                                  };
                   4965:                         }
                   4966:                     }
1.490     raeburn  4967:                 }
1.1062    raeburn  4968:             }
                   4969:         }
                   4970:     }
                   4971:     foreach my $blocker (@blockers) {
                   4972:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4973:             &parse_block_record($commblocks{$blocker});
                   4974:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4975:         my ($start,$end,$triggertype);
                   4976:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4977:             ($start,$end) = ($1,$2);
                   4978:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4979:             $start = $triggered{$blocker}{'start'};
                   4980:             $end = $triggered{$blocker}{'end'};
                   4981:             $triggertype = $triggered{$blocker}{'type'};
                   4982:         }
                   4983:         if ($start) {
                   4984:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4985:             if ($triggertype) {
                   4986:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4987:             } else {
                   4988:                 push(@{$$setters{$course}{'triggers'}},0);
                   4989:             }
                   4990:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4991:                 $startblock = $start;
                   4992:                 if ($triggertype) {
                   4993:                     $triggerblock = $blocker;
1.474     raeburn  4994:                 }
                   4995:             }
1.1062    raeburn  4996:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4997:                $endblock = $end;
                   4998:                if ($triggertype) {
                   4999:                    $triggerblock = $blocker;
                   5000:                }
                   5001:             }
1.474     raeburn  5002:         }
                   5003:     }
1.1062    raeburn  5004:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5005: }
                   5006: 
                   5007: sub parse_block_record {
                   5008:     my ($record) = @_;
                   5009:     my ($setuname,$setudom,$title,$blocks);
                   5010:     if (ref($record) eq 'HASH') {
                   5011:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5012:         $title = &unescape($record->{'event'});
                   5013:         $blocks = $record->{'blocks'};
                   5014:     } else {
                   5015:         my @data = split(/:/,$record,3);
                   5016:         if (scalar(@data) eq 2) {
                   5017:             $title = $data[1];
                   5018:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5019:         } else {
                   5020:             ($setuname,$setudom,$title) = @data;
                   5021:         }
                   5022:         $blocks = { 'com' => 'on' };
                   5023:     }
                   5024:     return ($setuname,$setudom,$title,$blocks);
                   5025: }
                   5026: 
1.854     kalberla 5027: sub blocking_status {
1.1075.2.147  raeburn  5028:     my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5029:     my %setters;
1.890     droeschl 5030: 
1.1061    raeburn  5031: # check for active blocking
1.1062    raeburn  5032:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.147  raeburn  5033:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5034:     my $blocked = 0;
                   5035:     if ($startblock && $endblock) {
                   5036:         $blocked = 1;
                   5037:     }
1.890     droeschl 5038: 
1.1061    raeburn  5039: # caller just wants to know whether a block is active
                   5040:     if (!wantarray) { return $blocked; }
                   5041: 
                   5042: # build a link to a popup window containing the details
                   5043:     my $querystring  = "?activity=$activity";
                   5044: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  5045:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5046:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5047:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5048:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5049:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5050:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5051:         if ($symb) {
                   5052:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5053:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5054:         }
1.1062    raeburn  5055:     }
1.1061    raeburn  5056: 
                   5057:     my $output .= <<'END_MYBLOCK';
                   5058: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5059:     var options = "width=" + w + ",height=" + h + ",";
                   5060:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5061:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5062:     var newWin = window.open(url, wdwName, options);
                   5063:     newWin.focus();
                   5064: }
1.890     droeschl 5065: END_MYBLOCK
1.854     kalberla 5066: 
1.1061    raeburn  5067:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5068:   
1.1061    raeburn  5069:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5070:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5071:     my $class = 'LC_comblock';
1.1062    raeburn  5072:     if ($activity eq 'docs') {
                   5073:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5074:         $class = '';
1.1063    raeburn  5075:     } elsif ($activity eq 'printout') {
                   5076:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5077:     } elsif ($activity eq 'passwd') {
                   5078:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  5079:     }
1.1061    raeburn  5080:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5081: <div class='$class'>
1.869     kalberla 5082:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5083:   title='$text'>
                   5084:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5085:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5086:   title='$text'>$text</a>
1.867     kalberla 5087: </div>
                   5088: 
                   5089: END_BLOCK
1.474     raeburn  5090: 
1.1061    raeburn  5091:     return ($blocked, $output);
1.854     kalberla 5092: }
1.490     raeburn  5093: 
1.60      matthew  5094: ###############################################
                   5095: 
1.682     raeburn  5096: sub check_ip_acc {
1.1075.2.105  raeburn  5097:     my ($acc,$clientip)=@_;
1.682     raeburn  5098:     &Apache::lonxml::debug("acc is $acc");
                   5099:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5100:         return 1;
                   5101:     }
                   5102:     my $allowed=0;
1.1075.2.144  raeburn  5103:     my $ip;
                   5104:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5105:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5106:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5107:     } else {
                   5108:         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
                   5109:     }
1.682     raeburn  5110: 
                   5111:     my $name;
                   5112:     foreach my $pattern (split(',',$acc)) {
                   5113:         $pattern =~ s/^\s*//;
                   5114:         $pattern =~ s/\s*$//;
                   5115:         if ($pattern =~ /\*$/) {
                   5116:             #35.8.*
                   5117:             $pattern=~s/\*//;
                   5118:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5119:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5120:             #35.8.3.[34-56]
                   5121:             my $low=$2;
                   5122:             my $high=$3;
                   5123:             $pattern=$1;
                   5124:             if ($ip =~ /^\Q$pattern\E/) {
                   5125:                 my $last=(split(/\./,$ip))[3];
                   5126:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   5127:             }
                   5128:         } elsif ($pattern =~ /^\*/) {
                   5129:             #*.msu.edu
                   5130:             $pattern=~s/\*//;
                   5131:             if (!defined($name)) {
                   5132:                 use Socket;
                   5133:                 my $netaddr=inet_aton($ip);
                   5134:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5135:             }
                   5136:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5137:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5138:             #127.0.0.1
                   5139:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5140:         } else {
                   5141:             #some.name.com
                   5142:             if (!defined($name)) {
                   5143:                 use Socket;
                   5144:                 my $netaddr=inet_aton($ip);
                   5145:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5146:             }
                   5147:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5148:         }
                   5149:         if ($allowed) { last; }
                   5150:     }
                   5151:     return $allowed;
                   5152: }
                   5153: 
                   5154: ###############################################
                   5155: 
1.60      matthew  5156: =pod
                   5157: 
1.112     bowersj2 5158: =head1 Domain Template Functions
                   5159: 
                   5160: =over 4
                   5161: 
                   5162: =item * &determinedomain()
1.60      matthew  5163: 
                   5164: Inputs: $domain (usually will be undef)
                   5165: 
1.63      www      5166: Returns: Determines which domain should be used for designs
1.60      matthew  5167: 
                   5168: =cut
1.54      www      5169: 
1.60      matthew  5170: ###############################################
1.63      www      5171: sub determinedomain {
                   5172:     my $domain=shift;
1.531     albertel 5173:     if (! $domain) {
1.60      matthew  5174:         # Determine domain if we have not been given one
1.893     raeburn  5175:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5176:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5177:         if ($env{'request.role.domain'}) { 
                   5178:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5179:         }
                   5180:     }
1.63      www      5181:     return $domain;
                   5182: }
                   5183: ###############################################
1.517     raeburn  5184: 
1.518     albertel 5185: sub devalidate_domconfig_cache {
                   5186:     my ($udom)=@_;
                   5187:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5188: }
                   5189: 
                   5190: # ---------------------- Get domain configuration for a domain
                   5191: sub get_domainconf {
                   5192:     my ($udom) = @_;
                   5193:     my $cachetime=1800;
                   5194:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5195:     if (defined($cached)) { return %{$result}; }
                   5196: 
                   5197:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5198: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5199:     my (%designhash,%legacy);
1.518     albertel 5200:     if (keys(%domconfig) > 0) {
                   5201:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5202:             if (keys(%{$domconfig{'login'}})) {
                   5203:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5204:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5205:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5206:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5207:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5208:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5209:                                         if ($key eq 'loginvia') {
                   5210:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5211:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5212:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5213:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5214:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5215:                                                 } else {
                   5216:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5217:                                                 }
1.948     raeburn  5218:                                             }
1.1075.2.87  raeburn  5219:                                         } elsif ($key eq 'headtag') {
                   5220:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5221:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5222:                                             }
1.946     raeburn  5223:                                         }
1.1075.2.87  raeburn  5224:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5225:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5226:                                         }
1.946     raeburn  5227:                                     }
                   5228:                                 }
                   5229:                             }
                   5230:                         } else {
                   5231:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5232:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5233:                                     $domconfig{'login'}{$key}{$img};
                   5234:                             }
1.699     raeburn  5235:                         }
                   5236:                     } else {
                   5237:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5238:                     }
1.632     raeburn  5239:                 }
                   5240:             } else {
                   5241:                 $legacy{'login'} = 1;
1.518     albertel 5242:             }
1.632     raeburn  5243:         } else {
                   5244:             $legacy{'login'} = 1;
1.518     albertel 5245:         }
                   5246:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5247:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5248:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5249:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5250:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5251:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5252:                         }
1.518     albertel 5253:                     }
                   5254:                 }
1.632     raeburn  5255:             } else {
                   5256:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5257:             }
1.632     raeburn  5258:         } else {
                   5259:             $legacy{'rolecolors'} = 1;
1.518     albertel 5260:         }
1.948     raeburn  5261:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5262:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5263:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5264:             }
                   5265:         }
1.632     raeburn  5266:         if (keys(%legacy) > 0) {
                   5267:             my %legacyhash = &get_legacy_domconf($udom);
                   5268:             foreach my $item (keys(%legacyhash)) {
                   5269:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5270:                     if ($legacy{'login'}) { 
                   5271:                         $designhash{$item} = $legacyhash{$item};
                   5272:                     }
                   5273:                 } else {
                   5274:                     if ($legacy{'rolecolors'}) {
                   5275:                         $designhash{$item} = $legacyhash{$item};
                   5276:                     }
1.518     albertel 5277:                 }
                   5278:             }
                   5279:         }
1.632     raeburn  5280:     } else {
                   5281:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5282:     }
                   5283:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5284: 				  $cachetime);
                   5285:     return %designhash;
                   5286: }
                   5287: 
1.632     raeburn  5288: sub get_legacy_domconf {
                   5289:     my ($udom) = @_;
                   5290:     my %legacyhash;
                   5291:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5292:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5293:     if (-e $designfile) {
1.1075.2.128  raeburn  5294:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5295:             while (my $line = <$fh>) {
                   5296:                 next if ($line =~ /^\#/);
                   5297:                 chomp($line);
                   5298:                 my ($key,$val)=(split(/\=/,$line));
                   5299:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5300:             }
                   5301:             close($fh);
                   5302:         }
                   5303:     }
1.1026    raeburn  5304:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5305:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5306:     }
                   5307:     return %legacyhash;
                   5308: }
                   5309: 
1.63      www      5310: =pod
                   5311: 
1.112     bowersj2 5312: =item * &domainlogo()
1.63      www      5313: 
                   5314: Inputs: $domain (usually will be undef)
                   5315: 
                   5316: Returns: A link to a domain logo, if the domain logo exists.
                   5317: If the domain logo does not exist, a description of the domain.
                   5318: 
                   5319: =cut
1.112     bowersj2 5320: 
1.63      www      5321: ###############################################
                   5322: sub domainlogo {
1.517     raeburn  5323:     my $domain = &determinedomain(shift);
1.518     albertel 5324:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5325:     # See if there is a logo
                   5326:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5327:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5328:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5329: 	    if ($imgsrc =~ m{^/res/}) {
                   5330: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5331: 		&Apache::lonnet::repcopy($local_name);
                   5332: 	    }
                   5333: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5334:         } 
                   5335:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5336:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5337:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5338:     } else {
1.60      matthew  5339:         return '';
1.59      www      5340:     }
                   5341: }
1.63      www      5342: ##############################################
                   5343: 
                   5344: =pod
                   5345: 
1.112     bowersj2 5346: =item * &designparm()
1.63      www      5347: 
                   5348: Inputs: $which parameter; $domain (usually will be undef)
                   5349: 
                   5350: Returns: value of designparamter $which
                   5351: 
                   5352: =cut
1.112     bowersj2 5353: 
1.397     albertel 5354: 
1.400     albertel 5355: ##############################################
1.397     albertel 5356: sub designparm {
                   5357:     my ($which,$domain)=@_;
                   5358:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5359:         return $env{'environment.color.'.$which};
1.96      www      5360:     }
1.63      www      5361:     $domain=&determinedomain($domain);
1.1016    raeburn  5362:     my %domdesign;
                   5363:     unless ($domain eq 'public') {
                   5364:         %domdesign = &get_domainconf($domain);
                   5365:     }
1.520     raeburn  5366:     my $output;
1.517     raeburn  5367:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5368:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5369:     } else {
1.520     raeburn  5370:         $output = $defaultdesign{$which};
                   5371:     }
                   5372:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5373:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5374:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5375:             if ($output =~ m{^/res/}) {
                   5376:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5377:                 &Apache::lonnet::repcopy($local_name);
                   5378:             }
1.520     raeburn  5379:             $output = &lonhttpdurl($output);
                   5380:         }
1.63      www      5381:     }
1.520     raeburn  5382:     return $output;
1.63      www      5383: }
1.59      www      5384: 
1.822     bisitz   5385: ##############################################
                   5386: =pod
                   5387: 
1.832     bisitz   5388: =item * &authorspace()
                   5389: 
1.1028    raeburn  5390: Inputs: $url (usually will be undef).
1.832     bisitz   5391: 
1.1075.2.40  raeburn  5392: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5393:          directory being viewed (or for which action is being taken). 
                   5394:          If $url is provided, and begins /priv/<domain>/<uname>
                   5395:          the path will be that portion of the $context argument.
                   5396:          Otherwise the path will be for the author space of the current
                   5397:          user when the current role is author, or for that of the 
                   5398:          co-author/assistant co-author space when the current role 
                   5399:          is co-author or assistant co-author.
1.832     bisitz   5400: 
                   5401: =cut
                   5402: 
                   5403: sub authorspace {
1.1028    raeburn  5404:     my ($url) = @_;
                   5405:     if ($url ne '') {
                   5406:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5407:            return $1;
                   5408:         }
                   5409:     }
1.832     bisitz   5410:     my $caname = '';
1.1024    www      5411:     my $cadom = '';
1.1028    raeburn  5412:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5413:         ($cadom,$caname) =
1.832     bisitz   5414:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5415:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5416:         $caname = $env{'user.name'};
1.1024    www      5417:         $cadom = $env{'user.domain'};
1.832     bisitz   5418:     }
1.1028    raeburn  5419:     if (($caname ne '') && ($cadom ne '')) {
                   5420:         return "/priv/$cadom/$caname/";
                   5421:     }
                   5422:     return;
1.832     bisitz   5423: }
                   5424: 
                   5425: ##############################################
                   5426: =pod
                   5427: 
1.822     bisitz   5428: =item * &head_subbox()
                   5429: 
                   5430: Inputs: $content (contains HTML code with page functions, etc.)
                   5431: 
                   5432: Returns: HTML div with $content
                   5433:          To be included in page header
                   5434: 
                   5435: =cut
                   5436: 
                   5437: sub head_subbox {
                   5438:     my ($content)=@_;
                   5439:     my $output =
1.993     raeburn  5440:         '<div class="LC_head_subbox">'
1.822     bisitz   5441:        .$content
                   5442:        .'</div>'
                   5443: }
                   5444: 
                   5445: ##############################################
                   5446: =pod
                   5447: 
                   5448: =item * &CSTR_pageheader()
                   5449: 
1.1026    raeburn  5450: Input: (optional) filename from which breadcrumb trail is built.
                   5451:        In most cases no input as needed, as $env{'request.filename'}
                   5452:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5453: 
                   5454: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5455:          To be included on Authoring Space pages
1.822     bisitz   5456: 
                   5457: =cut
                   5458: 
                   5459: sub CSTR_pageheader {
1.1026    raeburn  5460:     my ($trailfile) = @_;
                   5461:     if ($trailfile eq '') {
                   5462:         $trailfile = $env{'request.filename'};
                   5463:     }
                   5464: 
                   5465: # this is for resources; directories have customtitle, and crumbs
                   5466: # and select recent are created in lonpubdir.pm
                   5467: 
                   5468:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5469:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5470:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5471:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5472:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5473: 
                   5474:     my $parentpath = '';
                   5475:     my $lastitem = '';
                   5476:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5477:         $parentpath = $1;
                   5478:         $lastitem = $2;
                   5479:     } else {
                   5480:         $lastitem = $thisdisfn;
                   5481:     }
1.921     bisitz   5482: 
                   5483:     my $output =
1.822     bisitz   5484:          '<div>'
                   5485:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5486:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5487:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5488:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5489:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5490: 
                   5491:     if ($lastitem) {
                   5492:         $output .=
                   5493:              '<span class="LC_filename">'
                   5494:             .$lastitem
                   5495:             .'</span>';
                   5496:     }
                   5497:     $output .=
                   5498:          '<br />'
1.822     bisitz   5499:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5500:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5501:         .'</form>'
                   5502:         .&Apache::lonmenu::constspaceform()
                   5503:         .'</div>';
1.921     bisitz   5504: 
                   5505:     return $output;
1.822     bisitz   5506: }
                   5507: 
1.60      matthew  5508: ###############################################
                   5509: ###############################################
                   5510: 
                   5511: =pod
                   5512: 
1.112     bowersj2 5513: =back
                   5514: 
1.549     albertel 5515: =head1 HTML Helpers
1.112     bowersj2 5516: 
                   5517: =over 4
                   5518: 
                   5519: =item * &bodytag()
1.60      matthew  5520: 
                   5521: Returns a uniform header for LON-CAPA web pages.
                   5522: 
                   5523: Inputs: 
                   5524: 
1.112     bowersj2 5525: =over 4
                   5526: 
                   5527: =item * $title, A title to be displayed on the page.
                   5528: 
                   5529: =item * $function, the current role (can be undef).
                   5530: 
                   5531: =item * $addentries, extra parameters for the <body> tag.
                   5532: 
                   5533: =item * $bodyonly, if defined, only return the <body> tag.
                   5534: 
                   5535: =item * $domain, if defined, force a given domain.
                   5536: 
                   5537: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5538:             text interface only)
1.60      matthew  5539: 
1.814     bisitz   5540: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5541:                      navigational links
1.317     albertel 5542: 
1.338     albertel 5543: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5544: 
1.1075.2.12  raeburn  5545: =item * $no_inline_link, if true and in remote mode, don't show the
                   5546:          'Switch To Inline Menu' link
                   5547: 
1.460     albertel 5548: =item * $args, optional argument valid values are
                   5549:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5550:             use_absolute     -> for external resource or syllabus, this will
                   5551:                                 contain https://<hostname> if server uses
                   5552:                                 https (as per hosts.tab), but request is for http
                   5553:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5554: 
1.1075.2.15  raeburn  5555: =item * $advtoolsref, optional argument, ref to an array containing
                   5556:             inlineremote items to be added in "Functions" menu below
                   5557:             breadcrumbs.
                   5558: 
1.112     bowersj2 5559: =back
                   5560: 
1.60      matthew  5561: Returns: A uniform header for LON-CAPA web pages.  
                   5562: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5563: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5564: other decorations will be returned.
                   5565: 
                   5566: =cut
                   5567: 
1.54      www      5568: sub bodytag {
1.831     bisitz   5569:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5570:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5571: 
1.954     raeburn  5572:     my $public;
                   5573:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5574:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5575:         $public = 1;
                   5576:     }
1.460     albertel 5577:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5578:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5579:     my $hostname = $args->{'hostname'};
1.339     albertel 5580: 
1.183     matthew  5581:     $function = &get_users_function() if (!$function);
1.339     albertel 5582:     my $img =    &designparm($function.'.img',$domain);
                   5583:     my $font =   &designparm($function.'.font',$domain);
                   5584:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5585: 
1.803     bisitz   5586:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5587: 		   'bgcolor' => $pgbg,
1.339     albertel 5588: 		   'text'    => $font,
                   5589:                    'alink'   => &designparm($function.'.alink',$domain),
                   5590: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5591: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5592:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5593: 
1.63      www      5594:  # role and realm
1.1075.2.68  raeburn  5595:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5596:     if ($realm) {
                   5597:         $realm = '/'.$realm;
                   5598:     }
1.378     raeburn  5599:     if ($role  eq 'ca') {
1.479     albertel 5600:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5601:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5602:     } 
1.55      www      5603: # realm
1.258     albertel 5604:     if ($env{'request.course.id'}) {
1.378     raeburn  5605:         if ($env{'request.role'} !~ /^cr/) {
                   5606:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5607:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5608:             if ($env{'request.role.desc'}) {
                   5609:                 $role = $env{'request.role.desc'};
                   5610:             } else {
                   5611:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5612:             }
1.1075.2.115  raeburn  5613:         } else {
                   5614:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5615:         }
1.898     raeburn  5616:         if ($env{'request.course.sec'}) {
                   5617:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5618:         }   
1.359     albertel 5619: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5620:     } else {
                   5621:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5622:     }
1.433     albertel 5623: 
1.359     albertel 5624:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5625: 
1.438     albertel 5626:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5627: 
1.101     www      5628: # construct main body tag
1.359     albertel 5629:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5630: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5631: 
1.1075.2.38  raeburn  5632:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5633: 
                   5634:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5635:         return $bodytag;
1.1075.2.38  raeburn  5636:     }
1.359     albertel 5637: 
1.954     raeburn  5638:     if ($public) {
1.433     albertel 5639: 	undef($role);
                   5640:     }
1.359     albertel 5641:     
1.762     bisitz   5642:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5643:     #
                   5644:     # Extra info if you are the DC
                   5645:     my $dc_info = '';
                   5646:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5647:                         $env{'course.'.$env{'request.course.id'}.
                   5648:                                  '.domain'}.'/'})) {
                   5649:         my $cid = $env{'request.course.id'};
1.917     raeburn  5650:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5651:         $dc_info =~ s/\s+$//;
1.359     albertel 5652:     }
                   5653: 
1.1075.2.108  raeburn  5654:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5655: 
1.1075.2.13  raeburn  5656:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5657: 
1.1075.2.38  raeburn  5658: 
                   5659: 
1.1075.2.21  raeburn  5660:     my $funclist;
                   5661:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5662:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5663:                     Apache::lonmenu::serverform();
                   5664:         my $forbodytag;
                   5665:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5666:                                             $forcereg,$args->{'group'},
                   5667:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5668:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5669:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5670:             $funclist = $forbodytag;
                   5671:         }
                   5672:     } else {
1.903     droeschl 5673: 
                   5674:         #    if ($env{'request.state'} eq 'construct') {
                   5675:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5676:         #    }
                   5677: 
1.1075.2.38  raeburn  5678:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5679:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5680: 
1.1075.2.38  raeburn  5681:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5682: 
1.916     droeschl 5683:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5684:             if ($dc_info) {
                   5685:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5686:             }
1.1075.2.38  raeburn  5687:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5688:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5689:             return $bodytag;
                   5690:         }
1.894     droeschl 5691: 
1.927     raeburn  5692:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5693:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5694:         }
1.916     droeschl 5695: 
1.1075.2.38  raeburn  5696:         $bodytag .= $right;
1.852     droeschl 5697: 
1.917     raeburn  5698:         if ($dc_info) {
                   5699:             $dc_info = &dc_courseid_toggle($dc_info);
                   5700:         }
                   5701:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5702: 
1.1075.2.61  raeburn  5703:         #if directed to not display the secondary menu, don't.
                   5704:         if ($args->{'no_secondary_menu'}) {
                   5705:             return $bodytag;
                   5706:         }
1.903     droeschl 5707:         #don't show menus for public users
1.954     raeburn  5708:         if (!$public){
1.1075.2.52  raeburn  5709:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5710:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5711:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5712:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5713:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133  raeburn  5714:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5715:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5716:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5717:                                                             $args->{'group'},
1.1075.2.133  raeburn  5718:                                                             $args->{'hide_buttons',
                   5719:                                                             $hostname});
1.1075.2.15  raeburn  5720:             } else {
1.1075.2.21  raeburn  5721:                 my $forbodytag;
                   5722:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5723:                                                     $forcereg,$args->{'group'},
                   5724:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5725:                                                     $advtoolsref,'',$hostname,
                   5726:                                                     \$forbodytag);
1.1075.2.21  raeburn  5727:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5728:                     $bodytag .= $forbodytag;
                   5729:                 }
1.920     raeburn  5730:             }
1.903     droeschl 5731:         }else{
                   5732:             # this is to seperate menu from content when there's no secondary
                   5733:             # menu. Especially needed for public accessible ressources.
                   5734:             $bodytag .= '<hr style="clear:both" />';
                   5735:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5736:         }
1.903     droeschl 5737: 
1.235     raeburn  5738:         return $bodytag;
1.1075.2.12  raeburn  5739:     }
                   5740: 
                   5741: #
                   5742: # Top frame rendering, Remote is up
                   5743: #
                   5744: 
                   5745:     my $imgsrc = $img;
                   5746:     if ($img =~ /^\/adm/) {
                   5747:         $imgsrc = &lonhttpdurl($img);
                   5748:     }
                   5749:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5750: 
1.1075.2.60  raeburn  5751:     my $help=($no_inline_link?''
                   5752:               :&Apache::loncommon::top_nav_help('Help'));
                   5753: 
1.1075.2.12  raeburn  5754:     # Explicit link to get inline menu
                   5755:     my $menu= ($no_inline_link?''
                   5756:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5757: 
                   5758:     if ($dc_info) {
                   5759:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5760:     }
                   5761: 
1.1075.2.38  raeburn  5762:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5763:     unless ($public) {
                   5764:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5765:                                 undef,'LC_menubuttons_link');
                   5766:     }
                   5767: 
1.1075.2.12  raeburn  5768:     unless ($env{'form.inhibitmenu'}) {
                   5769:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5770:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5771:                        <li>$help</li>
1.1075.2.12  raeburn  5772:                        <li>$menu</li>
                   5773:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5774:     }
1.1075.2.13  raeburn  5775:     if ($env{'request.state'} eq 'construct') {
                   5776:         if (!$public){
                   5777:             if ($env{'request.state'} eq 'construct') {
                   5778:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5779:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5780:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5781:                             &Apache::lonmenu::innerregister($forcereg,
                   5782:                                                             $args->{'bread_crumbs'});
                   5783:             }
                   5784:         }
                   5785:     }
1.1075.2.21  raeburn  5786:     return $bodytag."\n".$funclist;
1.182     matthew  5787: }
                   5788: 
1.917     raeburn  5789: sub dc_courseid_toggle {
                   5790:     my ($dc_info) = @_;
1.980     raeburn  5791:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5792:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5793:            &mt('(More ...)').'</a></span>'.
                   5794:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5795: }
                   5796: 
1.330     albertel 5797: sub make_attr_string {
                   5798:     my ($register,$attr_ref) = @_;
                   5799: 
                   5800:     if ($attr_ref && !ref($attr_ref)) {
                   5801: 	die("addentries Must be a hash ref ".
                   5802: 	    join(':',caller(1))." ".
                   5803: 	    join(':',caller(0))." ");
                   5804:     }
                   5805: 
                   5806:     if ($register) {
1.339     albertel 5807: 	my ($on_load,$on_unload);
                   5808: 	foreach my $key (keys(%{$attr_ref})) {
                   5809: 	    if      (lc($key) eq 'onload') {
                   5810: 		$on_load.=$attr_ref->{$key}.';';
                   5811: 		delete($attr_ref->{$key});
                   5812: 
                   5813: 	    } elsif (lc($key) eq 'onunload') {
                   5814: 		$on_unload.=$attr_ref->{$key}.';';
                   5815: 		delete($attr_ref->{$key});
                   5816: 	    }
                   5817: 	}
1.1075.2.12  raeburn  5818:         if ($env{'environment.remote'} eq 'on') {
                   5819:             $attr_ref->{'onload'}  =
                   5820:                 &Apache::lonmenu::loadevents().  $on_load;
                   5821:             $attr_ref->{'onunload'}=
                   5822:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5823:         } else {  
                   5824: 	    $attr_ref->{'onload'}  = $on_load;
                   5825: 	    $attr_ref->{'onunload'}= $on_unload;
                   5826:         }
1.330     albertel 5827:     }
1.339     albertel 5828: 
1.330     albertel 5829:     my $attr_string;
1.1075.2.56  raeburn  5830:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5831: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5832:     }
                   5833:     return $attr_string;
                   5834: }
                   5835: 
                   5836: 
1.182     matthew  5837: ###############################################
1.251     albertel 5838: ###############################################
                   5839: 
                   5840: =pod
                   5841: 
                   5842: =item * &endbodytag()
                   5843: 
                   5844: Returns a uniform footer for LON-CAPA web pages.
                   5845: 
1.635     raeburn  5846: Inputs: 1 - optional reference to an args hash
                   5847: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5848: a 'Continue' link is not displayed if the page contains an
                   5849: internal redirect in the <head></head> section,
                   5850: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5851: 
                   5852: =cut
                   5853: 
                   5854: sub endbodytag {
1.635     raeburn  5855:     my ($args) = @_;
1.1075.2.6  raeburn  5856:     my $endbodytag;
                   5857:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5858:         $endbodytag='</body>';
                   5859:     }
1.315     albertel 5860:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5861:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5862: 	    $endbodytag=
                   5863: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5864: 	        &mt('Continue').'</a>'.
                   5865: 	        $endbodytag;
                   5866:         }
1.315     albertel 5867:     }
1.251     albertel 5868:     return $endbodytag;
                   5869: }
                   5870: 
1.352     albertel 5871: =pod
                   5872: 
                   5873: =item * &standard_css()
                   5874: 
                   5875: Returns a style sheet
                   5876: 
                   5877: Inputs: (all optional)
                   5878:             domain         -> force to color decorate a page for a specific
                   5879:                                domain
                   5880:             function       -> force usage of a specific rolish color scheme
                   5881:             bgcolor        -> override the default page bgcolor
                   5882: 
                   5883: =cut
                   5884: 
1.343     albertel 5885: sub standard_css {
1.345     albertel 5886:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5887:     $function  = &get_users_function() if (!$function);
                   5888:     my $img    = &designparm($function.'.img',   $domain);
                   5889:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5890:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5891:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5892: #second colour for later usage
1.345     albertel 5893:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5894:     my $pgbg_or_bgcolor =
                   5895: 	         $bgcolor ||
1.352     albertel 5896: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5897:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5898:     my $alink  = &designparm($function.'.alink', $domain);
                   5899:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5900:     my $link   = &designparm($function.'.link',  $domain);
                   5901: 
1.602     albertel 5902:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5903:     my $mono                 = 'monospace';
1.850     bisitz   5904:     my $data_table_head      = $sidebg;
                   5905:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5906:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5907:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5908:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5909:     my $mail_new             = '#FFBB77';
                   5910:     my $mail_new_hover       = '#DD9955';
                   5911:     my $mail_read            = '#BBBB77';
                   5912:     my $mail_read_hover      = '#999944';
                   5913:     my $mail_replied         = '#AAAA88';
                   5914:     my $mail_replied_hover   = '#888855';
                   5915:     my $mail_other           = '#99BBBB';
                   5916:     my $mail_other_hover     = '#669999';
1.391     albertel 5917:     my $table_header         = '#DDDDDD';
1.489     raeburn  5918:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5919:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5920:     my $button_hover         = '#BF2317';
1.392     albertel 5921: 
1.608     albertel 5922:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5923:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5924:                                              : '0 3px 0 4px';
1.448     albertel 5925: 
1.523     albertel 5926: 
1.343     albertel 5927:     return <<END;
1.947     droeschl 5928: 
                   5929: /* needed for iframe to allow 100% height in FF */
                   5930: body, html { 
                   5931:     margin: 0;
                   5932:     padding: 0 0.5%;
                   5933:     height: 99%; /* to avoid scrollbars */
                   5934: }
                   5935: 
1.795     www      5936: body {
1.911     bisitz   5937:   font-family: $sans;
                   5938:   line-height:130%;
                   5939:   font-size:0.83em;
                   5940:   color:$font;
1.795     www      5941: }
                   5942: 
1.959     onken    5943: a:focus,
                   5944: a:focus img {
1.795     www      5945:   color: red;
                   5946: }
1.698     harmsja  5947: 
1.911     bisitz   5948: form, .inline {
                   5949:   display: inline;
1.795     www      5950: }
1.721     harmsja  5951: 
1.795     www      5952: .LC_right {
1.911     bisitz   5953:   text-align:right;
1.795     www      5954: }
                   5955: 
                   5956: .LC_middle {
1.911     bisitz   5957:   vertical-align:middle;
1.795     www      5958: }
1.721     harmsja  5959: 
1.1075.2.38  raeburn  5960: .LC_floatleft {
                   5961:   float: left;
                   5962: }
                   5963: 
                   5964: .LC_floatright {
                   5965:   float: right;
                   5966: }
                   5967: 
1.911     bisitz   5968: .LC_400Box {
                   5969:   width:400px;
                   5970: }
1.721     harmsja  5971: 
1.947     droeschl 5972: .LC_iframecontainer {
                   5973:     width: 98%;
                   5974:     margin: 0;
                   5975:     position: fixed;
                   5976:     top: 8.5em;
                   5977:     bottom: 0;
                   5978: }
                   5979: 
                   5980: .LC_iframecontainer iframe{
                   5981:     border: none;
                   5982:     width: 100%;
                   5983:     height: 100%;
                   5984: }
                   5985: 
1.778     bisitz   5986: .LC_filename {
                   5987:   font-family: $mono;
                   5988:   white-space:pre;
1.921     bisitz   5989:   font-size: 120%;
1.778     bisitz   5990: }
                   5991: 
                   5992: .LC_fileicon {
                   5993:   border: none;
                   5994:   height: 1.3em;
                   5995:   vertical-align: text-bottom;
                   5996:   margin-right: 0.3em;
                   5997:   text-decoration:none;
                   5998: }
                   5999: 
1.1008    www      6000: .LC_setting {
                   6001:   text-decoration:underline;
                   6002: }
                   6003: 
1.350     albertel 6004: .LC_error {
                   6005:   color: red;
                   6006: }
1.795     www      6007: 
1.1075.2.15  raeburn  6008: .LC_warning {
                   6009:   color: darkorange;
                   6010: }
                   6011: 
1.457     albertel 6012: .LC_diff_removed {
1.733     bisitz   6013:   color: red;
1.394     albertel 6014: }
1.532     albertel 6015: 
                   6016: .LC_info,
1.457     albertel 6017: .LC_success,
                   6018: .LC_diff_added {
1.350     albertel 6019:   color: green;
                   6020: }
1.795     www      6021: 
1.802     bisitz   6022: div.LC_confirm_box {
                   6023:   background-color: #FAFAFA;
                   6024:   border: 1px solid $lg_border_color;
                   6025:   margin-right: 0;
                   6026:   padding: 5px;
                   6027: }
                   6028: 
                   6029: div.LC_confirm_box .LC_error img,
                   6030: div.LC_confirm_box .LC_success img {
                   6031:   vertical-align: middle;
                   6032: }
                   6033: 
1.1075.2.108  raeburn  6034: .LC_maxwidth {
                   6035:   max-width: 100%;
                   6036:   height: auto;
                   6037: }
                   6038: 
                   6039: .LC_textsize_mobile {
                   6040:   \@media only screen and (max-device-width: 480px) {
                   6041:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6042:   }
                   6043: }
                   6044: 
1.440     albertel 6045: .LC_icon {
1.771     droeschl 6046:   border: none;
1.790     droeschl 6047:   vertical-align: middle;
1.771     droeschl 6048: }
                   6049: 
1.543     albertel 6050: .LC_docs_spacer {
                   6051:   width: 25px;
                   6052:   height: 1px;
1.771     droeschl 6053:   border: none;
1.543     albertel 6054: }
1.346     albertel 6055: 
1.532     albertel 6056: .LC_internal_info {
1.735     bisitz   6057:   color: #999999;
1.532     albertel 6058: }
                   6059: 
1.794     www      6060: .LC_discussion {
1.1050    www      6061:   background: $data_table_dark;
1.911     bisitz   6062:   border: 1px solid black;
                   6063:   margin: 2px;
1.794     www      6064: }
                   6065: 
                   6066: .LC_disc_action_left {
1.1050    www      6067:   background: $sidebg;
1.911     bisitz   6068:   text-align: left;
1.1050    www      6069:   padding: 4px;
                   6070:   margin: 2px;
1.794     www      6071: }
                   6072: 
                   6073: .LC_disc_action_right {
1.1050    www      6074:   background: $sidebg;
1.911     bisitz   6075:   text-align: right;
1.1050    www      6076:   padding: 4px;
                   6077:   margin: 2px;
1.794     www      6078: }
                   6079: 
                   6080: .LC_disc_new_item {
1.911     bisitz   6081:   background: white;
                   6082:   border: 2px solid red;
1.1050    www      6083:   margin: 4px;
                   6084:   padding: 4px;
1.794     www      6085: }
                   6086: 
                   6087: .LC_disc_old_item {
1.911     bisitz   6088:   background: white;
1.1050    www      6089:   margin: 4px;
                   6090:   padding: 4px;
1.794     www      6091: }
                   6092: 
1.458     albertel 6093: table.LC_pastsubmission {
                   6094:   border: 1px solid black;
                   6095:   margin: 2px;
                   6096: }
                   6097: 
1.924     bisitz   6098: table#LC_menubuttons {
1.345     albertel 6099:   width: 100%;
                   6100:   background: $pgbg;
1.392     albertel 6101:   border: 2px;
1.402     albertel 6102:   border-collapse: separate;
1.803     bisitz   6103:   padding: 0;
1.345     albertel 6104: }
1.392     albertel 6105: 
1.801     tempelho 6106: table#LC_title_bar a {
                   6107:   color: $fontmenu;
                   6108: }
1.836     bisitz   6109: 
1.807     droeschl 6110: table#LC_title_bar {
1.819     tempelho 6111:   clear: both;
1.836     bisitz   6112:   display: none;
1.807     droeschl 6113: }
                   6114: 
1.795     www      6115: table#LC_title_bar,
1.933     droeschl 6116: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6117: table#LC_title_bar.LC_with_remote {
1.359     albertel 6118:   width: 100%;
1.392     albertel 6119:   border-color: $pgbg;
                   6120:   border-style: solid;
                   6121:   border-width: $border;
1.379     albertel 6122:   background: $pgbg;
1.801     tempelho 6123:   color: $fontmenu;
1.392     albertel 6124:   border-collapse: collapse;
1.803     bisitz   6125:   padding: 0;
1.819     tempelho 6126:   margin: 0;
1.359     albertel 6127: }
1.795     www      6128: 
1.933     droeschl 6129: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6130:     margin: 0;
                   6131:     padding: 0;
1.933     droeschl 6132:     position: relative;
                   6133:     list-style: none;
1.913     droeschl 6134: }
1.933     droeschl 6135: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6136:     display: inline;
                   6137: }
1.933     droeschl 6138: 
                   6139: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6140:     padding: 0;
1.933     droeschl 6141:     margin: 0;
                   6142:     float: left;
1.913     droeschl 6143: }
1.933     droeschl 6144: .LC_breadcrumb_tools_tools {
                   6145:     padding: 0;
                   6146:     margin: 0;
1.913     droeschl 6147:     float: right;
                   6148: }
                   6149: 
1.359     albertel 6150: table#LC_title_bar td {
                   6151:   background: $tabbg;
                   6152: }
1.795     www      6153: 
1.911     bisitz   6154: table#LC_menubuttons img {
1.803     bisitz   6155:   border: none;
1.346     albertel 6156: }
1.795     www      6157: 
1.842     droeschl 6158: .LC_breadcrumbs_component {
1.911     bisitz   6159:   float: right;
                   6160:   margin: 0 1em;
1.357     albertel 6161: }
1.842     droeschl 6162: .LC_breadcrumbs_component img {
1.911     bisitz   6163:   vertical-align: middle;
1.777     tempelho 6164: }
1.795     www      6165: 
1.1075.2.108  raeburn  6166: .LC_breadcrumbs_hoverable {
                   6167:   background: $sidebg;
                   6168: }
                   6169: 
1.383     albertel 6170: td.LC_table_cell_checkbox {
                   6171:   text-align: center;
                   6172: }
1.795     www      6173: 
                   6174: .LC_fontsize_small {
1.911     bisitz   6175:   font-size: 70%;
1.705     tempelho 6176: }
                   6177: 
1.844     bisitz   6178: #LC_breadcrumbs {
1.911     bisitz   6179:   clear:both;
                   6180:   background: $sidebg;
                   6181:   border-bottom: 1px solid $lg_border_color;
                   6182:   line-height: 2.5em;
1.933     droeschl 6183:   overflow: hidden;
1.911     bisitz   6184:   margin: 0;
                   6185:   padding: 0;
1.995     raeburn  6186:   text-align: left;
1.819     tempelho 6187: }
1.862     bisitz   6188: 
1.1075.2.16  raeburn  6189: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6190:   clear:both;
                   6191:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6192:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6193:   margin: 0 0 10px 0;
1.966     bisitz   6194:   padding: 3px;
1.995     raeburn  6195:   text-align: left;
1.822     bisitz   6196: }
                   6197: 
1.795     www      6198: .LC_fontsize_medium {
1.911     bisitz   6199:   font-size: 85%;
1.705     tempelho 6200: }
                   6201: 
1.795     www      6202: .LC_fontsize_large {
1.911     bisitz   6203:   font-size: 120%;
1.705     tempelho 6204: }
                   6205: 
1.346     albertel 6206: .LC_menubuttons_inline_text {
                   6207:   color: $font;
1.698     harmsja  6208:   font-size: 90%;
1.701     harmsja  6209:   padding-left:3px;
1.346     albertel 6210: }
                   6211: 
1.934     droeschl 6212: .LC_menubuttons_inline_text img{
                   6213:   vertical-align: middle;
                   6214: }
                   6215: 
1.1051    www      6216: li.LC_menubuttons_inline_text img {
1.951     onken    6217:   cursor:pointer;
1.1002    droeschl 6218:   text-decoration: none;
1.951     onken    6219: }
                   6220: 
1.526     www      6221: .LC_menubuttons_link {
                   6222:   text-decoration: none;
                   6223: }
1.795     www      6224: 
1.522     albertel 6225: .LC_menubuttons_category {
1.521     www      6226:   color: $font;
1.526     www      6227:   background: $pgbg;
1.521     www      6228:   font-size: larger;
                   6229:   font-weight: bold;
                   6230: }
                   6231: 
1.346     albertel 6232: td.LC_menubuttons_text {
1.911     bisitz   6233:   color: $font;
1.346     albertel 6234: }
1.706     harmsja  6235: 
1.346     albertel 6236: .LC_current_location {
                   6237:   background: $tabbg;
                   6238: }
1.795     www      6239: 
1.1075.2.134  raeburn  6240: td.LC_zero_height {
                   6241:   line-height: 0;
                   6242:   cellpadding: 0;
                   6243: }
                   6244: 
1.938     bisitz   6245: table.LC_data_table {
1.347     albertel 6246:   border: 1px solid #000000;
1.402     albertel 6247:   border-collapse: separate;
1.426     albertel 6248:   border-spacing: 1px;
1.610     albertel 6249:   background: $pgbg;
1.347     albertel 6250: }
1.795     www      6251: 
1.422     albertel 6252: .LC_data_table_dense {
                   6253:   font-size: small;
                   6254: }
1.795     www      6255: 
1.507     raeburn  6256: table.LC_nested_outer {
                   6257:   border: 1px solid #000000;
1.589     raeburn  6258:   border-collapse: collapse;
1.803     bisitz   6259:   border-spacing: 0;
1.507     raeburn  6260:   width: 100%;
                   6261: }
1.795     www      6262: 
1.879     raeburn  6263: table.LC_innerpickbox,
1.507     raeburn  6264: table.LC_nested {
1.803     bisitz   6265:   border: none;
1.589     raeburn  6266:   border-collapse: collapse;
1.803     bisitz   6267:   border-spacing: 0;
1.507     raeburn  6268:   width: 100%;
                   6269: }
1.795     www      6270: 
1.911     bisitz   6271: table.LC_data_table tr th,
                   6272: table.LC_calendar tr th,
1.879     raeburn  6273: table.LC_prior_tries tr th,
                   6274: table.LC_innerpickbox tr th {
1.349     albertel 6275:   font-weight: bold;
                   6276:   background-color: $data_table_head;
1.801     tempelho 6277:   color:$fontmenu;
1.701     harmsja  6278:   font-size:90%;
1.347     albertel 6279: }
1.795     www      6280: 
1.879     raeburn  6281: table.LC_innerpickbox tr th,
                   6282: table.LC_innerpickbox tr td {
                   6283:   vertical-align: top;
                   6284: }
                   6285: 
1.711     raeburn  6286: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6287:   background-color: #CCCCCC;
1.711     raeburn  6288:   font-weight: bold;
                   6289:   text-align: left;
                   6290: }
1.795     www      6291: 
1.912     bisitz   6292: table.LC_data_table tr.LC_odd_row > td {
                   6293:   background-color: $data_table_light;
                   6294:   padding: 2px;
                   6295:   vertical-align: top;
                   6296: }
                   6297: 
1.809     bisitz   6298: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6299:   background-color: $data_table_light;
1.912     bisitz   6300:   vertical-align: top;
                   6301: }
                   6302: 
                   6303: table.LC_data_table tr.LC_even_row > td {
                   6304:   background-color: $data_table_dark;
1.425     albertel 6305:   padding: 2px;
1.900     bisitz   6306:   vertical-align: top;
1.347     albertel 6307: }
1.795     www      6308: 
1.809     bisitz   6309: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6310:   background-color: $data_table_dark;
1.900     bisitz   6311:   vertical-align: top;
1.347     albertel 6312: }
1.795     www      6313: 
1.425     albertel 6314: table.LC_data_table tr.LC_data_table_highlight td {
                   6315:   background-color: $data_table_darker;
                   6316: }
1.795     www      6317: 
1.639     raeburn  6318: table.LC_data_table tr td.LC_leftcol_header {
                   6319:   background-color: $data_table_head;
                   6320:   font-weight: bold;
                   6321: }
1.795     www      6322: 
1.451     albertel 6323: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6324: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6325:   font-weight: bold;
                   6326:   font-style: italic;
                   6327:   text-align: center;
                   6328:   padding: 8px;
1.347     albertel 6329: }
1.795     www      6330: 
1.1075.2.30  raeburn  6331: table.LC_data_table tr.LC_empty_row td,
                   6332: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6333:   background-color: $sidebg;
                   6334: }
                   6335: 
                   6336: table.LC_nested tr.LC_empty_row td {
                   6337:   background-color: #FFFFFF;
                   6338: }
                   6339: 
1.890     droeschl 6340: table.LC_caption {
                   6341: }
                   6342: 
1.507     raeburn  6343: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6344:   padding: 4ex
                   6345: }
1.795     www      6346: 
1.507     raeburn  6347: table.LC_nested_outer tr th {
                   6348:   font-weight: bold;
1.801     tempelho 6349:   color:$fontmenu;
1.507     raeburn  6350:   background-color: $data_table_head;
1.701     harmsja  6351:   font-size: small;
1.507     raeburn  6352:   border-bottom: 1px solid #000000;
                   6353: }
1.795     www      6354: 
1.507     raeburn  6355: table.LC_nested_outer tr td.LC_subheader {
                   6356:   background-color: $data_table_head;
                   6357:   font-weight: bold;
                   6358:   font-size: small;
                   6359:   border-bottom: 1px solid #000000;
                   6360:   text-align: right;
1.451     albertel 6361: }
1.795     www      6362: 
1.507     raeburn  6363: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6364:   background-color: #CCCCCC;
1.451     albertel 6365:   font-weight: bold;
                   6366:   font-size: small;
1.507     raeburn  6367:   text-align: center;
                   6368: }
1.795     www      6369: 
1.589     raeburn  6370: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6371: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6372:   text-align: left;
1.451     albertel 6373: }
1.795     www      6374: 
1.507     raeburn  6375: table.LC_nested td {
1.735     bisitz   6376:   background-color: #FFFFFF;
1.451     albertel 6377:   font-size: small;
1.507     raeburn  6378: }
1.795     www      6379: 
1.507     raeburn  6380: table.LC_nested_outer tr th.LC_right_item,
                   6381: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6382: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6383: table.LC_nested tr td.LC_right_item {
1.451     albertel 6384:   text-align: right;
                   6385: }
                   6386: 
1.507     raeburn  6387: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6388:   background-color: #EEEEEE;
1.451     albertel 6389: }
                   6390: 
1.473     raeburn  6391: table.LC_createuser {
                   6392: }
                   6393: 
                   6394: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6395:   font-size: small;
1.473     raeburn  6396: }
                   6397: 
                   6398: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6399:   background-color: #CCCCCC;
1.473     raeburn  6400:   font-weight: bold;
                   6401:   text-align: center;
                   6402: }
                   6403: 
1.349     albertel 6404: table.LC_calendar {
                   6405:   border: 1px solid #000000;
                   6406:   border-collapse: collapse;
1.917     raeburn  6407:   width: 98%;
1.349     albertel 6408: }
1.795     www      6409: 
1.349     albertel 6410: table.LC_calendar_pickdate {
                   6411:   font-size: xx-small;
                   6412: }
1.795     www      6413: 
1.349     albertel 6414: table.LC_calendar tr td {
                   6415:   border: 1px solid #000000;
                   6416:   vertical-align: top;
1.917     raeburn  6417:   width: 14%;
1.349     albertel 6418: }
1.795     www      6419: 
1.349     albertel 6420: table.LC_calendar tr td.LC_calendar_day_empty {
                   6421:   background-color: $data_table_dark;
                   6422: }
1.795     www      6423: 
1.779     bisitz   6424: table.LC_calendar tr td.LC_calendar_day_current {
                   6425:   background-color: $data_table_highlight;
1.777     tempelho 6426: }
1.795     www      6427: 
1.938     bisitz   6428: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6429:   background-color: $mail_new;
                   6430: }
1.795     www      6431: 
1.938     bisitz   6432: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6433:   background-color: $mail_new_hover;
                   6434: }
1.795     www      6435: 
1.938     bisitz   6436: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6437:   background-color: $mail_read;
                   6438: }
1.795     www      6439: 
1.938     bisitz   6440: /*
                   6441: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6442:   background-color: $mail_read_hover;
                   6443: }
1.938     bisitz   6444: */
1.795     www      6445: 
1.938     bisitz   6446: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6447:   background-color: $mail_replied;
                   6448: }
1.795     www      6449: 
1.938     bisitz   6450: /*
                   6451: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6452:   background-color: $mail_replied_hover;
                   6453: }
1.938     bisitz   6454: */
1.795     www      6455: 
1.938     bisitz   6456: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6457:   background-color: $mail_other;
                   6458: }
1.795     www      6459: 
1.938     bisitz   6460: /*
                   6461: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6462:   background-color: $mail_other_hover;
                   6463: }
1.938     bisitz   6464: */
1.494     raeburn  6465: 
1.777     tempelho 6466: table.LC_data_table tr > td.LC_browser_file,
                   6467: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6468:   background: #AAEE77;
1.389     albertel 6469: }
1.795     www      6470: 
1.777     tempelho 6471: table.LC_data_table tr > td.LC_browser_file_locked,
                   6472: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6473:   background: #FFAA99;
1.387     albertel 6474: }
1.795     www      6475: 
1.777     tempelho 6476: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6477:   background: #888888;
1.779     bisitz   6478: }
1.795     www      6479: 
1.777     tempelho 6480: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6481: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6482:   background: #F8F866;
1.777     tempelho 6483: }
1.795     www      6484: 
1.696     bisitz   6485: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6486:   background: #E0E8FF;
1.387     albertel 6487: }
1.696     bisitz   6488: 
1.707     bisitz   6489: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6490:   /* background: #77FF77; */
1.707     bisitz   6491: }
1.795     www      6492: 
1.707     bisitz   6493: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6494:   border-right: 8px solid #FFFF77;
1.707     bisitz   6495: }
1.795     www      6496: 
1.707     bisitz   6497: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6498:   border-right: 8px solid #FFAA77;
1.707     bisitz   6499: }
1.795     www      6500: 
1.707     bisitz   6501: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6502:   border-right: 8px solid #FF7777;
1.707     bisitz   6503: }
1.795     www      6504: 
1.707     bisitz   6505: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6506:   border-right: 8px solid #AAFF77;
1.707     bisitz   6507: }
1.795     www      6508: 
1.707     bisitz   6509: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6510:   border-right: 8px solid #11CC55;
1.707     bisitz   6511: }
                   6512: 
1.388     albertel 6513: span.LC_current_location {
1.701     harmsja  6514:   font-size:larger;
1.388     albertel 6515:   background: $pgbg;
                   6516: }
1.387     albertel 6517: 
1.1029    www      6518: span.LC_current_nav_location {
                   6519:   font-weight:bold;
                   6520:   background: $sidebg;
                   6521: }
                   6522: 
1.395     albertel 6523: span.LC_parm_menu_item {
                   6524:   font-size: larger;
                   6525: }
1.795     www      6526: 
1.395     albertel 6527: span.LC_parm_scope_all {
                   6528:   color: red;
                   6529: }
1.795     www      6530: 
1.395     albertel 6531: span.LC_parm_scope_folder {
                   6532:   color: green;
                   6533: }
1.795     www      6534: 
1.395     albertel 6535: span.LC_parm_scope_resource {
                   6536:   color: orange;
                   6537: }
1.795     www      6538: 
1.395     albertel 6539: span.LC_parm_part {
                   6540:   color: blue;
                   6541: }
1.795     www      6542: 
1.911     bisitz   6543: span.LC_parm_folder,
                   6544: span.LC_parm_symb {
1.395     albertel 6545:   font-size: x-small;
                   6546:   font-family: $mono;
                   6547:   color: #AAAAAA;
                   6548: }
                   6549: 
1.977     bisitz   6550: ul.LC_parm_parmlist li {
                   6551:   display: inline-block;
                   6552:   padding: 0.3em 0.8em;
                   6553:   vertical-align: top;
                   6554:   width: 150px;
                   6555:   border-top:1px solid $lg_border_color;
                   6556: }
                   6557: 
1.795     www      6558: td.LC_parm_overview_level_menu,
                   6559: td.LC_parm_overview_map_menu,
                   6560: td.LC_parm_overview_parm_selectors,
                   6561: td.LC_parm_overview_restrictions  {
1.396     albertel 6562:   border: 1px solid black;
                   6563:   border-collapse: collapse;
                   6564: }
1.795     www      6565: 
1.396     albertel 6566: table.LC_parm_overview_restrictions td {
                   6567:   border-width: 1px 4px 1px 4px;
                   6568:   border-style: solid;
                   6569:   border-color: $pgbg;
                   6570:   text-align: center;
                   6571: }
1.795     www      6572: 
1.396     albertel 6573: table.LC_parm_overview_restrictions th {
                   6574:   background: $tabbg;
                   6575:   border-width: 1px 4px 1px 4px;
                   6576:   border-style: solid;
                   6577:   border-color: $pgbg;
                   6578: }
1.795     www      6579: 
1.398     albertel 6580: table#LC_helpmenu {
1.803     bisitz   6581:   border: none;
1.398     albertel 6582:   height: 55px;
1.803     bisitz   6583:   border-spacing: 0;
1.398     albertel 6584: }
                   6585: 
                   6586: table#LC_helpmenu fieldset legend {
                   6587:   font-size: larger;
                   6588: }
1.795     www      6589: 
1.397     albertel 6590: table#LC_helpmenu_links {
                   6591:   width: 100%;
                   6592:   border: 1px solid black;
                   6593:   background: $pgbg;
1.803     bisitz   6594:   padding: 0;
1.397     albertel 6595:   border-spacing: 1px;
                   6596: }
1.795     www      6597: 
1.397     albertel 6598: table#LC_helpmenu_links tr td {
                   6599:   padding: 1px;
                   6600:   background: $tabbg;
1.399     albertel 6601:   text-align: center;
                   6602:   font-weight: bold;
1.397     albertel 6603: }
1.396     albertel 6604: 
1.795     www      6605: table#LC_helpmenu_links a:link,
                   6606: table#LC_helpmenu_links a:visited,
1.397     albertel 6607: table#LC_helpmenu_links a:active {
                   6608:   text-decoration: none;
                   6609:   color: $font;
                   6610: }
1.795     www      6611: 
1.397     albertel 6612: table#LC_helpmenu_links a:hover {
                   6613:   text-decoration: underline;
                   6614:   color: $vlink;
                   6615: }
1.396     albertel 6616: 
1.417     albertel 6617: .LC_chrt_popup_exists {
                   6618:   border: 1px solid #339933;
                   6619:   margin: -1px;
                   6620: }
1.795     www      6621: 
1.417     albertel 6622: .LC_chrt_popup_up {
                   6623:   border: 1px solid yellow;
                   6624:   margin: -1px;
                   6625: }
1.795     www      6626: 
1.417     albertel 6627: .LC_chrt_popup {
                   6628:   border: 1px solid #8888FF;
                   6629:   background: #CCCCFF;
                   6630: }
1.795     www      6631: 
1.421     albertel 6632: table.LC_pick_box {
                   6633:   border-collapse: separate;
                   6634:   background: white;
                   6635:   border: 1px solid black;
                   6636:   border-spacing: 1px;
                   6637: }
1.795     www      6638: 
1.421     albertel 6639: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6640:   background: $sidebg;
1.421     albertel 6641:   font-weight: bold;
1.900     bisitz   6642:   text-align: left;
1.740     bisitz   6643:   vertical-align: top;
1.421     albertel 6644:   width: 184px;
                   6645:   padding: 8px;
                   6646: }
1.795     www      6647: 
1.579     raeburn  6648: table.LC_pick_box td.LC_pick_box_value {
                   6649:   text-align: left;
                   6650:   padding: 8px;
                   6651: }
1.795     www      6652: 
1.579     raeburn  6653: table.LC_pick_box td.LC_pick_box_select {
                   6654:   text-align: left;
                   6655:   padding: 8px;
                   6656: }
1.795     www      6657: 
1.424     albertel 6658: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6659:   padding: 0;
1.421     albertel 6660:   height: 1px;
                   6661:   background: black;
                   6662: }
1.795     www      6663: 
1.421     albertel 6664: table.LC_pick_box td.LC_pick_box_submit {
                   6665:   text-align: right;
                   6666: }
1.795     www      6667: 
1.579     raeburn  6668: table.LC_pick_box td.LC_evenrow_value {
                   6669:   text-align: left;
                   6670:   padding: 8px;
                   6671:   background-color: $data_table_light;
                   6672: }
1.795     www      6673: 
1.579     raeburn  6674: table.LC_pick_box td.LC_oddrow_value {
                   6675:   text-align: left;
                   6676:   padding: 8px;
                   6677:   background-color: $data_table_light;
                   6678: }
1.795     www      6679: 
1.579     raeburn  6680: span.LC_helpform_receipt_cat {
                   6681:   font-weight: bold;
                   6682: }
1.795     www      6683: 
1.424     albertel 6684: table.LC_group_priv_box {
                   6685:   background: white;
                   6686:   border: 1px solid black;
                   6687:   border-spacing: 1px;
                   6688: }
1.795     www      6689: 
1.424     albertel 6690: table.LC_group_priv_box td.LC_pick_box_title {
                   6691:   background: $tabbg;
                   6692:   font-weight: bold;
                   6693:   text-align: right;
                   6694:   width: 184px;
                   6695: }
1.795     www      6696: 
1.424     albertel 6697: table.LC_group_priv_box td.LC_groups_fixed {
                   6698:   background: $data_table_light;
                   6699:   text-align: center;
                   6700: }
1.795     www      6701: 
1.424     albertel 6702: table.LC_group_priv_box td.LC_groups_optional {
                   6703:   background: $data_table_dark;
                   6704:   text-align: center;
                   6705: }
1.795     www      6706: 
1.424     albertel 6707: table.LC_group_priv_box td.LC_groups_functionality {
                   6708:   background: $data_table_darker;
                   6709:   text-align: center;
                   6710:   font-weight: bold;
                   6711: }
1.795     www      6712: 
1.424     albertel 6713: table.LC_group_priv td {
                   6714:   text-align: left;
1.803     bisitz   6715:   padding: 0;
1.424     albertel 6716: }
                   6717: 
                   6718: .LC_navbuttons {
                   6719:   margin: 2ex 0ex 2ex 0ex;
                   6720: }
1.795     www      6721: 
1.423     albertel 6722: .LC_topic_bar {
                   6723:   font-weight: bold;
                   6724:   background: $tabbg;
1.918     wenzelju 6725:   margin: 1em 0em 1em 2em;
1.805     bisitz   6726:   padding: 3px;
1.918     wenzelju 6727:   font-size: 1.2em;
1.423     albertel 6728: }
1.795     www      6729: 
1.423     albertel 6730: .LC_topic_bar span {
1.918     wenzelju 6731:   left: 0.5em;
                   6732:   position: absolute;
1.423     albertel 6733:   vertical-align: middle;
1.918     wenzelju 6734:   font-size: 1.2em;
1.423     albertel 6735: }
1.795     www      6736: 
1.423     albertel 6737: table.LC_course_group_status {
                   6738:   margin: 20px;
                   6739: }
1.795     www      6740: 
1.423     albertel 6741: table.LC_status_selector td {
                   6742:   vertical-align: top;
                   6743:   text-align: center;
1.424     albertel 6744:   padding: 4px;
                   6745: }
1.795     www      6746: 
1.599     albertel 6747: div.LC_feedback_link {
1.616     albertel 6748:   clear: both;
1.829     kalberla 6749:   background: $sidebg;
1.779     bisitz   6750:   width: 100%;
1.829     kalberla 6751:   padding-bottom: 10px;
                   6752:   border: 1px $tabbg solid;
1.833     kalberla 6753:   height: 22px;
                   6754:   line-height: 22px;
                   6755:   padding-top: 5px;
                   6756: }
                   6757: 
                   6758: div.LC_feedback_link img {
                   6759:   height: 22px;
1.867     kalberla 6760:   vertical-align:middle;
1.829     kalberla 6761: }
                   6762: 
1.911     bisitz   6763: div.LC_feedback_link a {
1.829     kalberla 6764:   text-decoration: none;
1.489     raeburn  6765: }
1.795     www      6766: 
1.867     kalberla 6767: div.LC_comblock {
1.911     bisitz   6768:   display:inline;
1.867     kalberla 6769:   color:$font;
                   6770:   font-size:90%;
                   6771: }
                   6772: 
                   6773: div.LC_feedback_link div.LC_comblock {
                   6774:   padding-left:5px;
                   6775: }
                   6776: 
                   6777: div.LC_feedback_link div.LC_comblock a {
                   6778:   color:$font;
                   6779: }
                   6780: 
1.489     raeburn  6781: span.LC_feedback_link {
1.858     bisitz   6782:   /* background: $feedback_link_bg; */
1.599     albertel 6783:   font-size: larger;
                   6784: }
1.795     www      6785: 
1.599     albertel 6786: span.LC_message_link {
1.858     bisitz   6787:   /* background: $feedback_link_bg; */
1.599     albertel 6788:   font-size: larger;
                   6789:   position: absolute;
                   6790:   right: 1em;
1.489     raeburn  6791: }
1.421     albertel 6792: 
1.515     albertel 6793: table.LC_prior_tries {
1.524     albertel 6794:   border: 1px solid #000000;
                   6795:   border-collapse: separate;
                   6796:   border-spacing: 1px;
1.515     albertel 6797: }
1.523     albertel 6798: 
1.515     albertel 6799: table.LC_prior_tries td {
1.524     albertel 6800:   padding: 2px;
1.515     albertel 6801: }
1.523     albertel 6802: 
                   6803: .LC_answer_correct {
1.795     www      6804:   background: lightgreen;
                   6805:   color: darkgreen;
                   6806:   padding: 6px;
1.523     albertel 6807: }
1.795     www      6808: 
1.523     albertel 6809: .LC_answer_charged_try {
1.797     www      6810:   background: #FFAAAA;
1.795     www      6811:   color: darkred;
                   6812:   padding: 6px;
1.523     albertel 6813: }
1.795     www      6814: 
1.779     bisitz   6815: .LC_answer_not_charged_try,
1.523     albertel 6816: .LC_answer_no_grade,
                   6817: .LC_answer_late {
1.795     www      6818:   background: lightyellow;
1.523     albertel 6819:   color: black;
1.795     www      6820:   padding: 6px;
1.523     albertel 6821: }
1.795     www      6822: 
1.523     albertel 6823: .LC_answer_previous {
1.795     www      6824:   background: lightblue;
                   6825:   color: darkblue;
                   6826:   padding: 6px;
1.523     albertel 6827: }
1.795     www      6828: 
1.779     bisitz   6829: .LC_answer_no_message {
1.777     tempelho 6830:   background: #FFFFFF;
                   6831:   color: black;
1.795     www      6832:   padding: 6px;
1.779     bisitz   6833: }
1.795     www      6834: 
1.1075.2.140  raeburn  6835: .LC_answer_unknown,
                   6836: .LC_answer_warning {
1.779     bisitz   6837:   background: orange;
                   6838:   color: black;
1.795     www      6839:   padding: 6px;
1.777     tempelho 6840: }
1.795     www      6841: 
1.529     albertel 6842: span.LC_prior_numerical,
                   6843: span.LC_prior_string,
                   6844: span.LC_prior_custom,
                   6845: span.LC_prior_reaction,
                   6846: span.LC_prior_math {
1.925     bisitz   6847:   font-family: $mono;
1.523     albertel 6848:   white-space: pre;
                   6849: }
                   6850: 
1.525     albertel 6851: span.LC_prior_string {
1.925     bisitz   6852:   font-family: $mono;
1.525     albertel 6853:   white-space: pre;
                   6854: }
                   6855: 
1.523     albertel 6856: table.LC_prior_option {
                   6857:   width: 100%;
                   6858:   border-collapse: collapse;
                   6859: }
1.795     www      6860: 
1.911     bisitz   6861: table.LC_prior_rank,
1.795     www      6862: table.LC_prior_match {
1.528     albertel 6863:   border-collapse: collapse;
                   6864: }
1.795     www      6865: 
1.528     albertel 6866: table.LC_prior_option tr td,
                   6867: table.LC_prior_rank tr td,
                   6868: table.LC_prior_match tr td {
1.524     albertel 6869:   border: 1px solid #000000;
1.515     albertel 6870: }
                   6871: 
1.855     bisitz   6872: .LC_nobreak {
1.544     albertel 6873:   white-space: nowrap;
1.519     raeburn  6874: }
                   6875: 
1.576     raeburn  6876: span.LC_cusr_emph {
                   6877:   font-style: italic;
                   6878: }
                   6879: 
1.633     raeburn  6880: span.LC_cusr_subheading {
                   6881:   font-weight: normal;
                   6882:   font-size: 85%;
                   6883: }
                   6884: 
1.861     bisitz   6885: div.LC_docs_entry_move {
1.859     bisitz   6886:   border: 1px solid #BBBBBB;
1.545     albertel 6887:   background: #DDDDDD;
1.861     bisitz   6888:   width: 22px;
1.859     bisitz   6889:   padding: 1px;
                   6890:   margin: 0;
1.545     albertel 6891: }
                   6892: 
1.861     bisitz   6893: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6894: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6895:   font-size: x-small;
                   6896: }
1.795     www      6897: 
1.861     bisitz   6898: .LC_docs_entry_parameter {
                   6899:   white-space: nowrap;
                   6900: }
                   6901: 
1.544     albertel 6902: .LC_docs_copy {
1.545     albertel 6903:   color: #000099;
1.544     albertel 6904: }
1.795     www      6905: 
1.544     albertel 6906: .LC_docs_cut {
1.545     albertel 6907:   color: #550044;
1.544     albertel 6908: }
1.795     www      6909: 
1.544     albertel 6910: .LC_docs_rename {
1.545     albertel 6911:   color: #009900;
1.544     albertel 6912: }
1.795     www      6913: 
1.544     albertel 6914: .LC_docs_remove {
1.545     albertel 6915:   color: #990000;
                   6916: }
                   6917: 
1.1075.2.134  raeburn  6918: .LC_domprefs_email,
1.547     albertel 6919: .LC_docs_reinit_warn,
                   6920: .LC_docs_ext_edit {
                   6921:   font-size: x-small;
                   6922: }
                   6923: 
1.545     albertel 6924: table.LC_docs_adddocs td,
                   6925: table.LC_docs_adddocs th {
                   6926:   border: 1px solid #BBBBBB;
                   6927:   padding: 4px;
                   6928:   background: #DDDDDD;
1.543     albertel 6929: }
                   6930: 
1.584     albertel 6931: table.LC_sty_begin {
                   6932:   background: #BBFFBB;
                   6933: }
1.795     www      6934: 
1.584     albertel 6935: table.LC_sty_end {
                   6936:   background: #FFBBBB;
                   6937: }
                   6938: 
1.589     raeburn  6939: table.LC_double_column {
1.803     bisitz   6940:   border-width: 0;
1.589     raeburn  6941:   border-collapse: collapse;
                   6942:   width: 100%;
                   6943:   padding: 2px;
                   6944: }
                   6945: 
                   6946: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6947:   top: 2px;
1.589     raeburn  6948:   left: 2px;
                   6949:   width: 47%;
                   6950:   vertical-align: top;
                   6951: }
                   6952: 
                   6953: table.LC_double_column tr td.LC_right_col {
                   6954:   top: 2px;
1.779     bisitz   6955:   right: 2px;
1.589     raeburn  6956:   width: 47%;
                   6957:   vertical-align: top;
                   6958: }
                   6959: 
1.591     raeburn  6960: div.LC_left_float {
                   6961:   float: left;
                   6962:   padding-right: 5%;
1.597     albertel 6963:   padding-bottom: 4px;
1.591     raeburn  6964: }
                   6965: 
                   6966: div.LC_clear_float_header {
1.597     albertel 6967:   padding-bottom: 2px;
1.591     raeburn  6968: }
                   6969: 
                   6970: div.LC_clear_float_footer {
1.597     albertel 6971:   padding-top: 10px;
1.591     raeburn  6972:   clear: both;
                   6973: }
                   6974: 
1.597     albertel 6975: div.LC_grade_show_user {
1.941     bisitz   6976: /*  border-left: 5px solid $sidebg; */
                   6977:   border-top: 5px solid #000000;
                   6978:   margin: 50px 0 0 0;
1.936     bisitz   6979:   padding: 15px 0 5px 10px;
1.597     albertel 6980: }
1.795     www      6981: 
1.936     bisitz   6982: div.LC_grade_show_user_odd_row {
1.941     bisitz   6983: /*  border-left: 5px solid #000000; */
                   6984: }
                   6985: 
                   6986: div.LC_grade_show_user div.LC_Box {
                   6987:   margin-right: 50px;
1.597     albertel 6988: }
                   6989: 
                   6990: div.LC_grade_submissions,
                   6991: div.LC_grade_message_center,
1.936     bisitz   6992: div.LC_grade_info_links {
1.597     albertel 6993:   margin: 5px;
                   6994:   width: 99%;
                   6995:   background: #FFFFFF;
                   6996: }
1.795     www      6997: 
1.597     albertel 6998: div.LC_grade_submissions_header,
1.936     bisitz   6999: div.LC_grade_message_center_header {
1.705     tempelho 7000:   font-weight: bold;
                   7001:   font-size: large;
1.597     albertel 7002: }
1.795     www      7003: 
1.597     albertel 7004: div.LC_grade_submissions_body,
1.936     bisitz   7005: div.LC_grade_message_center_body {
1.597     albertel 7006:   border: 1px solid black;
                   7007:   width: 99%;
                   7008:   background: #FFFFFF;
                   7009: }
1.795     www      7010: 
1.613     albertel 7011: table.LC_scantron_action {
                   7012:   width: 100%;
                   7013: }
1.795     www      7014: 
1.613     albertel 7015: table.LC_scantron_action tr th {
1.698     harmsja  7016:   font-weight:bold;
                   7017:   font-style:normal;
1.613     albertel 7018: }
1.795     www      7019: 
1.779     bisitz   7020: .LC_edit_problem_header,
1.614     albertel 7021: div.LC_edit_problem_footer {
1.705     tempelho 7022:   font-weight: normal;
                   7023:   font-size:  medium;
1.602     albertel 7024:   margin: 2px;
1.1060    bisitz   7025:   background-color: $sidebg;
1.600     albertel 7026: }
1.795     www      7027: 
1.600     albertel 7028: div.LC_edit_problem_header,
1.602     albertel 7029: div.LC_edit_problem_header div,
1.614     albertel 7030: div.LC_edit_problem_footer,
                   7031: div.LC_edit_problem_footer div,
1.602     albertel 7032: div.LC_edit_problem_editxml_header,
                   7033: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7034:   z-index: 100;
1.600     albertel 7035: }
1.795     www      7036: 
1.600     albertel 7037: div.LC_edit_problem_header_title {
1.705     tempelho 7038:   font-weight: bold;
                   7039:   font-size: larger;
1.602     albertel 7040:   background: $tabbg;
                   7041:   padding: 3px;
1.1060    bisitz   7042:   margin: 0 0 5px 0;
1.602     albertel 7043: }
1.795     www      7044: 
1.602     albertel 7045: table.LC_edit_problem_header_title {
                   7046:   width: 100%;
1.600     albertel 7047:   background: $tabbg;
1.602     albertel 7048: }
                   7049: 
1.1075.2.112  raeburn  7050: div.LC_edit_actionbar {
                   7051:     background-color: $sidebg;
                   7052:     margin: 0;
                   7053:     padding: 0;
                   7054:     line-height: 200%;
1.602     albertel 7055: }
1.795     www      7056: 
1.1075.2.112  raeburn  7057: div.LC_edit_actionbar div{
                   7058:     padding: 0;
                   7059:     margin: 0;
                   7060:     display: inline-block;
1.600     albertel 7061: }
1.795     www      7062: 
1.1075.2.34  raeburn  7063: .LC_edit_opt {
                   7064:   padding-left: 1em;
                   7065:   white-space: nowrap;
                   7066: }
                   7067: 
1.1075.2.57  raeburn  7068: .LC_edit_problem_latexhelper{
                   7069:     text-align: right;
                   7070: }
                   7071: 
                   7072: #LC_edit_problem_colorful div{
                   7073:     margin-left: 40px;
                   7074: }
                   7075: 
1.1075.2.112  raeburn  7076: #LC_edit_problem_codemirror div{
                   7077:     margin-left: 0px;
                   7078: }
                   7079: 
1.911     bisitz   7080: img.stift {
1.803     bisitz   7081:   border-width: 0;
                   7082:   vertical-align: middle;
1.677     riegler  7083: }
1.680     riegler  7084: 
1.923     bisitz   7085: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7086:   vertical-align: top;
1.777     tempelho 7087: }
1.795     www      7088: 
1.716     raeburn  7089: div.LC_createcourse {
1.911     bisitz   7090:   margin: 10px 10px 10px 10px;
1.716     raeburn  7091: }
                   7092: 
1.917     raeburn  7093: .LC_dccid {
1.1075.2.38  raeburn  7094:   float: right;
1.917     raeburn  7095:   margin: 0.2em 0 0 0;
                   7096:   padding: 0;
                   7097:   font-size: 90%;
                   7098:   display:none;
                   7099: }
                   7100: 
1.897     wenzelju 7101: ol.LC_primary_menu a:hover,
1.721     harmsja  7102: ol#LC_MenuBreadcrumbs a:hover,
                   7103: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7104: ul#LC_secondary_menu a:hover,
1.721     harmsja  7105: .LC_FormSectionClearButton input:hover
1.795     www      7106: ul.LC_TabContent   li:hover a {
1.952     onken    7107:   color:$button_hover;
1.911     bisitz   7108:   text-decoration:none;
1.693     droeschl 7109: }
                   7110: 
1.779     bisitz   7111: h1 {
1.911     bisitz   7112:   padding: 0;
                   7113:   line-height:130%;
1.693     droeschl 7114: }
1.698     harmsja  7115: 
1.911     bisitz   7116: h2,
                   7117: h3,
                   7118: h4,
                   7119: h5,
                   7120: h6 {
                   7121:   margin: 5px 0 5px 0;
                   7122:   padding: 0;
                   7123:   line-height:130%;
1.693     droeschl 7124: }
1.795     www      7125: 
                   7126: .LC_hcell {
1.911     bisitz   7127:   padding:3px 15px 3px 15px;
                   7128:   margin: 0;
                   7129:   background-color:$tabbg;
                   7130:   color:$fontmenu;
                   7131:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7132: }
1.795     www      7133: 
1.840     bisitz   7134: .LC_Box > .LC_hcell {
1.911     bisitz   7135:   margin: 0 -10px 10px -10px;
1.835     bisitz   7136: }
                   7137: 
1.721     harmsja  7138: .LC_noBorder {
1.911     bisitz   7139:   border: 0;
1.698     harmsja  7140: }
1.693     droeschl 7141: 
1.721     harmsja  7142: .LC_FormSectionClearButton input {
1.911     bisitz   7143:   background-color:transparent;
                   7144:   border: none;
                   7145:   cursor:pointer;
                   7146:   text-decoration:underline;
1.693     droeschl 7147: }
1.763     bisitz   7148: 
                   7149: .LC_help_open_topic {
1.911     bisitz   7150:   color: #FFFFFF;
                   7151:   background-color: #EEEEFF;
                   7152:   margin: 1px;
                   7153:   padding: 4px;
                   7154:   border: 1px solid #000033;
                   7155:   white-space: nowrap;
                   7156:   /* vertical-align: middle; */
1.759     neumanie 7157: }
1.693     droeschl 7158: 
1.911     bisitz   7159: dl,
                   7160: ul,
                   7161: div,
                   7162: fieldset {
                   7163:   margin: 10px 10px 10px 0;
                   7164:   /* overflow: hidden; */
1.693     droeschl 7165: }
1.795     www      7166: 
1.1075.2.90  raeburn  7167: article.geogebraweb div {
                   7168:     margin: 0;
                   7169: }
                   7170: 
1.838     bisitz   7171: fieldset > legend {
1.911     bisitz   7172:   font-weight: bold;
                   7173:   padding: 0 5px 0 5px;
1.838     bisitz   7174: }
                   7175: 
1.813     bisitz   7176: #LC_nav_bar {
1.911     bisitz   7177:   float: left;
1.995     raeburn  7178:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7179:   margin: 0 0 2px 0;
1.807     droeschl 7180: }
                   7181: 
1.916     droeschl 7182: #LC_realm {
                   7183:   margin: 0.2em 0 0 0;
                   7184:   padding: 0;
                   7185:   font-weight: bold;
                   7186:   text-align: center;
1.995     raeburn  7187:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7188: }
                   7189: 
1.911     bisitz   7190: #LC_nav_bar em {
                   7191:   font-weight: bold;
                   7192:   font-style: normal;
1.807     droeschl 7193: }
                   7194: 
1.897     wenzelju 7195: ol.LC_primary_menu {
1.934     droeschl 7196:   margin: 0;
1.1075.2.2  raeburn  7197:   padding: 0;
1.807     droeschl 7198: }
                   7199: 
1.852     droeschl 7200: ol#LC_PathBreadcrumbs {
1.911     bisitz   7201:   margin: 0;
1.693     droeschl 7202: }
                   7203: 
1.897     wenzelju 7204: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7205:   color: RGB(80, 80, 80);
                   7206:   vertical-align: middle;
                   7207:   text-align: left;
                   7208:   list-style: none;
1.1075.2.112  raeburn  7209:   position: relative;
1.1075.2.2  raeburn  7210:   float: left;
1.1075.2.112  raeburn  7211:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7212:   line-height: 1.5em;
1.1075.2.2  raeburn  7213: }
                   7214: 
1.1075.2.113  raeburn  7215: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7216: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7217:   display: block;
                   7218:   margin: 0;
                   7219:   padding: 0 5px 0 10px;
                   7220:   text-decoration: none;
                   7221: }
                   7222: 
1.1075.2.112  raeburn  7223: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7224:   display: inline-block;
                   7225:   width: 95%;
                   7226:   text-align: left;
                   7227: }
                   7228: 
                   7229: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7230:   display: inline-block;
                   7231:   width: 5%;
                   7232:   float: right;
                   7233:   text-align: right;
                   7234:   font-size: 70%;
                   7235: }
                   7236: 
                   7237: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7238:   display: none;
1.1075.2.112  raeburn  7239:   width: 15em;
1.1075.2.2  raeburn  7240:   background-color: $data_table_light;
1.1075.2.112  raeburn  7241:   position: absolute;
                   7242:   top: 100%;
                   7243: }
                   7244: 
                   7245: ol.LC_primary_menu ul ul {
                   7246:   left: 100%;
                   7247:   top: 0;
1.1075.2.2  raeburn  7248: }
                   7249: 
1.1075.2.112  raeburn  7250: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7251:   display: block;
                   7252:   position: absolute;
                   7253:   margin: 0;
                   7254:   padding: 0;
1.1075.2.5  raeburn  7255:   z-index: 2;
1.1075.2.2  raeburn  7256: }
                   7257: 
                   7258: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7259: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7260:   font-size: 90%;
1.911     bisitz   7261:   vertical-align: top;
1.1075.2.2  raeburn  7262:   float: none;
1.1075.2.5  raeburn  7263:   border-left: 1px solid black;
                   7264:   border-right: 1px solid black;
1.1075.2.112  raeburn  7265: /* A dark bottom border to visualize different menu options;
                   7266: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7267:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7268: }
                   7269: 
1.1075.2.112  raeburn  7270: ol.LC_primary_menu li li p:hover {
                   7271:   color:$button_hover;
                   7272:   text-decoration:none;
                   7273:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7274: }
                   7275: 
                   7276: ol.LC_primary_menu li li a:hover {
                   7277:    color:$button_hover;
                   7278:    background-color:$data_table_dark;
1.693     droeschl 7279: }
                   7280: 
1.1075.2.112  raeburn  7281: /* Font-size equal to the size of the predecessors*/
                   7282: ol.LC_primary_menu li:hover li li {
                   7283:   font-size: 100%;
                   7284: }
                   7285: 
1.897     wenzelju 7286: ol.LC_primary_menu li img {
1.911     bisitz   7287:   vertical-align: bottom;
1.934     droeschl 7288:   height: 1.1em;
1.1075.2.3  raeburn  7289:   margin: 0.2em 0 0 0;
1.693     droeschl 7290: }
                   7291: 
1.897     wenzelju 7292: ol.LC_primary_menu a {
1.911     bisitz   7293:   color: RGB(80, 80, 80);
                   7294:   text-decoration: none;
1.693     droeschl 7295: }
1.795     www      7296: 
1.949     droeschl 7297: ol.LC_primary_menu a.LC_new_message {
                   7298:   font-weight:bold;
                   7299:   color: darkred;
                   7300: }
                   7301: 
1.975     raeburn  7302: ol.LC_docs_parameters {
                   7303:   margin-left: 0;
                   7304:   padding: 0;
                   7305:   list-style: none;
                   7306: }
                   7307: 
                   7308: ol.LC_docs_parameters li {
                   7309:   margin: 0;
                   7310:   padding-right: 20px;
                   7311:   display: inline;
                   7312: }
                   7313: 
1.976     raeburn  7314: ol.LC_docs_parameters li:before {
                   7315:   content: "\\002022 \\0020";
                   7316: }
                   7317: 
                   7318: li.LC_docs_parameters_title {
                   7319:   font-weight: bold;
                   7320: }
                   7321: 
                   7322: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7323:   content: "";
                   7324: }
                   7325: 
1.897     wenzelju 7326: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7327:   clear: right;
1.911     bisitz   7328:   color: $fontmenu;
                   7329:   background: $tabbg;
                   7330:   list-style: none;
                   7331:   padding: 0;
                   7332:   margin: 0;
                   7333:   width: 100%;
1.995     raeburn  7334:   text-align: left;
1.1075.2.4  raeburn  7335:   float: left;
1.808     droeschl 7336: }
                   7337: 
1.897     wenzelju 7338: ul#LC_secondary_menu li {
1.911     bisitz   7339:   font-weight: bold;
                   7340:   line-height: 1.8em;
                   7341:   border-right: 1px solid black;
1.1075.2.4  raeburn  7342:   float: left;
                   7343: }
                   7344: 
                   7345: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7346:   background-color: $data_table_light;
                   7347: }
                   7348: 
                   7349: ul#LC_secondary_menu li a {
                   7350:   padding: 0 0.8em;
                   7351: }
                   7352: 
                   7353: ul#LC_secondary_menu li ul {
                   7354:   display: none;
                   7355: }
                   7356: 
                   7357: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7358:   display: block;
                   7359:   position: absolute;
                   7360:   margin: 0;
                   7361:   padding: 0;
                   7362:   list-style:none;
                   7363:   float: none;
                   7364:   background-color: $data_table_light;
1.1075.2.5  raeburn  7365:   z-index: 2;
1.1075.2.10  raeburn  7366:   margin-left: -1px;
1.1075.2.4  raeburn  7367: }
                   7368: 
                   7369: ul#LC_secondary_menu li ul li {
                   7370:   font-size: 90%;
                   7371:   vertical-align: top;
                   7372:   border-left: 1px solid black;
                   7373:   border-right: 1px solid black;
1.1075.2.33  raeburn  7374:   background-color: $data_table_light;
1.1075.2.4  raeburn  7375:   list-style:none;
                   7376:   float: none;
                   7377: }
                   7378: 
                   7379: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7380:   background-color: $data_table_dark;
1.807     droeschl 7381: }
                   7382: 
1.847     tempelho 7383: ul.LC_TabContent {
1.911     bisitz   7384:   display:block;
                   7385:   background: $sidebg;
                   7386:   border-bottom: solid 1px $lg_border_color;
                   7387:   list-style:none;
1.1020    raeburn  7388:   margin: -1px -10px 0 -10px;
1.911     bisitz   7389:   padding: 0;
1.693     droeschl 7390: }
                   7391: 
1.795     www      7392: ul.LC_TabContent li,
                   7393: ul.LC_TabContentBigger li {
1.911     bisitz   7394:   float:left;
1.741     harmsja  7395: }
1.795     www      7396: 
1.897     wenzelju 7397: ul#LC_secondary_menu li a {
1.911     bisitz   7398:   color: $fontmenu;
                   7399:   text-decoration: none;
1.693     droeschl 7400: }
1.795     www      7401: 
1.721     harmsja  7402: ul.LC_TabContent {
1.952     onken    7403:   min-height:20px;
1.721     harmsja  7404: }
1.795     www      7405: 
                   7406: ul.LC_TabContent li {
1.911     bisitz   7407:   vertical-align:middle;
1.959     onken    7408:   padding: 0 16px 0 10px;
1.911     bisitz   7409:   background-color:$tabbg;
                   7410:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7411:   border-left: solid 1px $font;
1.721     harmsja  7412: }
1.795     www      7413: 
1.847     tempelho 7414: ul.LC_TabContent .right {
1.911     bisitz   7415:   float:right;
1.847     tempelho 7416: }
                   7417: 
1.911     bisitz   7418: ul.LC_TabContent li a,
                   7419: ul.LC_TabContent li {
                   7420:   color:rgb(47,47,47);
                   7421:   text-decoration:none;
                   7422:   font-size:95%;
                   7423:   font-weight:bold;
1.952     onken    7424:   min-height:20px;
                   7425: }
                   7426: 
1.959     onken    7427: ul.LC_TabContent li a:hover,
                   7428: ul.LC_TabContent li a:focus {
1.952     onken    7429:   color: $button_hover;
1.959     onken    7430:   background:none;
                   7431:   outline:none;
1.952     onken    7432: }
                   7433: 
                   7434: ul.LC_TabContent li:hover {
                   7435:   color: $button_hover;
                   7436:   cursor:pointer;
1.721     harmsja  7437: }
1.795     www      7438: 
1.911     bisitz   7439: ul.LC_TabContent li.active {
1.952     onken    7440:   color: $font;
1.911     bisitz   7441:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7442:   border-bottom:solid 1px #FFFFFF;
                   7443:   cursor: default;
1.744     ehlerst  7444: }
1.795     www      7445: 
1.959     onken    7446: ul.LC_TabContent li.active a {
                   7447:   color:$font;
                   7448:   background:#FFFFFF;
                   7449:   outline: none;
                   7450: }
1.1047    raeburn  7451: 
                   7452: ul.LC_TabContent li.goback {
                   7453:   float: left;
                   7454:   border-left: none;
                   7455: }
                   7456: 
1.870     tempelho 7457: #maincoursedoc {
1.911     bisitz   7458:   clear:both;
1.870     tempelho 7459: }
                   7460: 
                   7461: ul.LC_TabContentBigger {
1.911     bisitz   7462:   display:block;
                   7463:   list-style:none;
                   7464:   padding: 0;
1.870     tempelho 7465: }
                   7466: 
1.795     www      7467: ul.LC_TabContentBigger li {
1.911     bisitz   7468:   vertical-align:bottom;
                   7469:   height: 30px;
                   7470:   font-size:110%;
                   7471:   font-weight:bold;
                   7472:   color: #737373;
1.841     tempelho 7473: }
                   7474: 
1.957     onken    7475: ul.LC_TabContentBigger li.active {
                   7476:   position: relative;
                   7477:   top: 1px;
                   7478: }
                   7479: 
1.870     tempelho 7480: ul.LC_TabContentBigger li a {
1.911     bisitz   7481:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7482:   height: 30px;
                   7483:   line-height: 30px;
                   7484:   text-align: center;
                   7485:   display: block;
                   7486:   text-decoration: none;
1.958     onken    7487:   outline: none;  
1.741     harmsja  7488: }
1.795     www      7489: 
1.870     tempelho 7490: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7491:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7492:   color:$font;
1.744     ehlerst  7493: }
1.795     www      7494: 
1.870     tempelho 7495: ul.LC_TabContentBigger li b {
1.911     bisitz   7496:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7497:   display: block;
                   7498:   float: left;
                   7499:   padding: 0 30px;
1.957     onken    7500:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7501: }
                   7502: 
1.956     onken    7503: ul.LC_TabContentBigger li:hover b {
                   7504:   color:$button_hover;
                   7505: }
                   7506: 
1.870     tempelho 7507: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7508:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7509:   color:$font;
1.957     onken    7510:   border: 0;
1.741     harmsja  7511: }
1.693     droeschl 7512: 
1.870     tempelho 7513: 
1.862     bisitz   7514: ul.LC_CourseBreadcrumbs {
                   7515:   background: $sidebg;
1.1020    raeburn  7516:   height: 2em;
1.862     bisitz   7517:   padding-left: 10px;
1.1020    raeburn  7518:   margin: 0;
1.862     bisitz   7519:   list-style-position: inside;
                   7520: }
                   7521: 
1.911     bisitz   7522: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7523: ol#LC_PathBreadcrumbs {
1.911     bisitz   7524:   padding-left: 10px;
                   7525:   margin: 0;
1.933     droeschl 7526:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7527: }
                   7528: 
1.911     bisitz   7529: ol#LC_MenuBreadcrumbs li,
                   7530: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7531: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7532:   display: inline;
1.933     droeschl 7533:   white-space: normal;  
1.693     droeschl 7534: }
                   7535: 
1.823     bisitz   7536: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7537: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7538:   text-decoration: none;
                   7539:   font-size:90%;
1.693     droeschl 7540: }
1.795     www      7541: 
1.969     droeschl 7542: ol#LC_MenuBreadcrumbs h1 {
                   7543:   display: inline;
                   7544:   font-size: 90%;
                   7545:   line-height: 2.5em;
                   7546:   margin: 0;
                   7547:   padding: 0;
                   7548: }
                   7549: 
1.795     www      7550: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7551:   text-decoration:none;
                   7552:   font-size:100%;
                   7553:   font-weight:bold;
1.693     droeschl 7554: }
1.795     www      7555: 
1.840     bisitz   7556: .LC_Box {
1.911     bisitz   7557:   border: solid 1px $lg_border_color;
                   7558:   padding: 0 10px 10px 10px;
1.746     neumanie 7559: }
1.795     www      7560: 
1.1020    raeburn  7561: .LC_DocsBox {
                   7562:   border: solid 1px $lg_border_color;
                   7563:   padding: 0 0 10px 10px;
                   7564: }
                   7565: 
1.795     www      7566: .LC_AboutMe_Image {
1.911     bisitz   7567:   float:left;
                   7568:   margin-right:10px;
1.747     neumanie 7569: }
1.795     www      7570: 
                   7571: .LC_Clear_AboutMe_Image {
1.911     bisitz   7572:   clear:left;
1.747     neumanie 7573: }
1.795     www      7574: 
1.721     harmsja  7575: dl.LC_ListStyleClean dt {
1.911     bisitz   7576:   padding-right: 5px;
                   7577:   display: table-header-group;
1.693     droeschl 7578: }
                   7579: 
1.721     harmsja  7580: dl.LC_ListStyleClean dd {
1.911     bisitz   7581:   display: table-row;
1.693     droeschl 7582: }
                   7583: 
1.721     harmsja  7584: .LC_ListStyleClean,
                   7585: .LC_ListStyleSimple,
                   7586: .LC_ListStyleNormal,
1.795     www      7587: .LC_ListStyleSpecial {
1.911     bisitz   7588:   /* display:block; */
                   7589:   list-style-position: inside;
                   7590:   list-style-type: none;
                   7591:   overflow: hidden;
                   7592:   padding: 0;
1.693     droeschl 7593: }
                   7594: 
1.721     harmsja  7595: .LC_ListStyleSimple li,
                   7596: .LC_ListStyleSimple dd,
                   7597: .LC_ListStyleNormal li,
                   7598: .LC_ListStyleNormal dd,
                   7599: .LC_ListStyleSpecial li,
1.795     www      7600: .LC_ListStyleSpecial dd {
1.911     bisitz   7601:   margin: 0;
                   7602:   padding: 5px 5px 5px 10px;
                   7603:   clear: both;
1.693     droeschl 7604: }
                   7605: 
1.721     harmsja  7606: .LC_ListStyleClean li,
                   7607: .LC_ListStyleClean dd {
1.911     bisitz   7608:   padding-top: 0;
                   7609:   padding-bottom: 0;
1.693     droeschl 7610: }
                   7611: 
1.721     harmsja  7612: .LC_ListStyleSimple dd,
1.795     www      7613: .LC_ListStyleSimple li {
1.911     bisitz   7614:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7615: }
                   7616: 
1.721     harmsja  7617: .LC_ListStyleSpecial li,
                   7618: .LC_ListStyleSpecial dd {
1.911     bisitz   7619:   list-style-type: none;
                   7620:   background-color: RGB(220, 220, 220);
                   7621:   margin-bottom: 4px;
1.693     droeschl 7622: }
                   7623: 
1.721     harmsja  7624: table.LC_SimpleTable {
1.911     bisitz   7625:   margin:5px;
                   7626:   border:solid 1px $lg_border_color;
1.795     www      7627: }
1.693     droeschl 7628: 
1.721     harmsja  7629: table.LC_SimpleTable tr {
1.911     bisitz   7630:   padding: 0;
                   7631:   border:solid 1px $lg_border_color;
1.693     droeschl 7632: }
1.795     www      7633: 
                   7634: table.LC_SimpleTable thead {
1.911     bisitz   7635:   background:rgb(220,220,220);
1.693     droeschl 7636: }
                   7637: 
1.721     harmsja  7638: div.LC_columnSection {
1.911     bisitz   7639:   display: block;
                   7640:   clear: both;
                   7641:   overflow: hidden;
                   7642:   margin: 0;
1.693     droeschl 7643: }
                   7644: 
1.721     harmsja  7645: div.LC_columnSection>* {
1.911     bisitz   7646:   float: left;
                   7647:   margin: 10px 20px 10px 0;
                   7648:   overflow:hidden;
1.693     droeschl 7649: }
1.721     harmsja  7650: 
1.795     www      7651: table em {
1.911     bisitz   7652:   font-weight: bold;
                   7653:   font-style: normal;
1.748     schulted 7654: }
1.795     www      7655: 
1.779     bisitz   7656: table.LC_tableBrowseRes,
1.795     www      7657: table.LC_tableOfContent {
1.911     bisitz   7658:   border:none;
                   7659:   border-spacing: 1px;
                   7660:   padding: 3px;
                   7661:   background-color: #FFFFFF;
                   7662:   font-size: 90%;
1.753     droeschl 7663: }
1.789     droeschl 7664: 
1.911     bisitz   7665: table.LC_tableOfContent {
                   7666:   border-collapse: collapse;
1.789     droeschl 7667: }
                   7668: 
1.771     droeschl 7669: table.LC_tableBrowseRes a,
1.768     schulted 7670: table.LC_tableOfContent a {
1.911     bisitz   7671:   background-color: transparent;
                   7672:   text-decoration: none;
1.753     droeschl 7673: }
                   7674: 
1.795     www      7675: table.LC_tableOfContent img {
1.911     bisitz   7676:   border: none;
                   7677:   height: 1.3em;
                   7678:   vertical-align: text-bottom;
                   7679:   margin-right: 0.3em;
1.753     droeschl 7680: }
1.757     schulted 7681: 
1.795     www      7682: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7683:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7684: }
                   7685: 
1.795     www      7686: a#LC_content_toolbar_everything {
1.911     bisitz   7687:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7688: }
                   7689: 
1.795     www      7690: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7691:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7692: }
                   7693: 
1.795     www      7694: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7695:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7696: }
                   7697: 
1.795     www      7698: a#LC_content_toolbar_changefolder {
1.911     bisitz   7699:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7700: }
                   7701: 
1.795     www      7702: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7703:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7704: }
                   7705: 
1.1043    raeburn  7706: a#LC_content_toolbar_edittoplevel {
                   7707:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7708: }
                   7709: 
1.795     www      7710: ul#LC_toolbar li a:hover {
1.911     bisitz   7711:   background-position: bottom center;
1.757     schulted 7712: }
                   7713: 
1.795     www      7714: ul#LC_toolbar {
1.911     bisitz   7715:   padding: 0;
                   7716:   margin: 2px;
                   7717:   list-style:none;
                   7718:   position:relative;
                   7719:   background-color:white;
1.1075.2.9  raeburn  7720:   overflow: auto;
1.757     schulted 7721: }
                   7722: 
1.795     www      7723: ul#LC_toolbar li {
1.911     bisitz   7724:   border:1px solid white;
                   7725:   padding: 0;
                   7726:   margin: 0;
                   7727:   float: left;
                   7728:   display:inline;
                   7729:   vertical-align:middle;
1.1075.2.9  raeburn  7730:   white-space: nowrap;
1.911     bisitz   7731: }
1.757     schulted 7732: 
1.783     amueller 7733: 
1.795     www      7734: a.LC_toolbarItem {
1.911     bisitz   7735:   display:block;
                   7736:   padding: 0;
                   7737:   margin: 0;
                   7738:   height: 32px;
                   7739:   width: 32px;
                   7740:   color:white;
                   7741:   border: none;
                   7742:   background-repeat:no-repeat;
                   7743:   background-color:transparent;
1.757     schulted 7744: }
                   7745: 
1.915     droeschl 7746: ul.LC_funclist {
                   7747:     margin: 0;
                   7748:     padding: 0.5em 1em 0.5em 0;
                   7749: }
                   7750: 
1.933     droeschl 7751: ul.LC_funclist > li:first-child {
                   7752:     font-weight:bold; 
                   7753:     margin-left:0.8em;
                   7754: }
                   7755: 
1.915     droeschl 7756: ul.LC_funclist + ul.LC_funclist {
                   7757:     /* 
                   7758:        left border as a seperator if we have more than
                   7759:        one list 
                   7760:     */
                   7761:     border-left: 1px solid $sidebg;
                   7762:     /* 
                   7763:        this hides the left border behind the border of the 
                   7764:        outer box if element is wrapped to the next 'line' 
                   7765:     */
                   7766:     margin-left: -1px;
                   7767: }
                   7768: 
1.843     bisitz   7769: ul.LC_funclist li {
1.915     droeschl 7770:   display: inline;
1.782     bisitz   7771:   white-space: nowrap;
1.915     droeschl 7772:   margin: 0 0 0 25px;
                   7773:   line-height: 150%;
1.782     bisitz   7774: }
                   7775: 
1.974     wenzelju 7776: .LC_hidden {
                   7777:   display: none;
                   7778: }
                   7779: 
1.1030    www      7780: .LCmodal-overlay {
                   7781: 		position:fixed;
                   7782: 		top:0;
                   7783: 		right:0;
                   7784: 		bottom:0;
                   7785: 		left:0;
                   7786: 		height:100%;
                   7787: 		width:100%;
                   7788: 		margin:0;
                   7789: 		padding:0;
                   7790: 		background:#999;
                   7791: 		opacity:.75;
                   7792: 		filter: alpha(opacity=75);
                   7793: 		-moz-opacity: 0.75;
                   7794: 		z-index:101;
                   7795: }
                   7796: 
                   7797: * html .LCmodal-overlay {   
                   7798: 		position: absolute;
                   7799: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7800: }
                   7801: 
                   7802: .LCmodal-window {
                   7803: 		position:fixed;
                   7804: 		top:50%;
                   7805: 		left:50%;
                   7806: 		margin:0;
                   7807: 		padding:0;
                   7808: 		z-index:102;
                   7809: 	}
                   7810: 
                   7811: * html .LCmodal-window {
                   7812: 		position:absolute;
                   7813: }
                   7814: 
                   7815: .LCclose-window {
                   7816: 		position:absolute;
                   7817: 		width:32px;
                   7818: 		height:32px;
                   7819: 		right:8px;
                   7820: 		top:8px;
                   7821: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7822: 		text-indent:-99999px;
                   7823: 		overflow:hidden;
                   7824: 		cursor:pointer;
                   7825: }
                   7826: 
1.1075.2.141  raeburn  7827: pre.LC_wordwrap {
                   7828:   white-space: pre-wrap;
                   7829:   white-space: -moz-pre-wrap;
                   7830:   white-space: -pre-wrap;
                   7831:   white-space: -o-pre-wrap;
                   7832:   word-wrap: break-word;
                   7833: }
                   7834: 
1.1075.2.17  raeburn  7835: /*
                   7836:   styles used by TTH when "Default set of options to pass to tth/m
                   7837:   when converting TeX" in course settings has been set
                   7838: 
                   7839:   option passed: -t
                   7840: 
                   7841: */
                   7842: 
                   7843: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7844: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7845: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7846: td div.norm {line-height:normal;}
                   7847: 
                   7848: /*
                   7849:   option passed -y3
                   7850: */
                   7851: 
                   7852: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7853: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7854: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7855: 
1.1075.2.121  raeburn  7856: #LC_minitab_header {
                   7857:   float:left;
                   7858:   width:100%;
                   7859:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7860:   font-size:93%;
                   7861:   line-height:normal;
                   7862:   margin: 0.5em 0 0.5em 0;
                   7863: }
                   7864: #LC_minitab_header ul {
                   7865:   margin:0;
                   7866:   padding:10px 10px 0;
                   7867:   list-style:none;
                   7868: }
                   7869: #LC_minitab_header li {
                   7870:   float:left;
                   7871:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7872:   margin:0;
                   7873:   padding:0 0 0 9px;
                   7874: }
                   7875: #LC_minitab_header a {
                   7876:   display:block;
                   7877:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7878:   padding:5px 15px 4px 6px;
                   7879: }
                   7880: #LC_minitab_header #LC_current_minitab {
                   7881:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7882: }
                   7883: #LC_minitab_header #LC_current_minitab a {
                   7884:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7885:   padding-bottom:5px;
                   7886: }
                   7887: 
                   7888: 
1.343     albertel 7889: END
                   7890: }
                   7891: 
1.306     albertel 7892: =pod
                   7893: 
                   7894: =item * &headtag()
                   7895: 
                   7896: Returns a uniform footer for LON-CAPA web pages.
                   7897: 
1.307     albertel 7898: Inputs: $title - optional title for the head
                   7899:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7900:         $args - optional arguments
1.319     albertel 7901:             force_register - if is true call registerurl so the remote is 
                   7902:                              informed
1.415     albertel 7903:             redirect       -> array ref of
                   7904:                                    1- seconds before redirect occurs
                   7905:                                    2- url to redirect to
                   7906:                                    3- whether the side effect should occur
1.315     albertel 7907:                            (side effect of setting 
                   7908:                                $env{'internal.head.redirect'} to the url 
                   7909:                                redirected too)
1.352     albertel 7910:             domain         -> force to color decorate a page for a specific
                   7911:                                domain
                   7912:             function       -> force usage of a specific rolish color scheme
                   7913:             bgcolor        -> override the default page bgcolor
1.460     albertel 7914:             no_auto_mt_title
                   7915:                            -> prevent &mt()ing the title arg
1.464     albertel 7916: 
1.306     albertel 7917: =cut
                   7918: 
                   7919: sub headtag {
1.313     albertel 7920:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7921:     
1.363     albertel 7922:     my $function = $args->{'function'} || &get_users_function();
                   7923:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7924:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7925:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7926:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7927: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7928: 		   #time(),
1.418     albertel 7929: 		   $env{'environment.color.timestamp'},
1.363     albertel 7930: 		   $function,$domain,$bgcolor);
                   7931: 
1.369     www      7932:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7933: 
1.308     albertel 7934:     my $result =
                   7935: 	'<head>'.
1.1075.2.56  raeburn  7936: 	&font_settings($args);
1.319     albertel 7937: 
1.1075.2.72  raeburn  7938:     my $inhibitprint;
                   7939:     if ($args->{'print_suppress'}) {
                   7940:         $inhibitprint = &print_suppression();
                   7941:     }
1.1064    raeburn  7942: 
1.461     albertel 7943:     if (!$args->{'frameset'}) {
                   7944: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7945:     }
1.1075.2.12  raeburn  7946:     if ($args->{'force_register'}) {
                   7947:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7948:     }
1.436     albertel 7949:     if (!$args->{'no_nav_bar'} 
                   7950: 	&& !$args->{'only_body'}
                   7951: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7952: 	$result .= &help_menu_js($httphost);
1.1032    www      7953:         $result.=&modal_window();
1.1038    www      7954:         $result.=&togglebox_script();
1.1034    www      7955:         $result.=&wishlist_window();
1.1041    www      7956:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7957:     } else {
                   7958:         if ($args->{'add_modal'}) {
                   7959:            $result.=&modal_window();
                   7960:         }
                   7961:         if ($args->{'add_wishlist'}) {
                   7962:            $result.=&wishlist_window();
                   7963:         }
1.1038    www      7964:         if ($args->{'add_togglebox'}) {
                   7965:            $result.=&togglebox_script();
                   7966:         }
1.1041    www      7967:         if ($args->{'add_progressbar'}) {
                   7968:            $result.=&LCprogressbarUpdate_script();
                   7969:         }
1.436     albertel 7970:     }
1.314     albertel 7971:     if (ref($args->{'redirect'})) {
1.414     albertel 7972: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7973: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7974: 	if (!$inhibit_continue) {
                   7975: 	    $env{'internal.head.redirect'} = $url;
                   7976: 	}
1.313     albertel 7977: 	$result.=<<ADDMETA
                   7978: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7979: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7980: ADDMETA
1.1075.2.89  raeburn  7981:     } else {
                   7982:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7983:             my $requrl = $env{'request.uri'};
                   7984:             if ($requrl eq '') {
                   7985:                 $requrl = $ENV{'REQUEST_URI'};
                   7986:                 $requrl =~ s/\?.+$//;
                   7987:             }
                   7988:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7989:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7990:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7991:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7992:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7993:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  7994:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7995:                     my $offload;
1.1075.2.89  raeburn  7996:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7997:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  7998:                             $offload = 1;
                   7999:                         }
                   8000:                     }
                   8001:                     unless ($offload) {
                   8002:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8003:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8004:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8005:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8006:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8007:                                         $offload = 1;
                   8008:                                         $dom_in_use = $env{'user.domain'};
                   8009:                                     }
1.1075.2.89  raeburn  8010:                                 }
1.1075.2.145  raeburn  8011:                             }
                   8012:                         }
                   8013:                     }
                   8014:                     if ($offload) {
                   8015:                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8016:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8017:                             my $numsec = 5;
                   8018:                             my $timeout = $numsec * 1000;
                   8019:                             my ($newurl,$locknum,%locks,$msg);
                   8020:                             if ($env{'request.role.adv'}) {
                   8021:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8022:                             }
                   8023:                             my $disable_submit = 0;
                   8024:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8025:                                 $disable_submit = 1;
                   8026:                             }
                   8027:                             if ($locknum) {
                   8028:                                 my @lockinfo = sort(values(%locks));
                   8029:                                 $msg = &mt('Once the following tasks are complete: ')."\n".
                   8030:                                        join(", ",sort(values(%locks)))."\n";
                   8031:                                 if (&show_course()) {
                   8032:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8033:                                 } else {
1.1075.2.145  raeburn  8034:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8035:                                 }
                   8036:                             } else {
                   8037:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8038:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8039:                                 }
                   8040:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8041:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8042:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8043:                                     $newurl .= '&role='.$env{'request.role'};
                   8044:                                 }
                   8045:                                 if ($env{'request.symb'}) {
                   8046:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8047:                                     if ($shownsymb =~ m{^/enc/}) {
                   8048:                                         my $reqdmajor = 2;
                   8049:                                         my $reqdminor = 11;
                   8050:                                         my $reqdsubminor = 3;
                   8051:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8052:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8053:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8054:                                         if (($major eq '' && $minor eq '') ||
                   8055:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8056:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8057:                                              ($reqdsubminor > $subminor))))) {
                   8058:                                             undef($shownsymb);
                   8059:                                         }
1.1075.2.89  raeburn  8060:                                     }
1.1075.2.145  raeburn  8061:                                     if ($shownsymb) {
                   8062:                                         &js_escape(\$shownsymb);
                   8063:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8064:                                     }
1.1075.2.145  raeburn  8065:                                 } else {
                   8066:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8067:                                     &js_escape(\$shownurl);
                   8068:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8069:                                 }
1.1075.2.145  raeburn  8070:                             }
                   8071:                             &js_escape(\$msg);
                   8072:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8073: <meta http-equiv="pragma" content="no-cache" />
                   8074: <script type="text/javascript">
1.1075.2.92  raeburn  8075: // <![CDATA[
1.1075.2.89  raeburn  8076: function LC_Offload_Now() {
                   8077:     var dest = "$newurl";
                   8078:     if (dest != '') {
                   8079:         window.location.href="$newurl";
                   8080:     }
                   8081: }
1.1075.2.92  raeburn  8082: \$(document).ready(function () {
                   8083:     window.alert('$msg');
                   8084:     if ($disable_submit) {
1.1075.2.89  raeburn  8085:         \$(".LC_hwk_submit").prop("disabled", true);
                   8086:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8087:     }
                   8088:     setTimeout('LC_Offload_Now()', $timeout);
                   8089: });
                   8090: // ]]>
1.1075.2.89  raeburn  8091: </script>
                   8092: OFFLOAD
                   8093:                         }
                   8094:                     }
                   8095:                 }
                   8096:             }
                   8097:         }
1.313     albertel 8098:     }
1.306     albertel 8099:     if (!defined($title)) {
                   8100: 	$title = 'The LearningOnline Network with CAPA';
                   8101:     }
1.460     albertel 8102:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8103:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8104: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8105:     if (!$args->{'frameset'}) {
                   8106:         $result .= ' /';
                   8107:     }
                   8108:     $result .= '>'
1.1064    raeburn  8109:         .$inhibitprint
1.414     albertel 8110: 	.$head_extra;
1.1075.2.108  raeburn  8111:     my $clientmobile;
                   8112:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8113:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8114:     } else {
                   8115:         $clientmobile = $env{'browser.mobile'};
                   8116:     }
                   8117:     if ($clientmobile) {
1.1075.2.42  raeburn  8118:         $result .= '
                   8119: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8120: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8121:     }
1.1075.2.126  raeburn  8122:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8123:     return $result.'</head>';
1.306     albertel 8124: }
                   8125: 
                   8126: =pod
                   8127: 
1.340     albertel 8128: =item * &font_settings()
                   8129: 
                   8130: Returns neccessary <meta> to set the proper encoding
                   8131: 
1.1075.2.56  raeburn  8132: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8133: 
                   8134: =cut
                   8135: 
                   8136: sub font_settings {
1.1075.2.56  raeburn  8137:     my ($args) = @_;
1.340     albertel 8138:     my $headerstring='';
1.1075.2.56  raeburn  8139:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8140:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8141: 	$headerstring.=
1.1075.2.61  raeburn  8142: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8143:         if (!$args->{'frameset'}) {
                   8144:             $headerstring.= ' /';
                   8145:         }
                   8146:         $headerstring .= '>'."\n";
1.340     albertel 8147:     }
                   8148:     return $headerstring;
                   8149: }
                   8150: 
1.341     albertel 8151: =pod
                   8152: 
1.1064    raeburn  8153: =item * &print_suppression()
                   8154: 
                   8155: In course context returns css which causes the body to be blank when media="print",
                   8156: if printout generation is unavailable for the current resource.
                   8157: 
                   8158: This could be because:
                   8159: 
                   8160: (a) printstartdate is in the future
                   8161: 
                   8162: (b) printenddate is in the past
                   8163: 
                   8164: (c) there is an active exam block with "printout"
                   8165: functionality blocked
                   8166: 
                   8167: Users with pav, pfo or evb privileges are exempt.
                   8168: 
                   8169: Inputs: none
                   8170: 
                   8171: =cut
                   8172: 
                   8173: 
                   8174: sub print_suppression {
                   8175:     my $noprint;
                   8176:     if ($env{'request.course.id'}) {
                   8177:         my $scope = $env{'request.course.id'};
                   8178:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8179:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8180:             return;
                   8181:         }
                   8182:         if ($env{'request.course.sec'} ne '') {
                   8183:             $scope .= "/$env{'request.course.sec'}";
                   8184:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8185:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8186:                 return;
1.1064    raeburn  8187:             }
                   8188:         }
                   8189:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8190:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  8191:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8192:         if ($blocked) {
                   8193:             my $checkrole = "cm./$cdom/$cnum";
                   8194:             if ($env{'request.course.sec'} ne '') {
                   8195:                 $checkrole .= "/$env{'request.course.sec'}";
                   8196:             }
                   8197:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8198:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8199:                 $noprint = 1;
                   8200:             }
                   8201:         }
                   8202:         unless ($noprint) {
                   8203:             my $symb = &Apache::lonnet::symbread();
                   8204:             if ($symb ne '') {
                   8205:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8206:                 if (ref($navmap)) {
                   8207:                     my $res = $navmap->getBySymb($symb);
                   8208:                     if (ref($res)) {
                   8209:                         if (!$res->resprintable()) {
                   8210:                             $noprint = 1;
                   8211:                         }
                   8212:                     }
                   8213:                 }
                   8214:             }
                   8215:         }
                   8216:         if ($noprint) {
                   8217:             return <<"ENDSTYLE";
                   8218: <style type="text/css" media="print">
                   8219:     body { display:none }
                   8220: </style>
                   8221: ENDSTYLE
                   8222:         }
                   8223:     }
                   8224:     return;
                   8225: }
                   8226: 
                   8227: =pod
                   8228: 
1.341     albertel 8229: =item * &xml_begin()
                   8230: 
                   8231: Returns the needed doctype and <html>
                   8232: 
                   8233: Inputs: none
                   8234: 
                   8235: =cut
                   8236: 
                   8237: sub xml_begin {
1.1075.2.61  raeburn  8238:     my ($is_frameset) = @_;
1.341     albertel 8239:     my $output='';
                   8240: 
                   8241:     if ($env{'browser.mathml'}) {
                   8242: 	$output='<?xml version="1.0"?>'
                   8243:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8244: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8245:             
                   8246: #	    .'<!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">] >'
                   8247: 	    .'<!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">'
                   8248:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8249: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8250:     } elsif ($is_frameset) {
                   8251:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8252:                 '<html>'."\n";
1.341     albertel 8253:     } else {
1.1075.2.61  raeburn  8254: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8255:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8256:     }
                   8257:     return $output;
                   8258: }
1.340     albertel 8259: 
                   8260: =pod
                   8261: 
1.306     albertel 8262: =item * &start_page()
                   8263: 
                   8264: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8265: 
1.648     raeburn  8266: Inputs:
                   8267: 
                   8268: =over 4
                   8269: 
                   8270: $title - optional title for the page
                   8271: 
                   8272: $head_extra - optional extra HTML to incude inside the <head>
                   8273: 
                   8274: $args - additional optional args supported are:
                   8275: 
                   8276: =over 8
                   8277: 
                   8278:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8279:                                     arg on
1.814     bisitz   8280:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8281:              add_entries    -> additional attributes to add to the  <body>
                   8282:              domain         -> force to color decorate a page for a 
1.317     albertel 8283:                                     specific domain
1.648     raeburn  8284:              function       -> force usage of a specific rolish color
1.317     albertel 8285:                                     scheme
1.648     raeburn  8286:              redirect       -> see &headtag()
                   8287:              bgcolor        -> override the default page bg color
                   8288:              js_ready       -> return a string ready for being used in 
1.317     albertel 8289:                                     a javascript writeln
1.648     raeburn  8290:              html_encode    -> return a string ready for being used in 
1.320     albertel 8291:                                     a html attribute
1.648     raeburn  8292:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8293:                                     $forcereg arg
1.648     raeburn  8294:              frameset       -> if true will start with a <frameset>
1.330     albertel 8295:                                     rather than <body>
1.648     raeburn  8296:              skip_phases    -> hash ref of 
1.338     albertel 8297:                                     head -> skip the <html><head> generation
                   8298:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8299:              no_inline_link -> if true and in remote mode, don't show the
                   8300:                                     'Switch To Inline Menu' link
1.648     raeburn  8301:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8302:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8303:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8304:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8305:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8306:              group          -> includes the current group, if page is for a
                   8307:                                specific group
1.1075.2.133  raeburn  8308:              use_absolute   -> for request for external resource or syllabus, this
                   8309:                                will contain https://<hostname> if server uses
                   8310:                                https (as per hosts.tab), but request is for http
                   8311:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8312: 
1.648     raeburn  8313: =back
1.460     albertel 8314: 
1.648     raeburn  8315: =back
1.562     albertel 8316: 
1.306     albertel 8317: =cut
                   8318: 
                   8319: sub start_page {
1.309     albertel 8320:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8321:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8322: 
1.315     albertel 8323:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8324:     my ($result,@advtools);
1.964     droeschl 8325: 
1.338     albertel 8326:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8327:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8328:     }
                   8329:     
                   8330:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8331: 	if ($args->{'frameset'}) {
                   8332: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8333: 						$args->{'add_entries'});
                   8334: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8335:         } else {
                   8336:             $result .=
                   8337:                 &bodytag($title, 
                   8338:                          $args->{'function'},       $args->{'add_entries'},
                   8339:                          $args->{'only_body'},      $args->{'domain'},
                   8340:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8341:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8342:                          $args,                     \@advtools);
1.831     bisitz   8343:         }
1.330     albertel 8344:     }
1.338     albertel 8345: 
1.315     albertel 8346:     if ($args->{'js_ready'}) {
1.713     kaisler  8347: 		$result = &js_ready($result);
1.315     albertel 8348:     }
1.320     albertel 8349:     if ($args->{'html_encode'}) {
1.713     kaisler  8350: 		$result = &html_encode($result);
                   8351:     }
                   8352: 
1.813     bisitz   8353:     # Preparation for new and consistent functionlist at top of screen
                   8354:     # if ($args->{'functionlist'}) {
                   8355:     #            $result .= &build_functionlist();
                   8356:     #}
                   8357: 
1.964     droeschl 8358:     # Don't add anything more if only_body wanted or in const space
                   8359:     return $result if    $args->{'only_body'} 
                   8360:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8361: 
                   8362:     #Breadcrumbs
1.758     kaisler  8363:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8364: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8365: 		#if any br links exists, add them to the breadcrumbs
                   8366: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8367: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8368: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8369: 			}
                   8370: 		}
1.1075.2.19  raeburn  8371:                 # if @advtools array contains items add then to the breadcrumbs
                   8372:                 if (@advtools > 0) {
                   8373:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8374:                 }
1.1075.2.123  raeburn  8375:                 my $menulink;
                   8376:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8377:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8378:                     $menulink = 0;
                   8379:                 } else {
                   8380:                     undef($menulink);
                   8381:                 }
1.758     kaisler  8382: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8383: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8384: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8385: 		}else{
1.1075.2.123  raeburn  8386: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8387: 		}
1.1075.2.24  raeburn  8388:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8389:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8390:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8391:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8392:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8393:     }
1.315     albertel 8394:     return $result;
1.306     albertel 8395: }
                   8396: 
                   8397: sub end_page {
1.315     albertel 8398:     my ($args) = @_;
                   8399:     $env{'internal.end_page'}++;
1.330     albertel 8400:     my $result;
1.335     albertel 8401:     if ($args->{'discussion'}) {
                   8402: 	my ($target,$parser);
                   8403: 	if (ref($args->{'discussion'})) {
                   8404: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8405: 				$args->{'discussion'}{'parser'});
                   8406: 	}
                   8407: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8408:     }
1.330     albertel 8409:     if ($args->{'frameset'}) {
                   8410: 	$result .= '</frameset>';
                   8411:     } else {
1.635     raeburn  8412: 	$result .= &endbodytag($args);
1.330     albertel 8413:     }
1.1075.2.6  raeburn  8414:     unless ($args->{'notbody'}) {
                   8415:         $result .= "\n</html>";
                   8416:     }
1.330     albertel 8417: 
1.315     albertel 8418:     if ($args->{'js_ready'}) {
1.317     albertel 8419: 	$result = &js_ready($result);
1.315     albertel 8420:     }
1.335     albertel 8421: 
1.320     albertel 8422:     if ($args->{'html_encode'}) {
                   8423: 	$result = &html_encode($result);
                   8424:     }
1.335     albertel 8425: 
1.315     albertel 8426:     return $result;
                   8427: }
                   8428: 
1.1034    www      8429: sub wishlist_window {
                   8430:     return(<<'ENDWISHLIST');
1.1046    raeburn  8431: <script type="text/javascript">
1.1034    www      8432: // <![CDATA[
                   8433: // <!-- BEGIN LON-CAPA Internal
                   8434: function set_wishlistlink(title, path) {
                   8435:     if (!title) {
                   8436:         title = document.title;
                   8437:         title = title.replace(/^LON-CAPA /,'');
                   8438:     }
1.1075.2.65  raeburn  8439:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8440:     title = title.replace("'","\\\'");
1.1034    www      8441:     if (!path) {
                   8442:         path = location.pathname;
                   8443:     }
1.1075.2.65  raeburn  8444:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8445:     path = path.replace("'","\\\'");
1.1034    www      8446:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8447:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8448: }
                   8449: // END LON-CAPA Internal -->
                   8450: // ]]>
                   8451: </script>
                   8452: ENDWISHLIST
                   8453: }
                   8454: 
1.1030    www      8455: sub modal_window {
                   8456:     return(<<'ENDMODAL');
1.1046    raeburn  8457: <script type="text/javascript">
1.1030    www      8458: // <![CDATA[
                   8459: // <!-- BEGIN LON-CAPA Internal
                   8460: var modalWindow = {
                   8461: 	parent:"body",
                   8462: 	windowId:null,
                   8463: 	content:null,
                   8464: 	width:null,
                   8465: 	height:null,
                   8466: 	close:function()
                   8467: 	{
                   8468: 	        $(".LCmodal-window").remove();
                   8469: 	        $(".LCmodal-overlay").remove();
                   8470: 	},
                   8471: 	open:function()
                   8472: 	{
                   8473: 		var modal = "";
                   8474: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8475: 		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;\">";
                   8476: 		modal += this.content;
                   8477: 		modal += "</div>";	
                   8478: 
                   8479: 		$(this.parent).append(modal);
                   8480: 
                   8481: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8482: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8483: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8484: 	}
                   8485: };
1.1075.2.42  raeburn  8486: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8487: 	{
1.1075.2.119  raeburn  8488:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8489: 		modalWindow.windowId = "myModal";
                   8490: 		modalWindow.width = width;
                   8491: 		modalWindow.height = height;
1.1075.2.80  raeburn  8492: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8493: 		modalWindow.open();
1.1075.2.87  raeburn  8494: 	};
1.1030    www      8495: // END LON-CAPA Internal -->
                   8496: // ]]>
                   8497: </script>
                   8498: ENDMODAL
                   8499: }
                   8500: 
                   8501: sub modal_link {
1.1075.2.42  raeburn  8502:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8503:     unless ($width) { $width=480; }
                   8504:     unless ($height) { $height=400; }
1.1031    www      8505:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8506:     unless ($transparency) { $transparency='true'; }
                   8507: 
1.1074    raeburn  8508:     my $target_attr;
                   8509:     if (defined($target)) {
                   8510:         $target_attr = 'target="'.$target.'"';
                   8511:     }
                   8512:     return <<"ENDLINK";
1.1075.2.143  raeburn  8513: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8514: ENDLINK
1.1030    www      8515: }
                   8516: 
1.1032    www      8517: sub modal_adhoc_script {
                   8518:     my ($funcname,$width,$height,$content)=@_;
                   8519:     return (<<ENDADHOC);
1.1046    raeburn  8520: <script type="text/javascript">
1.1032    www      8521: // <![CDATA[
                   8522:         var $funcname = function()
                   8523:         {
                   8524:                 modalWindow.windowId = "myModal";
                   8525:                 modalWindow.width = $width;
                   8526:                 modalWindow.height = $height;
                   8527:                 modalWindow.content = '$content';
                   8528:                 modalWindow.open();
                   8529:         };  
                   8530: // ]]>
                   8531: </script>
                   8532: ENDADHOC
                   8533: }
                   8534: 
1.1041    www      8535: sub modal_adhoc_inner {
                   8536:     my ($funcname,$width,$height,$content)=@_;
                   8537:     my $innerwidth=$width-20;
                   8538:     $content=&js_ready(
1.1042    www      8539:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8540:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8541:                  $content.
1.1041    www      8542:                  &end_scrollbox().
1.1075.2.42  raeburn  8543:                  &end_page()
1.1041    www      8544:              );
                   8545:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8546: }
                   8547: 
                   8548: sub modal_adhoc_window {
                   8549:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8550:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8551:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8552: }
                   8553: 
                   8554: sub modal_adhoc_launch {
                   8555:     my ($funcname,$width,$height,$content)=@_;
                   8556:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8557: <script type="text/javascript">
                   8558: // <![CDATA[
                   8559: $funcname();
                   8560: // ]]>
                   8561: </script>
                   8562: ENDLAUNCH
                   8563: }
                   8564: 
                   8565: sub modal_adhoc_close {
                   8566:     return (<<ENDCLOSE);
                   8567: <script type="text/javascript">
                   8568: // <![CDATA[
                   8569: modalWindow.close();
                   8570: // ]]>
                   8571: </script>
                   8572: ENDCLOSE
                   8573: }
                   8574: 
1.1038    www      8575: sub togglebox_script {
                   8576:    return(<<ENDTOGGLE);
                   8577: <script type="text/javascript"> 
                   8578: // <![CDATA[
                   8579: function LCtoggleDisplay(id,hidetext,showtext) {
                   8580:    link = document.getElementById(id + "link").childNodes[0];
                   8581:    with (document.getElementById(id).style) {
                   8582:       if (display == "none" ) {
                   8583:           display = "inline";
                   8584:           link.nodeValue = hidetext;
                   8585:         } else {
                   8586:           display = "none";
                   8587:           link.nodeValue = showtext;
                   8588:        }
                   8589:    }
                   8590: }
                   8591: // ]]>
                   8592: </script>
                   8593: ENDTOGGLE
                   8594: }
                   8595: 
1.1039    www      8596: sub start_togglebox {
                   8597:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8598:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8599:     unless ($showtext) { $showtext=&mt('show'); }
                   8600:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8601:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8602:     return &start_data_table().
                   8603:            &start_data_table_header_row().
                   8604:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8605:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8606:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8607:            &end_data_table_header_row().
                   8608:            '<tr id="'.$id.'" style="display:none""><td>';
                   8609: }
                   8610: 
                   8611: sub end_togglebox {
                   8612:     return '</td></tr>'.&end_data_table();
                   8613: }
                   8614: 
1.1041    www      8615: sub LCprogressbar_script {
1.1075.2.130  raeburn  8616:    my ($id,$number_to_do)=@_;
                   8617:    if ($number_to_do) {
                   8618:        return(<<ENDPROGRESS);
1.1041    www      8619: <script type="text/javascript">
                   8620: // <![CDATA[
1.1045    www      8621: \$('#progressbar$id').progressbar({
1.1041    www      8622:   value: 0,
                   8623:   change: function(event, ui) {
                   8624:     var newVal = \$(this).progressbar('option', 'value');
                   8625:     \$('.pblabel', this).text(LCprogressTxt);
                   8626:   }
                   8627: });
                   8628: // ]]>
                   8629: </script>
                   8630: ENDPROGRESS
1.1075.2.130  raeburn  8631:    } else {
                   8632:        return(<<ENDPROGRESS);
                   8633: <script type="text/javascript">
                   8634: // <![CDATA[
                   8635: \$('#progressbar$id').progressbar({
                   8636:   value: false,
                   8637:   create: function(event, ui) {
                   8638:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8639:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8640:   }
                   8641: });
                   8642: // ]]>
                   8643: </script>
                   8644: ENDPROGRESS
                   8645:    }
1.1041    www      8646: }
                   8647: 
                   8648: sub LCprogressbarUpdate_script {
                   8649:    return(<<ENDPROGRESSUPDATE);
                   8650: <style type="text/css">
                   8651: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8652: .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      8653: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8654: </style>
                   8655: <script type="text/javascript">
                   8656: // <![CDATA[
1.1045    www      8657: var LCprogressTxt='---';
                   8658: 
1.1075.2.130  raeburn  8659: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8660:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8661:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8662:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8663:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8664:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8665:    } else {
                   8666:        \$('#progressbar'+id).progressbar('value',percent);
                   8667:    }
1.1041    www      8668: }
                   8669: // ]]>
                   8670: </script>
                   8671: ENDPROGRESSUPDATE
                   8672: }
                   8673: 
1.1042    www      8674: my $LClastpercent;
1.1045    www      8675: my $LCidcnt;
                   8676: my $LCcurrentid;
1.1042    www      8677: 
1.1041    www      8678: sub LCprogressbar {
1.1075.2.130  raeburn  8679:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8680:     $LClastpercent=0;
1.1045    www      8681:     $LCidcnt++;
                   8682:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8683:     my ($starting,$content);
                   8684:     if ($number_to_do) {
                   8685:         $starting=&mt('Starting');
                   8686:         $content=(<<ENDPROGBAR);
                   8687: $preamble
1.1045    www      8688:   <div id="progressbar$LCcurrentid">
1.1041    www      8689:     <span class="pblabel">$starting</span>
                   8690:   </div>
                   8691: ENDPROGBAR
1.1075.2.130  raeburn  8692:     } else {
                   8693:         $starting=&mt('Loading...');
                   8694:         $LClastpercent='false';
                   8695:         $content=(<<ENDPROGBAR);
                   8696: $preamble
                   8697:   <div id="progressbar$LCcurrentid">
                   8698:       <div class="progress-label">$starting</div>
                   8699:   </div>
                   8700: ENDPROGBAR
                   8701:     }
                   8702:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8703: }
                   8704: 
                   8705: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8706:     my ($r,$val,$text,$number_to_do)=@_;
                   8707:     if ($number_to_do) {
                   8708:         unless ($val) { 
                   8709:             if ($LClastpercent) {
                   8710:                 $val=$LClastpercent;
                   8711:             } else {
                   8712:                 $val=0;
                   8713:             }
                   8714:         }
                   8715:         if ($val<0) { $val=0; }
                   8716:         if ($val>100) { $val=0; }
                   8717:         $LClastpercent=$val;
                   8718:         unless ($text) { $text=$val.'%'; }
                   8719:     } else {
                   8720:         $val = 'false';
1.1042    www      8721:     }
1.1041    www      8722:     $text=&js_ready($text);
1.1044    www      8723:     &r_print($r,<<ENDUPDATE);
1.1041    www      8724: <script type="text/javascript">
                   8725: // <![CDATA[
1.1075.2.130  raeburn  8726: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8727: // ]]>
                   8728: </script>
                   8729: ENDUPDATE
1.1035    www      8730: }
                   8731: 
1.1042    www      8732: sub LCprogressbarClose {
                   8733:     my ($r)=@_;
                   8734:     $LClastpercent=0;
1.1044    www      8735:     &r_print($r,<<ENDCLOSE);
1.1042    www      8736: <script type="text/javascript">
                   8737: // <![CDATA[
1.1045    www      8738: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8739: // ]]>
                   8740: </script>
                   8741: ENDCLOSE
1.1044    www      8742: }
                   8743: 
                   8744: sub r_print {
                   8745:     my ($r,$to_print)=@_;
                   8746:     if ($r) {
                   8747:       $r->print($to_print);
                   8748:       $r->rflush();
                   8749:     } else {
                   8750:       print($to_print);
                   8751:     }
1.1042    www      8752: }
                   8753: 
1.320     albertel 8754: sub html_encode {
                   8755:     my ($result) = @_;
                   8756: 
1.322     albertel 8757:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8758:     
                   8759:     return $result;
                   8760: }
1.1044    www      8761: 
1.317     albertel 8762: sub js_ready {
                   8763:     my ($result) = @_;
                   8764: 
1.323     albertel 8765:     $result =~ s/[\n\r]/ /xmsg;
                   8766:     $result =~ s/\\/\\\\/xmsg;
                   8767:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8768:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8769:     
                   8770:     return $result;
                   8771: }
                   8772: 
1.315     albertel 8773: sub validate_page {
                   8774:     if (  exists($env{'internal.start_page'})
1.316     albertel 8775: 	  &&     $env{'internal.start_page'} > 1) {
                   8776: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8777: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8778: 				 $ENV{'request.filename'});
1.315     albertel 8779:     }
                   8780:     if (  exists($env{'internal.end_page'})
1.316     albertel 8781: 	  &&     $env{'internal.end_page'} > 1) {
                   8782: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8783: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8784: 				 $env{'request.filename'});
1.315     albertel 8785:     }
                   8786:     if (     exists($env{'internal.start_page'})
                   8787: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8788: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8789: 				 $env{'request.filename'});
1.315     albertel 8790:     }
                   8791:     if (   ! exists($env{'internal.start_page'})
                   8792: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8793: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8794: 				 $env{'request.filename'});
1.315     albertel 8795:     }
1.306     albertel 8796: }
1.315     albertel 8797: 
1.996     www      8798: 
                   8799: sub start_scrollbox {
1.1075.2.56  raeburn  8800:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8801:     unless ($outerwidth) { $outerwidth='520px'; }
                   8802:     unless ($width) { $width='500px'; }
                   8803:     unless ($height) { $height='200px'; }
1.1075    raeburn  8804:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8805:     if ($id ne '') {
1.1075.2.42  raeburn  8806:         $table_id = ' id="table_'.$id.'"';
                   8807:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8808:     }
1.1075    raeburn  8809:     if ($bgcolor ne '') {
                   8810:         $tdcol = "background-color: $bgcolor;";
                   8811:     }
1.1075.2.42  raeburn  8812:     my $nicescroll_js;
                   8813:     if ($env{'browser.mobile'}) {
                   8814:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8815:     }
1.1075    raeburn  8816:     return <<"END";
1.1075.2.42  raeburn  8817: $nicescroll_js
                   8818: 
                   8819: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8820: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8821: END
1.996     www      8822: }
                   8823: 
                   8824: sub end_scrollbox {
1.1036    www      8825:     return '</div></td></tr></table>';
1.996     www      8826: }
                   8827: 
1.1075.2.42  raeburn  8828: sub nicescroll_javascript {
                   8829:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8830:     my %options;
                   8831:     if (ref($cursor) eq 'HASH') {
                   8832:         %options = %{$cursor};
                   8833:     }
                   8834:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8835:         $options{'railalign'} = 'left';
                   8836:     }
                   8837:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8838:         my $function  = &get_users_function();
                   8839:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8840:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8841:             $options{'cursorcolor'} = '#00F';
                   8842:         }
                   8843:     }
                   8844:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8845:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8846:             $options{'cursoropacity'}='1.0';
                   8847:         }
                   8848:     } else {
                   8849:         $options{'cursoropacity'}='1.0';
                   8850:     }
                   8851:     if ($options{'cursorfixedheight'} eq 'none') {
                   8852:         delete($options{'cursorfixedheight'});
                   8853:     } else {
                   8854:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8855:     }
                   8856:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8857:         delete($options{'railoffset'});
                   8858:     }
                   8859:     my @niceoptions;
                   8860:     while (my($key,$value) = each(%options)) {
                   8861:         if ($value =~ /^\{.+\}$/) {
                   8862:             push(@niceoptions,$key.':'.$value);
                   8863:         } else {
                   8864:             push(@niceoptions,$key.':"'.$value.'"');
                   8865:         }
                   8866:     }
                   8867:     my $nicescroll_js = '
                   8868: $(document).ready(
                   8869:       function() {
                   8870:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8871:       }
                   8872: );
                   8873: ';
                   8874:     if ($framecheck) {
                   8875:         $nicescroll_js .= '
                   8876: function expand_div(caller) {
                   8877:     if (top === self) {
                   8878:         document.getElementById("'.$id.'").style.width = "auto";
                   8879:         document.getElementById("'.$id.'").style.height = "auto";
                   8880:     } else {
                   8881:         try {
                   8882:             if (parent.frames) {
                   8883:                 if (parent.frames.length > 1) {
                   8884:                     var framesrc = parent.frames[1].location.href;
                   8885:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8886:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8887:                         document.getElementById("'.$id.'").style.width = "auto";
                   8888:                         document.getElementById("'.$id.'").style.height = "auto";
                   8889:                     }
                   8890:                 }
                   8891:             }
                   8892:         } catch (e) {
                   8893:             return;
                   8894:         }
                   8895:     }
                   8896:     return;
                   8897: }
                   8898: ';
                   8899:     }
                   8900:     if ($needjsready) {
                   8901:         $nicescroll_js = '
                   8902: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8903:     } else {
                   8904:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8905:     }
                   8906:     return $nicescroll_js;
                   8907: }
                   8908: 
1.318     albertel 8909: sub simple_error_page {
1.1075.2.49  raeburn  8910:     my ($r,$title,$msg,$args) = @_;
                   8911:     if (ref($args) eq 'HASH') {
                   8912:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8913:     } else {
                   8914:         $msg = &mt($msg);
                   8915:     }
                   8916: 
1.318     albertel 8917:     my $page =
                   8918: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8919: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8920: 	&Apache::loncommon::end_page();
                   8921:     if (ref($r)) {
                   8922: 	$r->print($page);
1.327     albertel 8923: 	return;
1.318     albertel 8924:     }
                   8925:     return $page;
                   8926: }
1.347     albertel 8927: 
                   8928: {
1.610     albertel 8929:     my @row_count;
1.961     onken    8930: 
                   8931:     sub start_data_table_count {
                   8932:         unshift(@row_count, 0);
                   8933:         return;
                   8934:     }
                   8935: 
                   8936:     sub end_data_table_count {
                   8937:         shift(@row_count);
                   8938:         return;
                   8939:     }
                   8940: 
1.347     albertel 8941:     sub start_data_table {
1.1018    raeburn  8942: 	my ($add_class,$id) = @_;
1.422     albertel 8943: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8944:         my $table_id;
                   8945:         if (defined($id)) {
                   8946:             $table_id = ' id="'.$id.'"';
                   8947:         }
1.961     onken    8948: 	&start_data_table_count();
1.1018    raeburn  8949: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8950:     }
                   8951: 
                   8952:     sub end_data_table {
1.961     onken    8953: 	&end_data_table_count();
1.389     albertel 8954: 	return '</table>'."\n";;
1.347     albertel 8955:     }
                   8956: 
                   8957:     sub start_data_table_row {
1.974     wenzelju 8958: 	my ($add_class, $id) = @_;
1.610     albertel 8959: 	$row_count[0]++;
                   8960: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8961: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8962:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8963:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8964:     }
1.471     banghart 8965:     
                   8966:     sub continue_data_table_row {
1.974     wenzelju 8967: 	my ($add_class, $id) = @_;
1.610     albertel 8968: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8969: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8970:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8971:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8972:     }
1.347     albertel 8973: 
                   8974:     sub end_data_table_row {
1.389     albertel 8975: 	return '</tr>'."\n";;
1.347     albertel 8976:     }
1.367     www      8977: 
1.421     albertel 8978:     sub start_data_table_empty_row {
1.707     bisitz   8979: #	$row_count[0]++;
1.421     albertel 8980: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8981:     }
                   8982: 
                   8983:     sub end_data_table_empty_row {
                   8984: 	return '</tr>'."\n";;
                   8985:     }
                   8986: 
1.367     www      8987:     sub start_data_table_header_row {
1.389     albertel 8988: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8989:     }
                   8990: 
                   8991:     sub end_data_table_header_row {
1.389     albertel 8992: 	return '</tr>'."\n";;
1.367     www      8993:     }
1.890     droeschl 8994: 
                   8995:     sub data_table_caption {
                   8996:         my $caption = shift;
                   8997:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8998:     }
1.347     albertel 8999: }
                   9000: 
1.548     albertel 9001: =pod
                   9002: 
                   9003: =item * &inhibit_menu_check($arg)
                   9004: 
                   9005: Checks for a inhibitmenu state and generates output to preserve it
                   9006: 
                   9007: Inputs:         $arg - can be any of
                   9008:                      - undef - in which case the return value is a string 
                   9009:                                to add  into arguments list of a uri
                   9010:                      - 'input' - in which case the return value is a HTML
                   9011:                                  <form> <input> field of type hidden to
                   9012:                                  preserve the value
                   9013:                      - a url - in which case the return value is the url with
                   9014:                                the neccesary cgi args added to preserve the
                   9015:                                inhibitmenu state
                   9016:                      - a ref to a url - no return value, but the string is
                   9017:                                         updated to include the neccessary cgi
                   9018:                                         args to preserve the inhibitmenu state
                   9019: 
                   9020: =cut
                   9021: 
                   9022: sub inhibit_menu_check {
                   9023:     my ($arg) = @_;
                   9024:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9025:     if ($arg eq 'input') {
                   9026: 	if ($env{'form.inhibitmenu'}) {
                   9027: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9028: 	} else {
                   9029: 	    return
                   9030: 	}
                   9031:     }
                   9032:     if ($env{'form.inhibitmenu'}) {
                   9033: 	if (ref($arg)) {
                   9034: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9035: 	} elsif ($arg eq '') {
                   9036: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9037: 	} else {
                   9038: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9039: 	}
                   9040:     }
                   9041:     if (!ref($arg)) {
                   9042: 	return $arg;
                   9043:     }
                   9044: }
                   9045: 
1.251     albertel 9046: ###############################################
1.182     matthew  9047: 
                   9048: =pod
                   9049: 
1.549     albertel 9050: =back
                   9051: 
                   9052: =head1 User Information Routines
                   9053: 
                   9054: =over 4
                   9055: 
1.405     albertel 9056: =item * &get_users_function()
1.182     matthew  9057: 
                   9058: Used by &bodytag to determine the current users primary role.
                   9059: Returns either 'student','coordinator','admin', or 'author'.
                   9060: 
                   9061: =cut
                   9062: 
                   9063: ###############################################
                   9064: sub get_users_function {
1.815     tempelho 9065:     my $function = 'norole';
1.818     tempelho 9066:     if ($env{'request.role'}=~/^(st)/) {
                   9067:         $function='student';
                   9068:     }
1.907     raeburn  9069:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9070:         $function='coordinator';
                   9071:     }
1.258     albertel 9072:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9073:         $function='admin';
                   9074:     }
1.826     bisitz   9075:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9076:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9077:         $function='author';
                   9078:     }
                   9079:     return $function;
1.54      www      9080: }
1.99      www      9081: 
                   9082: ###############################################
                   9083: 
1.233     raeburn  9084: =pod
                   9085: 
1.821     raeburn  9086: =item * &show_course()
                   9087: 
                   9088: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9089: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9090: 
                   9091: Inputs:
                   9092: None
                   9093: 
                   9094: Outputs:
                   9095: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9096: 
                   9097: =cut
                   9098: 
                   9099: ###############################################
                   9100: sub show_course {
                   9101:     my $course = !$env{'user.adv'};
                   9102:     if (!$env{'user.adv'}) {
                   9103:         foreach my $env (keys(%env)) {
                   9104:             next if ($env !~ m/^user\.priv\./);
                   9105:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9106:                 $course = 0;
                   9107:                 last;
                   9108:             }
                   9109:         }
                   9110:     }
                   9111:     return $course;
                   9112: }
                   9113: 
                   9114: ###############################################
                   9115: 
                   9116: =pod
                   9117: 
1.542     raeburn  9118: =item * &check_user_status()
1.274     raeburn  9119: 
                   9120: Determines current status of supplied role for a
                   9121: specific user. Roles can be active, previous or future.
                   9122: 
                   9123: Inputs: 
                   9124: user's domain, user's username, course's domain,
1.375     raeburn  9125: course's number, optional section ID.
1.274     raeburn  9126: 
                   9127: Outputs:
                   9128: role status: active, previous or future. 
                   9129: 
                   9130: =cut
                   9131: 
                   9132: sub check_user_status {
1.412     raeburn  9133:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9134:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9135:     my @uroles = keys(%userinfo);
1.274     raeburn  9136:     my $srchstr;
                   9137:     my $active_chk = 'none';
1.412     raeburn  9138:     my $now = time;
1.274     raeburn  9139:     if (@uroles > 0) {
1.908     raeburn  9140:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9141:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9142:         } else {
1.412     raeburn  9143:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9144:         }
                   9145:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9146:             my $role_end = 0;
                   9147:             my $role_start = 0;
                   9148:             $active_chk = 'active';
1.412     raeburn  9149:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9150:                 $role_end = $1;
                   9151:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9152:                     $role_start = $1;
1.274     raeburn  9153:                 }
                   9154:             }
                   9155:             if ($role_start > 0) {
1.412     raeburn  9156:                 if ($now < $role_start) {
1.274     raeburn  9157:                     $active_chk = 'future';
                   9158:                 }
                   9159:             }
                   9160:             if ($role_end > 0) {
1.412     raeburn  9161:                 if ($now > $role_end) {
1.274     raeburn  9162:                     $active_chk = 'previous';
                   9163:                 }
                   9164:             }
                   9165:         }
                   9166:     }
                   9167:     return $active_chk;
                   9168: }
                   9169: 
                   9170: ###############################################
                   9171: 
                   9172: =pod
                   9173: 
1.405     albertel 9174: =item * &get_sections()
1.233     raeburn  9175: 
                   9176: Determines all the sections for a course including
                   9177: sections with students and sections containing other roles.
1.419     raeburn  9178: Incoming parameters: 
                   9179: 
                   9180: 1. domain
                   9181: 2. course number 
                   9182: 3. reference to array containing roles for which sections should 
                   9183: be gathered (optional).
                   9184: 4. reference to array containing status types for which sections 
                   9185: should be gathered (optional).
                   9186: 
                   9187: If the third argument is undefined, sections are gathered for any role. 
                   9188: If the fourth argument is undefined, sections are gathered for any status.
                   9189: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9190:  
1.374     raeburn  9191: Returns section hash (keys are section IDs, values are
                   9192: number of users in each section), subject to the
1.419     raeburn  9193: optional roles filter, optional status filter 
1.233     raeburn  9194: 
                   9195: =cut
                   9196: 
                   9197: ###############################################
                   9198: sub get_sections {
1.419     raeburn  9199:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9200:     if (!defined($cdom) || !defined($cnum)) {
                   9201:         my $cid =  $env{'request.course.id'};
                   9202: 
                   9203: 	return if (!defined($cid));
                   9204: 
                   9205:         $cdom = $env{'course.'.$cid.'.domain'};
                   9206:         $cnum = $env{'course.'.$cid.'.num'};
                   9207:     }
                   9208: 
                   9209:     my %sectioncount;
1.419     raeburn  9210:     my $now = time;
1.240     albertel 9211: 
1.1075.2.33  raeburn  9212:     my $check_students = 1;
                   9213:     my $only_students = 0;
                   9214:     if (ref($possible_roles) eq 'ARRAY') {
                   9215:         if (grep(/^st$/,@{$possible_roles})) {
                   9216:             if (@{$possible_roles} == 1) {
                   9217:                 $only_students = 1;
                   9218:             }
                   9219:         } else {
                   9220:             $check_students = 0;
                   9221:         }
                   9222:     }
                   9223: 
                   9224:     if ($check_students) {
1.276     albertel 9225: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9226: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9227: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9228:         my $start_index = &Apache::loncoursedata::CL_START();
                   9229:         my $end_index = &Apache::loncoursedata::CL_END();
                   9230:         my $status;
1.366     albertel 9231: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9232: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9233: 				                     $data->[$status_index],
                   9234:                                                      $data->[$start_index],
                   9235:                                                      $data->[$end_index]);
                   9236:             if ($stu_status eq 'Active') {
                   9237:                 $status = 'active';
                   9238:             } elsif ($end < $now) {
                   9239:                 $status = 'previous';
                   9240:             } elsif ($start > $now) {
                   9241:                 $status = 'future';
                   9242:             } 
                   9243: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9244:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9245:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9246: 		    $sectioncount{$section}++;
                   9247:                 }
1.240     albertel 9248: 	    }
                   9249: 	}
                   9250:     }
1.1075.2.33  raeburn  9251:     if ($only_students) {
                   9252:         return %sectioncount;
                   9253:     }
1.240     albertel 9254:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9255:     foreach my $user (sort(keys(%courseroles))) {
                   9256: 	if ($user !~ /^(\w{2})/) { next; }
                   9257: 	my ($role) = ($user =~ /^(\w{2})/);
                   9258: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9259: 	my ($section,$status);
1.240     albertel 9260: 	if ($role eq 'cr' &&
                   9261: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9262: 	    $section=$1;
                   9263: 	}
                   9264: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9265: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9266:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9267:         if ($end == -1 && $start == -1) {
                   9268:             next; #deleted role
                   9269:         }
                   9270:         if (!defined($possible_status)) { 
                   9271:             $sectioncount{$section}++;
                   9272:         } else {
                   9273:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9274:                 $status = 'active';
                   9275:             } elsif ($end < $now) {
                   9276:                 $status = 'future';
                   9277:             } elsif ($start > $now) {
                   9278:                 $status = 'previous';
                   9279:             }
                   9280:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9281:                 $sectioncount{$section}++;
                   9282:             }
                   9283:         }
1.233     raeburn  9284:     }
1.366     albertel 9285:     return %sectioncount;
1.233     raeburn  9286: }
                   9287: 
1.274     raeburn  9288: ###############################################
1.294     raeburn  9289: 
                   9290: =pod
1.405     albertel 9291: 
                   9292: =item * &get_course_users()
                   9293: 
1.275     raeburn  9294: Retrieves usernames:domains for users in the specified course
                   9295: with specific role(s), and access status. 
                   9296: 
                   9297: Incoming parameters:
1.277     albertel 9298: 1. course domain
                   9299: 2. course number
                   9300: 3. access status: users must have - either active, 
1.275     raeburn  9301: previous, future, or all.
1.277     albertel 9302: 4. reference to array of permissible roles
1.288     raeburn  9303: 5. reference to array of section restrictions (optional)
                   9304: 6. reference to results object (hash of hashes).
                   9305: 7. reference to optional userdata hash
1.609     raeburn  9306: 8. reference to optional statushash
1.630     raeburn  9307: 9. flag if privileged users (except those set to unhide in
                   9308:    course settings) should be excluded    
1.609     raeburn  9309: Keys of top level results hash are roles.
1.275     raeburn  9310: Keys of inner hashes are username:domain, with 
                   9311: values set to access type.
1.288     raeburn  9312: Optional userdata hash returns an array with arguments in the 
                   9313: same order as loncoursedata::get_classlist() for student data.
                   9314: 
1.609     raeburn  9315: Optional statushash returns
                   9316: 
1.288     raeburn  9317: Entries for end, start, section and status are blank because
                   9318: of the possibility of multiple values for non-student roles.
                   9319: 
1.275     raeburn  9320: =cut
1.405     albertel 9321: 
1.275     raeburn  9322: ###############################################
1.405     albertel 9323: 
1.275     raeburn  9324: sub get_course_users {
1.630     raeburn  9325:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9326:     my %idx = ();
1.419     raeburn  9327:     my %seclists;
1.288     raeburn  9328: 
                   9329:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9330:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9331:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9332:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9333:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9334:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9335:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9336:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9337: 
1.290     albertel 9338:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9339:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9340:         my $now = time;
1.277     albertel 9341:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9342:             my $match = 0;
1.412     raeburn  9343:             my $secmatch = 0;
1.419     raeburn  9344:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9345:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9346:             if ($section eq '') {
                   9347:                 $section = 'none';
                   9348:             }
1.291     albertel 9349:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9350:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9351:                     $secmatch = 1;
                   9352:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9353:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9354:                         $secmatch = 1;
                   9355:                     }
                   9356:                 } else {  
1.419     raeburn  9357: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9358: 		        $secmatch = 1;
                   9359:                     }
1.290     albertel 9360: 		}
1.412     raeburn  9361:                 if (!$secmatch) {
                   9362:                     next;
                   9363:                 }
1.419     raeburn  9364:             }
1.275     raeburn  9365:             if (defined($$types{'active'})) {
1.288     raeburn  9366:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9367:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9368:                     $match = 1;
1.275     raeburn  9369:                 }
                   9370:             }
                   9371:             if (defined($$types{'previous'})) {
1.609     raeburn  9372:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9373:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9374:                     $match = 1;
1.275     raeburn  9375:                 }
                   9376:             }
                   9377:             if (defined($$types{'future'})) {
1.609     raeburn  9378:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9379:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9380:                     $match = 1;
1.275     raeburn  9381:                 }
                   9382:             }
1.609     raeburn  9383:             if ($match) {
                   9384:                 push(@{$seclists{$student}},$section);
                   9385:                 if (ref($userdata) eq 'HASH') {
                   9386:                     $$userdata{$student} = $$classlist{$student};
                   9387:                 }
                   9388:                 if (ref($statushash) eq 'HASH') {
                   9389:                     $statushash->{$student}{'st'}{$section} = $status;
                   9390:                 }
1.288     raeburn  9391:             }
1.275     raeburn  9392:         }
                   9393:     }
1.412     raeburn  9394:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9395:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9396:         my $now = time;
1.609     raeburn  9397:         my %displaystatus = ( previous => 'Expired',
                   9398:                               active   => 'Active',
                   9399:                               future   => 'Future',
                   9400:                             );
1.1075.2.36  raeburn  9401:         my (%nothide,@possdoms);
1.630     raeburn  9402:         if ($hidepriv) {
                   9403:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9404:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9405:                 if ($user !~ /:/) {
                   9406:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9407:                 } else {
                   9408:                     $nothide{$user} = 1;
                   9409:                 }
                   9410:             }
1.1075.2.36  raeburn  9411:             my @possdoms = ($cdom);
                   9412:             if ($coursehash{'checkforpriv'}) {
                   9413:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9414:             }
1.630     raeburn  9415:         }
1.439     raeburn  9416:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9417:             my $match = 0;
1.412     raeburn  9418:             my $secmatch = 0;
1.439     raeburn  9419:             my $status;
1.412     raeburn  9420:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9421:             $user =~ s/:$//;
1.439     raeburn  9422:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9423:             if ($end == -1 || $start == -1) {
                   9424:                 next;
                   9425:             }
                   9426:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9427:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9428:                 my ($uname,$udom) = split(/:/,$user);
                   9429:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9430:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9431:                         $secmatch = 1;
                   9432:                     } elsif ($usec eq '') {
1.420     albertel 9433:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9434:                             $secmatch = 1;
                   9435:                         }
                   9436:                     } else {
                   9437:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9438:                             $secmatch = 1;
                   9439:                         }
                   9440:                     }
                   9441:                     if (!$secmatch) {
                   9442:                         next;
                   9443:                     }
1.288     raeburn  9444:                 }
1.419     raeburn  9445:                 if ($usec eq '') {
                   9446:                     $usec = 'none';
                   9447:                 }
1.275     raeburn  9448:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9449:                     if ($hidepriv) {
1.1075.2.36  raeburn  9450:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9451:                             (!$nothide{$uname.':'.$udom})) {
                   9452:                             next;
                   9453:                         }
                   9454:                     }
1.503     raeburn  9455:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9456:                         $status = 'previous';
                   9457:                     } elsif ($start > $now) {
                   9458:                         $status = 'future';
                   9459:                     } else {
                   9460:                         $status = 'active';
                   9461:                     }
1.277     albertel 9462:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9463:                         if ($status eq $type) {
1.420     albertel 9464:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9465:                                 push(@{$$users{$role}{$user}},$type);
                   9466:                             }
1.288     raeburn  9467:                             $match = 1;
                   9468:                         }
                   9469:                     }
1.419     raeburn  9470:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9471:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9472: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9473:                         }
1.420     albertel 9474:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9475:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9476:                         }
1.609     raeburn  9477:                         if (ref($statushash) eq 'HASH') {
                   9478:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9479:                         }
1.275     raeburn  9480:                     }
                   9481:                 }
                   9482:             }
                   9483:         }
1.290     albertel 9484:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9485:             if ((defined($cdom)) && (defined($cnum))) {
                   9486:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9487:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9488:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9489:                     next if ($owner eq '');
                   9490:                     my ($ownername,$ownerdom);
                   9491:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9492:                         $ownername = $1;
                   9493:                         $ownerdom = $2;
                   9494:                     } else {
                   9495:                         $ownername = $owner;
                   9496:                         $ownerdom = $cdom;
                   9497:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9498:                     }
                   9499:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9500:                     if (defined($userdata) && 
1.609     raeburn  9501: 			!exists($$userdata{$owner})) {
                   9502: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9503:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9504:                             push(@{$seclists{$owner}},'none');
                   9505:                         }
                   9506:                         if (ref($statushash) eq 'HASH') {
                   9507:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9508:                         }
1.290     albertel 9509: 		    }
1.279     raeburn  9510:                 }
                   9511:             }
                   9512:         }
1.419     raeburn  9513:         foreach my $user (keys(%seclists)) {
                   9514:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9515:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9516:         }
1.275     raeburn  9517:     }
                   9518:     return;
                   9519: }
                   9520: 
1.288     raeburn  9521: sub get_user_info {
                   9522:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9523:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9524: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9525:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9526:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9527:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9528:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9529:     return;
                   9530: }
1.275     raeburn  9531: 
1.472     raeburn  9532: ###############################################
                   9533: 
                   9534: =pod
                   9535: 
                   9536: =item * &get_user_quota()
                   9537: 
1.1075.2.41  raeburn  9538: Retrieves quota assigned for storage of user files.
                   9539: Default is to report quota for portfolio files.
1.472     raeburn  9540: 
                   9541: Incoming parameters:
                   9542: 1. user's username
                   9543: 2. user's domain
1.1075.2.41  raeburn  9544: 3. quota name - portfolio, author, or course
                   9545:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9546: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9547:    course
1.472     raeburn  9548: 
                   9549: Returns:
1.1075.2.58  raeburn  9550: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9551: 2. (Optional) Type of setting: custom or default
                   9552:    (individually assigned or default for user's 
                   9553:    institutional status).
                   9554: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9555:    or student - types as defined in localenroll::inst_usertypes 
                   9556:    for user's domain, which determines default quota for user.
                   9557: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9558: 
                   9559: If a value has been stored in the user's environment, 
1.536     raeburn  9560: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9561: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9562: 
                   9563: =cut
                   9564: 
                   9565: ###############################################
                   9566: 
                   9567: 
                   9568: sub get_user_quota {
1.1075.2.42  raeburn  9569:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9570:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9571:     if (!defined($udom)) {
                   9572:         $udom = $env{'user.domain'};
                   9573:     }
                   9574:     if (!defined($uname)) {
                   9575:         $uname = $env{'user.name'};
                   9576:     }
                   9577:     if (($udom eq '' || $uname eq '') ||
                   9578:         ($udom eq 'public') && ($uname eq 'public')) {
                   9579:         $quota = 0;
1.536     raeburn  9580:         $quotatype = 'default';
                   9581:         $defquota = 0; 
1.472     raeburn  9582:     } else {
1.536     raeburn  9583:         my $inststatus;
1.1075.2.41  raeburn  9584:         if ($quotaname eq 'course') {
                   9585:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9586:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9587:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9588:             } else {
                   9589:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9590:                 $quota = $cenv{'internal.uploadquota'};
                   9591:             }
1.536     raeburn  9592:         } else {
1.1075.2.41  raeburn  9593:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9594:                 if ($quotaname eq 'author') {
                   9595:                     $quota = $env{'environment.authorquota'};
                   9596:                 } else {
                   9597:                     $quota = $env{'environment.portfolioquota'};
                   9598:                 }
                   9599:                 $inststatus = $env{'environment.inststatus'};
                   9600:             } else {
                   9601:                 my %userenv = 
                   9602:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9603:                                          'authorquota','inststatus'],$udom,$uname);
                   9604:                 my ($tmp) = keys(%userenv);
                   9605:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9606:                     if ($quotaname eq 'author') {
                   9607:                         $quota = $userenv{'authorquota'};
                   9608:                     } else {
                   9609:                         $quota = $userenv{'portfolioquota'};
                   9610:                     }
                   9611:                     $inststatus = $userenv{'inststatus'};
                   9612:                 } else {
                   9613:                     undef(%userenv);
                   9614:                 }
                   9615:             }
                   9616:         }
                   9617:         if ($quota eq '' || wantarray) {
                   9618:             if ($quotaname eq 'course') {
                   9619:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9620:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9621:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9622:                     $defquota = $domdefs{$crstype.'quota'};
                   9623:                 }
                   9624:                 if ($defquota eq '') {
                   9625:                     $defquota = 500;
                   9626:                 }
1.1075.2.41  raeburn  9627:             } else {
                   9628:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9629:             }
                   9630:             if ($quota eq '') {
                   9631:                 $quota = $defquota;
                   9632:                 $quotatype = 'default';
                   9633:             } else {
                   9634:                 $quotatype = 'custom';
                   9635:             }
1.472     raeburn  9636:         }
                   9637:     }
1.536     raeburn  9638:     if (wantarray) {
                   9639:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9640:     } else {
                   9641:         return $quota;
                   9642:     }
1.472     raeburn  9643: }
                   9644: 
                   9645: ###############################################
                   9646: 
                   9647: =pod
                   9648: 
                   9649: =item * &default_quota()
                   9650: 
1.536     raeburn  9651: Retrieves default quota assigned for storage of user portfolio files,
                   9652: given an (optional) user's institutional status.
1.472     raeburn  9653: 
                   9654: Incoming parameters:
1.1075.2.42  raeburn  9655: 
1.472     raeburn  9656: 1. domain
1.536     raeburn  9657: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9658:    status types (e.g., faculty, staff, student etc.)
                   9659:    which apply to the user for whom the default is being retrieved.
                   9660:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9661:    default quota will be returned.
                   9662: 3.  quota name - portfolio, author, or course
                   9663:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9664: 
                   9665: Returns:
1.1075.2.42  raeburn  9666: 
1.1075.2.58  raeburn  9667: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9668: 2. (Optional) institutional type which determined the value of the
                   9669:    default quota.
1.472     raeburn  9670: 
                   9671: If a value has been stored in the domain's configuration db,
                   9672: it will return that, otherwise it returns 20 (for backwards 
                   9673: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9674: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9675: 
1.536     raeburn  9676: If the user's status includes multiple types (e.g., staff and student),
                   9677: the largest default quota which applies to the user determines the
                   9678: default quota returned.
                   9679: 
1.472     raeburn  9680: =cut
                   9681: 
                   9682: ###############################################
                   9683: 
                   9684: 
                   9685: sub default_quota {
1.1075.2.41  raeburn  9686:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9687:     my ($defquota,$settingstatus);
                   9688:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9689:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9690:     my $key = 'defaultquota';
                   9691:     if ($quotaname eq 'author') {
                   9692:         $key = 'authorquota';
                   9693:     }
1.622     raeburn  9694:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9695:         if ($inststatus ne '') {
1.765     raeburn  9696:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9697:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9698:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9699:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9700:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9701:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9702:                             $settingstatus = $item;
1.1075.2.41  raeburn  9703:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9704:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9705:                             $settingstatus = $item;
                   9706:                         }
                   9707:                     }
1.1075.2.41  raeburn  9708:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9709:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9710:                         if ($defquota eq '') {
                   9711:                             $defquota = $quotahash{'quotas'}{$item};
                   9712:                             $settingstatus = $item;
                   9713:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9714:                             $defquota = $quotahash{'quotas'}{$item};
                   9715:                             $settingstatus = $item;
                   9716:                         }
1.536     raeburn  9717:                     }
                   9718:                 }
                   9719:             }
                   9720:         }
                   9721:         if ($defquota eq '') {
1.1075.2.41  raeburn  9722:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9723:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9724:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9725:                 $defquota = $quotahash{'quotas'}{'default'};
                   9726:             }
1.536     raeburn  9727:             $settingstatus = 'default';
1.1075.2.42  raeburn  9728:             if ($defquota eq '') {
                   9729:                 if ($quotaname eq 'author') {
                   9730:                     $defquota = 500;
                   9731:                 }
                   9732:             }
1.536     raeburn  9733:         }
                   9734:     } else {
                   9735:         $settingstatus = 'default';
1.1075.2.41  raeburn  9736:         if ($quotaname eq 'author') {
                   9737:             $defquota = 500;
                   9738:         } else {
                   9739:             $defquota = 20;
                   9740:         }
1.536     raeburn  9741:     }
                   9742:     if (wantarray) {
                   9743:         return ($defquota,$settingstatus);
1.472     raeburn  9744:     } else {
1.536     raeburn  9745:         return $defquota;
1.472     raeburn  9746:     }
                   9747: }
                   9748: 
1.1075.2.41  raeburn  9749: ###############################################
                   9750: 
                   9751: =pod
                   9752: 
1.1075.2.42  raeburn  9753: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9754: 
                   9755: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9756: of existing file within authoring space will cause quota for the authoring
                   9757: space to be exceeded.
                   9758: 
                   9759: Same, if upload of a file directly to a course/community via Course Editor
                   9760: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9761: 
1.1075.2.61  raeburn  9762: Inputs: 7 
1.1075.2.42  raeburn  9763: 1. username or coursenum
1.1075.2.41  raeburn  9764: 2. domain
1.1075.2.42  raeburn  9765: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9766: 4. filename of file for which action is being requested
                   9767: 5. filesize (kB) of file
                   9768: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9769: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9770: 
                   9771: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9772:          otherwise return null.
                   9773: 
1.1075.2.42  raeburn  9774: =back
                   9775: 
1.1075.2.41  raeburn  9776: =cut
                   9777: 
1.1075.2.42  raeburn  9778: sub excess_filesize_warning {
1.1075.2.59  raeburn  9779:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9780:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9781:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9782:     if ($context eq 'author') {
                   9783:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9784:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9785:     } else {
                   9786:         foreach my $subdir ('docs','supplemental') {
                   9787:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9788:         }
                   9789:     }
1.1075.2.41  raeburn  9790:     $disk_quota = int($disk_quota * 1000);
                   9791:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9792:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9793:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9794:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9795:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9796:                             $disk_quota,$current_disk_usage).
                   9797:                '</p>';
                   9798:     }
                   9799:     return;
                   9800: }
                   9801: 
                   9802: ###############################################
                   9803: 
                   9804: 
1.384     raeburn  9805: sub get_secgrprole_info {
                   9806:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9807:     my %sections_count = &get_sections($cdom,$cnum);
                   9808:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9809:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9810:     my @groups = sort(keys(%curr_groups));
                   9811:     my $allroles = [];
                   9812:     my $rolehash;
                   9813:     my $accesshash = {
                   9814:                      active => 'Currently has access',
                   9815:                      future => 'Will have future access',
                   9816:                      previous => 'Previously had access',
                   9817:                   };
                   9818:     if ($needroles) {
                   9819:         $rolehash = {'all' => 'all'};
1.385     albertel 9820:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9821: 	if (&Apache::lonnet::error(%user_roles)) {
                   9822: 	    undef(%user_roles);
                   9823: 	}
                   9824:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9825:             my ($role)=split(/\:/,$item,2);
                   9826:             if ($role eq 'cr') { next; }
                   9827:             if ($role =~ /^cr/) {
                   9828:                 $$rolehash{$role} = (split('/',$role))[3];
                   9829:             } else {
                   9830:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9831:             }
                   9832:         }
                   9833:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9834:             push(@{$allroles},$key);
                   9835:         }
                   9836:         push (@{$allroles},'st');
                   9837:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9838:     }
                   9839:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9840: }
                   9841: 
1.555     raeburn  9842: sub user_picker {
1.1075.2.127  raeburn  9843:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9844:     my $currdom = $dom;
1.1075.2.114  raeburn  9845:     my @alldoms = &Apache::lonnet::all_domains();
                   9846:     if (@alldoms == 1) {
                   9847:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9848:                                                ['directorysrch'],$alldoms[0]);
                   9849:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9850:         my $showdom = $domdesc;
                   9851:         if ($showdom eq '') {
                   9852:             $showdom = $dom;
                   9853:         }
                   9854:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9855:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9856:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9857:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9858:             }
                   9859:         }
                   9860:     }
1.555     raeburn  9861:     my %curr_selected = (
                   9862:                         srchin => 'dom',
1.580     raeburn  9863:                         srchby => 'lastname',
1.555     raeburn  9864:                       );
                   9865:     my $srchterm;
1.625     raeburn  9866:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9867:         if ($srch->{'srchby'} ne '') {
                   9868:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9869:         }
                   9870:         if ($srch->{'srchin'} ne '') {
                   9871:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9872:         }
                   9873:         if ($srch->{'srchtype'} ne '') {
                   9874:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9875:         }
                   9876:         if ($srch->{'srchdomain'} ne '') {
                   9877:             $currdom = $srch->{'srchdomain'};
                   9878:         }
                   9879:         $srchterm = $srch->{'srchterm'};
                   9880:     }
1.1075.2.98  raeburn  9881:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9882:                     'usr'       => 'Search criteria',
1.563     raeburn  9883:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9884:                     'uname'     => 'username',
                   9885:                     'lastname'  => 'last name',
1.555     raeburn  9886:                     'lastfirst' => 'last name, first name',
1.558     albertel 9887:                     'crs'       => 'in this course',
1.576     raeburn  9888:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9889:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9890:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9891:                     'exact'     => 'is',
                   9892:                     'contains'  => 'contains',
1.569     raeburn  9893:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9894:                                        );
                   9895:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9896:                     'youm'      => "You must include some text to search for.",
                   9897:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9898:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9899:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9900:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9901:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9902:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9903:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9904:                                        );
1.1075.2.98  raeburn  9905:     &html_escape(\%html_lt);
                   9906:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9907:     my $domform;
1.1075.2.126  raeburn  9908:     my $allow_blank = 1;
1.1075.2.115  raeburn  9909:     if ($fixeddom) {
1.1075.2.126  raeburn  9910:         $allow_blank = 0;
                   9911:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9912:     } else {
1.1075.2.126  raeburn  9913:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9914:     }
1.563     raeburn  9915:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9916: 
                   9917:     my @srchins = ('crs','dom','alc','instd');
                   9918: 
                   9919:     foreach my $option (@srchins) {
                   9920:         # FIXME 'alc' option unavailable until 
                   9921:         #       loncreateuser::print_user_query_page()
                   9922:         #       has been completed.
                   9923:         next if ($option eq 'alc');
1.880     raeburn  9924:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9925:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9926:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9927:         if ($curr_selected{'srchin'} eq $option) {
                   9928:             $srchinsel .= ' 
1.1075.2.98  raeburn  9929:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9930:         } else {
                   9931:             $srchinsel .= '
1.1075.2.98  raeburn  9932:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9933:         }
1.555     raeburn  9934:     }
1.563     raeburn  9935:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9936: 
                   9937:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9938:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9939:         if ($curr_selected{'srchby'} eq $option) {
                   9940:             $srchbysel .= '
1.1075.2.98  raeburn  9941:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9942:         } else {
                   9943:             $srchbysel .= '
1.1075.2.98  raeburn  9944:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9945:          }
                   9946:     }
                   9947:     $srchbysel .= "\n  </select>\n";
                   9948: 
                   9949:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9950:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9951:         if ($curr_selected{'srchtype'} eq $option) {
                   9952:             $srchtypesel .= '
1.1075.2.98  raeburn  9953:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9954:         } else {
                   9955:             $srchtypesel .= '
1.1075.2.98  raeburn  9956:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9957:         }
                   9958:     }
                   9959:     $srchtypesel .= "\n  </select>\n";
                   9960: 
1.558     albertel 9961:     my ($newuserscript,$new_user_create);
1.994     raeburn  9962:     my $context_dom = $env{'request.role.domain'};
                   9963:     if ($context eq 'requestcrs') {
                   9964:         if ($env{'form.coursedom'} ne '') { 
                   9965:             $context_dom = $env{'form.coursedom'};
                   9966:         }
                   9967:     }
1.556     raeburn  9968:     if ($forcenewuser) {
1.576     raeburn  9969:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9970:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9971:                 if ($cancreate) {
                   9972:                     $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>';
                   9973:                 } else {
1.799     bisitz   9974:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9975:                     my %usertypetext = (
                   9976:                         official   => 'institutional',
                   9977:                         unofficial => 'non-institutional',
                   9978:                     );
1.799     bisitz   9979:                     $new_user_create = '<p class="LC_warning">'
                   9980:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9981:                                       .' '
                   9982:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9983:                                           ,'<a href="'.$helplink.'">','</a>')
                   9984:                                       .'</p><br />';
1.627     raeburn  9985:                 }
1.576     raeburn  9986:             }
                   9987:         }
                   9988: 
1.556     raeburn  9989:         $newuserscript = <<"ENDSCRIPT";
                   9990: 
1.570     raeburn  9991: function setSearch(createnew,callingForm) {
1.556     raeburn  9992:     if (createnew == 1) {
1.570     raeburn  9993:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9994:             if (callingForm.srchby.options[i].value == 'uname') {
                   9995:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9996:             }
                   9997:         }
1.570     raeburn  9998:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9999:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10000: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10001:             }
                   10002:         }
1.570     raeburn  10003:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10004:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10005:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10006:             }
                   10007:         }
1.570     raeburn  10008:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10009:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10010:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10011:             }
                   10012:         }
                   10013:     }
                   10014: }
                   10015: ENDSCRIPT
1.558     albertel 10016: 
1.556     raeburn  10017:     }
                   10018: 
1.555     raeburn  10019:     my $output = <<"END_BLOCK";
1.556     raeburn  10020: <script type="text/javascript">
1.824     bisitz   10021: // <![CDATA[
1.570     raeburn  10022: function validateEntry(callingForm) {
1.558     albertel 10023: 
1.556     raeburn  10024:     var checkok = 1;
1.558     albertel 10025:     var srchin;
1.570     raeburn  10026:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10027: 	if ( callingForm.srchin[i].checked ) {
                   10028: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10029: 	}
                   10030:     }
                   10031: 
1.570     raeburn  10032:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10033:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10034:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10035:     var srchterm =  callingForm.srchterm.value;
                   10036:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10037:     var msg = "";
                   10038: 
                   10039:     if (srchterm == "") {
                   10040:         checkok = 0;
1.1075.2.98  raeburn  10041:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10042:     }
                   10043: 
1.569     raeburn  10044:     if (srchtype== 'begins') {
                   10045:         if (srchterm.length < 2) {
                   10046:             checkok = 0;
1.1075.2.98  raeburn  10047:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10048:         }
                   10049:     }
                   10050: 
1.556     raeburn  10051:     if (srchtype== 'contains') {
                   10052:         if (srchterm.length < 3) {
                   10053:             checkok = 0;
1.1075.2.98  raeburn  10054:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10055:         }
                   10056:     }
                   10057:     if (srchin == 'instd') {
                   10058:         if (srchdomain == '') {
                   10059:             checkok = 0;
1.1075.2.98  raeburn  10060:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10061:         }
                   10062:     }
                   10063:     if (srchin == 'dom') {
                   10064:         if (srchdomain == '') {
                   10065:             checkok = 0;
1.1075.2.98  raeburn  10066:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10067:         }
                   10068:     }
                   10069:     if (srchby == 'lastfirst') {
                   10070:         if (srchterm.indexOf(",") == -1) {
                   10071:             checkok = 0;
1.1075.2.98  raeburn  10072:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10073:         }
                   10074:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10075:             checkok = 0;
1.1075.2.98  raeburn  10076:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10077:         }
                   10078:     }
                   10079:     if (checkok == 0) {
1.1075.2.98  raeburn  10080:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10081:         return;
                   10082:     }
                   10083:     if (checkok == 1) {
1.570     raeburn  10084:         callingForm.submit();
1.556     raeburn  10085:     }
                   10086: }
                   10087: 
                   10088: $newuserscript
                   10089: 
1.824     bisitz   10090: // ]]>
1.556     raeburn  10091: </script>
1.558     albertel 10092: 
                   10093: $new_user_create
                   10094: 
1.555     raeburn  10095: END_BLOCK
1.558     albertel 10096: 
1.876     raeburn  10097:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10098:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10099:                $domform.
                   10100:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10101:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10102:                $srchbysel.
                   10103:                $srchtypesel. 
                   10104:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10105:                $srchinsel.
                   10106:                &Apache::lonhtmlcommon::row_closure(1). 
                   10107:                &Apache::lonhtmlcommon::end_pick_box().
                   10108:                '<br />';
1.1075.2.114  raeburn  10109:     return ($output,1);
1.555     raeburn  10110: }
                   10111: 
1.612     raeburn  10112: sub user_rule_check {
1.615     raeburn  10113:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10114:     my ($response,%inst_response);
1.612     raeburn  10115:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10116:         if (keys(%{$usershash}) > 1) {
                   10117:             my (%by_username,%by_id,%userdoms);
                   10118:             my $checkid;
1.612     raeburn  10119:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10120:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10121:                     $checkid = 1;
                   10122:                 }
                   10123:             }
                   10124:             foreach my $user (keys(%{$usershash})) {
                   10125:                 my ($uname,$udom) = split(/:/,$user);
                   10126:                 if ($checkid) {
                   10127:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10128:                         if ($usershash->{$user}->{'id'} ne '') {
                   10129:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10130:                             $userdoms{$udom} = 1;
                   10131:                             if (ref($inst_results) eq 'HASH') {
                   10132:                                 $inst_results->{$uname.':'.$udom} = {};
                   10133:                             }
                   10134:                         }
                   10135:                     }
                   10136:                 } else {
                   10137:                     $by_username{$udom}{$uname} = 1;
                   10138:                     $userdoms{$udom} = 1;
                   10139:                     if (ref($inst_results) eq 'HASH') {
                   10140:                         $inst_results->{$uname.':'.$udom} = {};
                   10141:                     }
                   10142:                 }
                   10143:             }
                   10144:             foreach my $udom (keys(%userdoms)) {
                   10145:                 if (!$got_rules->{$udom}) {
                   10146:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10147:                                                              ['usercreation'],$udom);
                   10148:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10149:                         foreach my $item ('username','id') {
                   10150:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10151:                                 $$curr_rules{$udom}{$item} =
                   10152:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10153:                             }
                   10154:                         }
                   10155:                     }
                   10156:                     $got_rules->{$udom} = 1;
                   10157:                 }
                   10158:             }
                   10159:             if ($checkid) {
                   10160:                 foreach my $udom (keys(%by_id)) {
                   10161:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10162:                     if ($outcome eq 'ok') {
                   10163:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10164:                             my $uname = $by_id{$udom}{$id};
                   10165:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10166:                         }
                   10167:                         if (ref($results) eq 'HASH') {
                   10168:                             foreach my $uname (keys(%{$results})) {
                   10169:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10170:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10171:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10172:                                 }
                   10173:                             }
                   10174:                         }
                   10175:                     }
1.612     raeburn  10176:                 }
1.615     raeburn  10177:             } else {
1.1075.2.99  raeburn  10178:                 foreach my $udom (keys(%by_username)) {
                   10179:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10180:                     if ($outcome eq 'ok') {
                   10181:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10182:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10183:                         }
                   10184:                         if (ref($results) eq 'HASH') {
                   10185:                             foreach my $uname (keys(%{$results})) {
                   10186:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10187:                             }
                   10188:                         }
                   10189:                     }
                   10190:                 }
1.612     raeburn  10191:             }
1.1075.2.99  raeburn  10192:         } elsif (keys(%{$usershash}) == 1) {
                   10193:             my $user = (keys(%{$usershash}))[0];
                   10194:             my ($uname,$udom) = split(/:/,$user);
                   10195:             if (($udom ne '') && ($uname ne '')) {
                   10196:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10197:                     if (ref($checks) eq 'HASH') {
                   10198:                         if (defined($checks->{'username'})) {
                   10199:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10200:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10201:                         } elsif (defined($checks->{'id'})) {
                   10202:                             if ($usershash->{$user}->{'id'} ne '') {
                   10203:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10204:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10205:                                                                   $usershash->{$user}->{'id'});
                   10206:                             } else {
                   10207:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10208:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10209:                             }
                   10210:                         }
                   10211:                     } else {
                   10212:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10213:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10214:                        return;
                   10215:                     }
                   10216:                     if (!$got_rules->{$udom}) {
                   10217:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10218:                                                                  ['usercreation'],$udom);
                   10219:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10220:                             foreach my $item ('username','id') {
                   10221:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10222:                                    $$curr_rules{$udom}{$item} =
                   10223:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10224:                                 }
                   10225:                             }
1.585     raeburn  10226:                         }
1.1075.2.99  raeburn  10227:                         $got_rules->{$udom} = 1;
1.585     raeburn  10228:                     }
                   10229:                 }
1.1075.2.99  raeburn  10230:             } else {
                   10231:                 return;
                   10232:             }
                   10233:         } else {
                   10234:             return;
                   10235:         }
                   10236:         foreach my $user (keys(%{$usershash})) {
                   10237:             my ($uname,$udom) = split(/:/,$user);
                   10238:             next if (($udom eq '') || ($uname eq ''));
                   10239:             my $id;
                   10240:             if (ref($inst_results) eq 'HASH') {
                   10241:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10242:                     $id = $inst_results->{$user}->{'id'};
                   10243:                 }
                   10244:             }
                   10245:             if ($id eq '') {
                   10246:                 if (ref($usershash->{$user})) {
                   10247:                     $id = $usershash->{$user}->{'id'};
                   10248:                 }
1.585     raeburn  10249:             }
1.612     raeburn  10250:             foreach my $item (keys(%{$checks})) {
                   10251:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10252:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10253:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10254:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10255:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10256:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10257:                                 if ($rule_check{$rule}) {
                   10258:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10259:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10260:                                         if (ref($inst_results) eq 'HASH') {
                   10261:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10262:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10263:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10264:                                                 } elsif ($item eq 'id') {
                   10265:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10266:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10267:                                                     }
1.615     raeburn  10268:                                                 }
1.612     raeburn  10269:                                             }
                   10270:                                         }
1.615     raeburn  10271:                                     }
                   10272:                                     last;
1.585     raeburn  10273:                                 }
                   10274:                             }
                   10275:                         }
                   10276:                     }
                   10277:                 }
                   10278:             }
                   10279:         }
                   10280:     }
1.612     raeburn  10281:     return;
                   10282: }
                   10283: 
                   10284: sub user_rule_formats {
                   10285:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10286:     my %text = ( 
                   10287:                  'username' => 'Usernames',
                   10288:                  'id'       => 'IDs',
                   10289:                );
                   10290:     my $output;
                   10291:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10292:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10293:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10294:             $output = '<br />'.
                   10295:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10296:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10297:                       ' <ul>';
1.612     raeburn  10298:             foreach my $rule (@{$ruleorder}) {
                   10299:                 if (ref($curr_rules) eq 'ARRAY') {
                   10300:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10301:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10302:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10303:                                         $rules->{$rule}{'desc'}.'</li>';
                   10304:                         }
                   10305:                     }
                   10306:                 }
                   10307:             }
                   10308:             $output .= '</ul>';
                   10309:         }
                   10310:     }
                   10311:     return $output;
                   10312: }
                   10313: 
                   10314: sub instrule_disallow_msg {
1.615     raeburn  10315:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10316:     my $response;
                   10317:     my %text = (
                   10318:                   item   => 'username',
                   10319:                   items  => 'usernames',
                   10320:                   match  => 'matches',
                   10321:                   do     => 'does',
                   10322:                   action => 'a username',
                   10323:                   one    => 'one',
                   10324:                );
                   10325:     if ($count > 1) {
                   10326:         $text{'item'} = 'usernames';
                   10327:         $text{'match'} ='match';
                   10328:         $text{'do'} = 'do';
                   10329:         $text{'action'} = 'usernames',
                   10330:         $text{'one'} = 'ones';
                   10331:     }
                   10332:     if ($checkitem eq 'id') {
                   10333:         $text{'items'} = 'IDs';
                   10334:         $text{'item'} = 'ID';
                   10335:         $text{'action'} = 'an ID';
1.615     raeburn  10336:         if ($count > 1) {
                   10337:             $text{'item'} = 'IDs';
                   10338:             $text{'action'} = 'IDs';
                   10339:         }
1.612     raeburn  10340:     }
1.674     bisitz   10341:     $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  10342:     if ($mode eq 'upload') {
                   10343:         if ($checkitem eq 'username') {
                   10344:             $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'}.");
                   10345:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10346:             $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  10347:         }
1.669     raeburn  10348:     } elsif ($mode eq 'selfcreate') {
                   10349:         if ($checkitem eq 'id') {
                   10350:             $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.");
                   10351:         }
1.615     raeburn  10352:     } else {
                   10353:         if ($checkitem eq 'username') {
                   10354:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10355:         } elsif ($checkitem eq 'id') {
                   10356:             $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.");
                   10357:         }
1.612     raeburn  10358:     }
                   10359:     return $response;
1.585     raeburn  10360: }
                   10361: 
1.624     raeburn  10362: sub personal_data_fieldtitles {
                   10363:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10364:                         id => 'Student/Employee ID',
                   10365:                         permanentemail => 'E-mail address',
                   10366:                         lastname => 'Last Name',
                   10367:                         firstname => 'First Name',
                   10368:                         middlename => 'Middle Name',
                   10369:                         generation => 'Generation',
                   10370:                         gen => 'Generation',
1.765     raeburn  10371:                         inststatus => 'Affiliation',
1.624     raeburn  10372:                    );
                   10373:     return %fieldtitles;
                   10374: }
                   10375: 
1.642     raeburn  10376: sub sorted_inst_types {
                   10377:     my ($dom) = @_;
1.1075.2.70  raeburn  10378:     my ($usertypes,$order);
                   10379:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10380:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10381:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10382:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10383:     } else {
                   10384:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10385:     }
1.642     raeburn  10386:     my $othertitle = &mt('All users');
                   10387:     if ($env{'request.course.id'}) {
1.668     raeburn  10388:         $othertitle  = &mt('Any users');
1.642     raeburn  10389:     }
                   10390:     my @types;
                   10391:     if (ref($order) eq 'ARRAY') {
                   10392:         @types = @{$order};
                   10393:     }
                   10394:     if (@types == 0) {
                   10395:         if (ref($usertypes) eq 'HASH') {
                   10396:             @types = sort(keys(%{$usertypes}));
                   10397:         }
                   10398:     }
                   10399:     if (keys(%{$usertypes}) > 0) {
                   10400:         $othertitle = &mt('Other users');
                   10401:     }
                   10402:     return ($othertitle,$usertypes,\@types);
                   10403: }
                   10404: 
1.645     raeburn  10405: sub get_institutional_codes {
                   10406:     my ($settings,$allcourses,$LC_code) = @_;
                   10407: # Get complete list of course sections to update
                   10408:     my @currsections = ();
                   10409:     my @currxlists = ();
                   10410:     my $coursecode = $$settings{'internal.coursecode'};
                   10411: 
                   10412:     if ($$settings{'internal.sectionnums'} ne '') {
                   10413:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10414:     }
                   10415: 
                   10416:     if ($$settings{'internal.crosslistings'} ne '') {
                   10417:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10418:     }
                   10419: 
                   10420:     if (@currxlists > 0) {
                   10421:         foreach (@currxlists) {
                   10422:             if (m/^([^:]+):(\w*)$/) {
                   10423:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10424:                     push(@{$allcourses},$1);
1.645     raeburn  10425:                     $$LC_code{$1} = $2;
                   10426:                 }
                   10427:             }
                   10428:         }
                   10429:     }
                   10430:  
                   10431:     if (@currsections > 0) {
                   10432:         foreach (@currsections) {
                   10433:             if (m/^(\w+):(\w*)$/) {
                   10434:                 my $sec = $coursecode.$1;
                   10435:                 my $lc_sec = $2;
                   10436:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10437:                     push(@{$allcourses},$sec);
1.645     raeburn  10438:                     $$LC_code{$sec} = $lc_sec;
                   10439:                 }
                   10440:             }
                   10441:         }
                   10442:     }
                   10443:     return;
                   10444: }
                   10445: 
1.971     raeburn  10446: sub get_standard_codeitems {
                   10447:     return ('Year','Semester','Department','Number','Section');
                   10448: }
                   10449: 
1.112     bowersj2 10450: =pod
                   10451: 
1.780     raeburn  10452: =head1 Slot Helpers
                   10453: 
                   10454: =over 4
                   10455: 
                   10456: =item * sorted_slots()
                   10457: 
1.1040    raeburn  10458: Sorts an array of slot names in order of an optional sort key,
                   10459: default sort is by slot start time (earliest first). 
1.780     raeburn  10460: 
                   10461: Inputs:
                   10462: 
                   10463: =over 4
                   10464: 
                   10465: slotsarr  - Reference to array of unsorted slot names.
                   10466: 
                   10467: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10468: 
1.1040    raeburn  10469: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10470: 
1.549     albertel 10471: =back
                   10472: 
1.780     raeburn  10473: Returns:
                   10474: 
                   10475: =over 4
                   10476: 
1.1040    raeburn  10477: sorted   - An array of slot names sorted by a specified sort key 
                   10478:            (default sort key is start time of the slot).
1.780     raeburn  10479: 
                   10480: =back
                   10481: 
                   10482: =cut
                   10483: 
                   10484: 
                   10485: sub sorted_slots {
1.1040    raeburn  10486:     my ($slotsarr,$slots,$sortkey) = @_;
                   10487:     if ($sortkey eq '') {
                   10488:         $sortkey = 'starttime';
                   10489:     }
1.780     raeburn  10490:     my @sorted;
                   10491:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10492:         @sorted =
                   10493:             sort {
                   10494:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10495:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10496:                      }
                   10497:                      if (ref($slots->{$a})) { return -1;}
                   10498:                      if (ref($slots->{$b})) { return 1;}
                   10499:                      return 0;
                   10500:                  } @{$slotsarr};
                   10501:     }
                   10502:     return @sorted;
                   10503: }
                   10504: 
1.1040    raeburn  10505: =pod
                   10506: 
                   10507: =item * get_future_slots()
                   10508: 
                   10509: Inputs:
                   10510: 
                   10511: =over 4
                   10512: 
                   10513: cnum - course number
                   10514: 
                   10515: cdom - course domain
                   10516: 
                   10517: now - current UNIX time
                   10518: 
                   10519: symb - optional symb
                   10520: 
                   10521: =back
                   10522: 
                   10523: Returns:
                   10524: 
                   10525: =over 4
                   10526: 
                   10527: sorted_reservable - ref to array of student_schedulable slots currently 
                   10528:                     reservable, ordered by end date of reservation period.
                   10529: 
                   10530: reservable_now - ref to hash of student_schedulable slots currently
                   10531:                  reservable.
                   10532: 
                   10533:     Keys in inner hash are:
                   10534:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10535:     (b) endreserve: end date of reservation period.
                   10536:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10537:         selected.
1.1040    raeburn  10538: 
                   10539: sorted_future - ref to array of student_schedulable slots reservable in
                   10540:                 the future, ordered by start date of reservation period.
                   10541: 
                   10542: future_reservable - ref to hash of student_schedulable slots reservable
                   10543:                     in the future.
                   10544: 
                   10545:     Keys in inner hash are:
                   10546:     (a) symb: either blank or symb to which slot use is restricted.
                   10547:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10548:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10549:         selected.
1.1040    raeburn  10550: 
                   10551: =back
                   10552: 
                   10553: =cut
                   10554: 
                   10555: sub get_future_slots {
                   10556:     my ($cnum,$cdom,$now,$symb) = @_;
                   10557:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10558:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10559:     foreach my $slot (keys(%slots)) {
                   10560:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10561:         if ($symb) {
                   10562:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10563:                      ($slots{$slot}->{'symb'} ne $symb));
                   10564:         }
                   10565:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10566:             ($slots{$slot}->{'endtime'} > $now)) {
                   10567:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10568:                 my $userallowed = 0;
                   10569:                 if ($slots{$slot}->{'allowedsections'}) {
                   10570:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10571:                     if (!defined($env{'request.role.sec'})
                   10572:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10573:                         $userallowed=1;
                   10574:                     } else {
                   10575:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10576:                             $userallowed=1;
                   10577:                         }
                   10578:                     }
                   10579:                     unless ($userallowed) {
                   10580:                         if (defined($env{'request.course.groups'})) {
                   10581:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10582:                             foreach my $group (@groups) {
                   10583:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10584:                                     $userallowed=1;
                   10585:                                     last;
                   10586:                                 }
                   10587:                             }
                   10588:                         }
                   10589:                     }
                   10590:                 }
                   10591:                 if ($slots{$slot}->{'allowedusers'}) {
                   10592:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10593:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10594:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10595:                         $userallowed = 1;
                   10596:                     }
                   10597:                 }
                   10598:                 next unless($userallowed);
                   10599:             }
                   10600:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10601:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10602:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10603:             my $uniqueperiod;
                   10604:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10605:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10606:             }
1.1040    raeburn  10607:             if (($startreserve < $now) &&
                   10608:                 (!$endreserve || $endreserve > $now)) {
                   10609:                 my $lastres = $endreserve;
                   10610:                 if (!$lastres) {
                   10611:                     $lastres = $slots{$slot}->{'starttime'};
                   10612:                 }
                   10613:                 $reservable_now{$slot} = {
                   10614:                                            symb       => $symb,
1.1075.2.104  raeburn  10615:                                            endreserve => $lastres,
                   10616:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10617:                                          };
                   10618:             } elsif (($startreserve > $now) &&
                   10619:                      (!$endreserve || $endreserve > $startreserve)) {
                   10620:                 $future_reservable{$slot} = {
                   10621:                                               symb         => $symb,
1.1075.2.104  raeburn  10622:                                               startreserve => $startreserve,
                   10623:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10624:                                             };
                   10625:             }
                   10626:         }
                   10627:     }
                   10628:     my @unsorted_reservable = keys(%reservable_now);
                   10629:     if (@unsorted_reservable > 0) {
                   10630:         @sorted_reservable = 
                   10631:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10632:     }
                   10633:     my @unsorted_future = keys(%future_reservable);
                   10634:     if (@unsorted_future > 0) {
                   10635:         @sorted_future =
                   10636:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10637:     }
                   10638:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10639: }
1.780     raeburn  10640: 
                   10641: =pod
                   10642: 
1.1057    foxr     10643: =back
                   10644: 
1.549     albertel 10645: =head1 HTTP Helpers
                   10646: 
                   10647: =over 4
                   10648: 
1.648     raeburn  10649: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10650: 
1.258     albertel 10651: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10652: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10653: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10654: 
                   10655: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10656: $possible_names is an ref to an array of form element names.  As an example:
                   10657: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10658: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10659: 
                   10660: =cut
1.1       albertel 10661: 
1.6       albertel 10662: sub get_unprocessed_cgi {
1.25      albertel 10663:   my ($query,$possible_names)= @_;
1.26      matthew  10664:   # $Apache::lonxml::debug=1;
1.356     albertel 10665:   foreach my $pair (split(/&/,$query)) {
                   10666:     my ($name, $value) = split(/=/,$pair);
1.369     www      10667:     $name = &unescape($name);
1.25      albertel 10668:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10669:       $value =~ tr/+/ /;
                   10670:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10671:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10672:     }
1.16      harris41 10673:   }
1.6       albertel 10674: }
                   10675: 
1.112     bowersj2 10676: =pod
                   10677: 
1.648     raeburn  10678: =item * &cacheheader() 
1.112     bowersj2 10679: 
                   10680: returns cache-controlling header code
                   10681: 
                   10682: =cut
                   10683: 
1.7       albertel 10684: sub cacheheader {
1.258     albertel 10685:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10686:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10687:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10688:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10689:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10690:     return $output;
1.7       albertel 10691: }
                   10692: 
1.112     bowersj2 10693: =pod
                   10694: 
1.648     raeburn  10695: =item * &no_cache($r) 
1.112     bowersj2 10696: 
                   10697: specifies header code to not have cache
                   10698: 
                   10699: =cut
                   10700: 
1.9       albertel 10701: sub no_cache {
1.216     albertel 10702:     my ($r) = @_;
                   10703:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10704: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10705:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10706:     $r->no_cache(1);
                   10707:     $r->header_out("Expires" => $date);
                   10708:     $r->header_out("Pragma" => "no-cache");
1.123     www      10709: }
                   10710: 
                   10711: sub content_type {
1.181     albertel 10712:     my ($r,$type,$charset) = @_;
1.299     foxr     10713:     if ($r) {
                   10714: 	#  Note that printout.pl calls this with undef for $r.
                   10715: 	&no_cache($r);
                   10716:     }
1.258     albertel 10717:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10718:     unless ($charset) {
                   10719: 	$charset=&Apache::lonlocal::current_encoding;
                   10720:     }
                   10721:     if ($charset) { $type.='; charset='.$charset; }
                   10722:     if ($r) {
                   10723: 	$r->content_type($type);
                   10724:     } else {
                   10725: 	print("Content-type: $type\n\n");
                   10726:     }
1.9       albertel 10727: }
1.25      albertel 10728: 
1.112     bowersj2 10729: =pod
                   10730: 
1.648     raeburn  10731: =item * &add_to_env($name,$value) 
1.112     bowersj2 10732: 
1.258     albertel 10733: adds $name to the %env hash with value
1.112     bowersj2 10734: $value, if $name already exists, the entry is converted to an array
                   10735: reference and $value is added to the array.
                   10736: 
                   10737: =cut
                   10738: 
1.25      albertel 10739: sub add_to_env {
                   10740:   my ($name,$value)=@_;
1.258     albertel 10741:   if (defined($env{$name})) {
                   10742:     if (ref($env{$name})) {
1.25      albertel 10743:       #already have multiple values
1.258     albertel 10744:       push(@{ $env{$name} },$value);
1.25      albertel 10745:     } else {
                   10746:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10747:       my $first=$env{$name};
                   10748:       undef($env{$name});
                   10749:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10750:     }
                   10751:   } else {
1.258     albertel 10752:     $env{$name}=$value;
1.25      albertel 10753:   }
1.31      albertel 10754: }
1.149     albertel 10755: 
                   10756: =pod
                   10757: 
1.648     raeburn  10758: =item * &get_env_multiple($name) 
1.149     albertel 10759: 
1.258     albertel 10760: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10761: values may be defined and end up as an array ref.
                   10762: 
                   10763: returns an array of values
                   10764: 
                   10765: =cut
                   10766: 
                   10767: sub get_env_multiple {
                   10768:     my ($name) = @_;
                   10769:     my @values;
1.258     albertel 10770:     if (defined($env{$name})) {
1.149     albertel 10771:         # exists is it an array
1.258     albertel 10772:         if (ref($env{$name})) {
                   10773:             @values=@{ $env{$name} };
1.149     albertel 10774:         } else {
1.258     albertel 10775:             $values[0]=$env{$name};
1.149     albertel 10776:         }
                   10777:     }
                   10778:     return(@values);
                   10779: }
                   10780: 
1.660     raeburn  10781: sub ask_for_embedded_content {
                   10782:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10783:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10784:         %currsubfile,%unused,$rem);
1.1071    raeburn  10785:     my $counter = 0;
                   10786:     my $numnew = 0;
1.987     raeburn  10787:     my $numremref = 0;
                   10788:     my $numinvalid = 0;
                   10789:     my $numpathchg = 0;
                   10790:     my $numexisting = 0;
1.1071    raeburn  10791:     my $numunused = 0;
                   10792:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10793:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10794:     my $heading = &mt('Upload embedded files');
                   10795:     my $buttontext = &mt('Upload');
                   10796: 
1.1075.2.11  raeburn  10797:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10798:         if ($actionurl eq '/adm/dependencies') {
                   10799:             $navmap = Apache::lonnavmaps::navmap->new();
                   10800:         }
                   10801:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10802:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10803:     }
1.1075.2.35  raeburn  10804:     if (($actionurl eq '/adm/portfolio') ||
                   10805:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10806:         my $current_path='/';
                   10807:         if ($env{'form.currentpath'}) {
                   10808:             $current_path = $env{'form.currentpath'};
                   10809:         }
                   10810:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10811:             $udom = $cdom;
                   10812:             $uname = $cnum;
1.984     raeburn  10813:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10814:         } else {
                   10815:             $udom = $env{'user.domain'};
                   10816:             $uname = $env{'user.name'};
                   10817:             $url = '/userfiles/portfolio';
                   10818:         }
1.987     raeburn  10819:         $toplevel = $url.'/';
1.984     raeburn  10820:         $url .= $current_path;
                   10821:         $getpropath = 1;
1.987     raeburn  10822:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10823:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10824:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10825:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10826:         $toplevel = $url;
1.984     raeburn  10827:         if ($rest ne '') {
1.987     raeburn  10828:             $url .= $rest;
                   10829:         }
                   10830:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10831:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10832:             $url = $args->{'docs_url'};
                   10833:             $toplevel = $url;
1.1075.2.11  raeburn  10834:             if ($args->{'context'} eq 'paste') {
                   10835:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10836:                 ($path) =
                   10837:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10838:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10839:                 $fileloc =~ s{^/}{};
                   10840:             }
1.1071    raeburn  10841:         }
                   10842:     } elsif ($actionurl eq '/adm/dependencies') {
                   10843:         if ($env{'request.course.id'} ne '') {
                   10844:             if (ref($args) eq 'HASH') {
                   10845:                 $url = $args->{'docs_url'};
                   10846:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10847:                 $toplevel = $url;
                   10848:                 unless ($toplevel =~ m{^/}) {
                   10849:                     $toplevel = "/$url";
                   10850:                 }
1.1075.2.11  raeburn  10851:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10852:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10853:                     $path = $1;
                   10854:                 } else {
                   10855:                     ($path) =
                   10856:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10857:                 }
1.1075.2.79  raeburn  10858:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10859:                     $fileloc = $toplevel;
                   10860:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10861:                     my ($udom,$uname,$fname) =
                   10862:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10863:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10864:                 } else {
                   10865:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10866:                 }
1.1071    raeburn  10867:                 $fileloc =~ s{^/}{};
                   10868:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10869:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10870:             }
1.987     raeburn  10871:         }
1.1075.2.35  raeburn  10872:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10873:         $udom = $cdom;
                   10874:         $uname = $cnum;
                   10875:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10876:         $toplevel = $url;
                   10877:         $path = $url;
                   10878:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10879:         $fileloc =~ s{^/}{};
                   10880:     }
                   10881:     foreach my $file (keys(%{$allfiles})) {
                   10882:         my $embed_file;
                   10883:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10884:             $embed_file = $1;
                   10885:         } else {
                   10886:             $embed_file = $file;
                   10887:         }
1.1075.2.55  raeburn  10888:         my ($absolutepath,$cleaned_file);
                   10889:         if ($embed_file =~ m{^\w+://}) {
                   10890:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10891:             $newfiles{$cleaned_file} = 1;
                   10892:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10893:         } else {
1.1075.2.55  raeburn  10894:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10895:             if ($embed_file =~ m{^/}) {
                   10896:                 $absolutepath = $embed_file;
                   10897:             }
1.1075.2.47  raeburn  10898:             if ($cleaned_file =~ m{/}) {
                   10899:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10900:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10901:                 my $item = $fname;
                   10902:                 if ($path ne '') {
                   10903:                     $item = $path.'/'.$fname;
                   10904:                     $subdependencies{$path}{$fname} = 1;
                   10905:                 } else {
                   10906:                     $dependencies{$item} = 1;
                   10907:                 }
                   10908:                 if ($absolutepath) {
                   10909:                     $mapping{$item} = $absolutepath;
                   10910:                 } else {
                   10911:                     $mapping{$item} = $embed_file;
                   10912:                 }
                   10913:             } else {
                   10914:                 $dependencies{$embed_file} = 1;
                   10915:                 if ($absolutepath) {
1.1075.2.47  raeburn  10916:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10917:                 } else {
1.1075.2.47  raeburn  10918:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10919:                 }
                   10920:             }
1.984     raeburn  10921:         }
                   10922:     }
1.1071    raeburn  10923:     my $dirptr = 16384;
1.984     raeburn  10924:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10925:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10926:         if (($actionurl eq '/adm/portfolio') ||
                   10927:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10928:             my ($sublistref,$listerror) =
                   10929:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10930:             if (ref($sublistref) eq 'ARRAY') {
                   10931:                 foreach my $line (@{$sublistref}) {
                   10932:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10933:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10934:                 }
1.984     raeburn  10935:             }
1.987     raeburn  10936:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10937:             if (opendir(my $dir,$url.'/'.$path)) {
                   10938:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10939:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10940:             }
1.1075.2.11  raeburn  10941:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10942:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10943:                   ($args->{'context'} eq 'paste')) ||
                   10944:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10945:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10946:                 my $dir;
                   10947:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10948:                     $dir = $fileloc;
                   10949:                 } else {
                   10950:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10951:                 }
1.1071    raeburn  10952:                 if ($dir ne '') {
                   10953:                     my ($sublistref,$listerror) =
                   10954:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10955:                     if (ref($sublistref) eq 'ARRAY') {
                   10956:                         foreach my $line (@{$sublistref}) {
                   10957:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10958:                                 undef,$mtime)=split(/\&/,$line,12);
                   10959:                             unless (($testdir&$dirptr) ||
                   10960:                                     ($file_name =~ /^\.\.?$/)) {
                   10961:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10962:                             }
                   10963:                         }
                   10964:                     }
                   10965:                 }
1.984     raeburn  10966:             }
                   10967:         }
                   10968:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10969:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10970:                 my $item = $path.'/'.$file;
                   10971:                 unless ($mapping{$item} eq $item) {
                   10972:                     $pathchanges{$item} = 1;
                   10973:                 }
                   10974:                 $existing{$item} = 1;
                   10975:                 $numexisting ++;
                   10976:             } else {
                   10977:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10978:             }
                   10979:         }
1.1071    raeburn  10980:         if ($actionurl eq '/adm/dependencies') {
                   10981:             foreach my $path (keys(%currsubfile)) {
                   10982:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10983:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10984:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10985:                              next if (($rem ne '') &&
                   10986:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10987:                                        (ref($navmap) &&
                   10988:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10989:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10990:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10991:                              $unused{$path.'/'.$file} = 1; 
                   10992:                          }
                   10993:                     }
                   10994:                 }
                   10995:             }
                   10996:         }
1.984     raeburn  10997:     }
1.987     raeburn  10998:     my %currfile;
1.1075.2.35  raeburn  10999:     if (($actionurl eq '/adm/portfolio') ||
                   11000:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11001:         my ($dirlistref,$listerror) =
                   11002:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11003:         if (ref($dirlistref) eq 'ARRAY') {
                   11004:             foreach my $line (@{$dirlistref}) {
                   11005:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11006:                 $currfile{$file_name} = 1;
                   11007:             }
1.984     raeburn  11008:         }
1.987     raeburn  11009:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11010:         if (opendir(my $dir,$url)) {
1.987     raeburn  11011:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11012:             map {$currfile{$_} = 1;} @dir_list;
                   11013:         }
1.1075.2.11  raeburn  11014:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11015:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11016:               ($args->{'context'} eq 'paste')) ||
                   11017:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11018:         if ($env{'request.course.id'} ne '') {
                   11019:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11020:             if ($dir ne '') {
                   11021:                 my ($dirlistref,$listerror) =
                   11022:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11023:                 if (ref($dirlistref) eq 'ARRAY') {
                   11024:                     foreach my $line (@{$dirlistref}) {
                   11025:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11026:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11027:                         unless (($testdir&$dirptr) ||
                   11028:                                 ($file_name =~ /^\.\.?$/)) {
                   11029:                             $currfile{$file_name} = [$size,$mtime];
                   11030:                         }
                   11031:                     }
                   11032:                 }
                   11033:             }
                   11034:         }
1.984     raeburn  11035:     }
                   11036:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11037:         if (exists($currfile{$file})) {
1.987     raeburn  11038:             unless ($mapping{$file} eq $file) {
                   11039:                 $pathchanges{$file} = 1;
                   11040:             }
                   11041:             $existing{$file} = 1;
                   11042:             $numexisting ++;
                   11043:         } else {
1.984     raeburn  11044:             $newfiles{$file} = 1;
                   11045:         }
                   11046:     }
1.1071    raeburn  11047:     foreach my $file (keys(%currfile)) {
                   11048:         unless (($file eq $filename) ||
                   11049:                 ($file eq $filename.'.bak') ||
                   11050:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11051:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11052:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11053:                     next if (($rem ne '') &&
                   11054:                              (($env{"httpref.$rem".$file} ne '') ||
                   11055:                               (ref($navmap) &&
                   11056:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11057:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11058:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11059:                 }
1.1075.2.11  raeburn  11060:             }
1.1071    raeburn  11061:             $unused{$file} = 1;
                   11062:         }
                   11063:     }
1.1075.2.11  raeburn  11064:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11065:         ($args->{'context'} eq 'paste')) {
                   11066:         $counter = scalar(keys(%existing));
                   11067:         $numpathchg = scalar(keys(%pathchanges));
                   11068:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11069:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11070:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11071:         $counter = scalar(keys(%existing));
                   11072:         $numpathchg = scalar(keys(%pathchanges));
                   11073:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11074:     }
1.984     raeburn  11075:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11076:         if ($actionurl eq '/adm/dependencies') {
                   11077:             next if ($embed_file =~ m{^\w+://});
                   11078:         }
1.660     raeburn  11079:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11080:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11081:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11082:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11083:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11084:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11085:         }
1.1075.2.35  raeburn  11086:         $upload_output .= '</td>';
1.1071    raeburn  11087:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11088:             $upload_output.='<td align="right">'.
                   11089:                             '<span class="LC_info LC_fontsize_medium">'.
                   11090:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11091:             $numremref++;
1.660     raeburn  11092:         } elsif ($args->{'error_on_invalid_names'}
                   11093:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11094:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11095:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11096:             $numinvalid++;
1.660     raeburn  11097:         } else {
1.1075.2.35  raeburn  11098:             $upload_output .= '<td>'.
                   11099:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11100:                                                      $embed_file,\%mapping,
1.1071    raeburn  11101:                                                      $allfiles,$codebase,'upload');
                   11102:             $counter ++;
                   11103:             $numnew ++;
1.987     raeburn  11104:         }
                   11105:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11106:     }
                   11107:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11108:         if ($actionurl eq '/adm/dependencies') {
                   11109:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11110:             $modify_output .= &start_data_table_row().
                   11111:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11112:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11113:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11114:                               '<td>'.$size.'</td>'.
                   11115:                               '<td>'.$mtime.'</td>'.
                   11116:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11117:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11118:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11119:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11120:                               &embedded_file_element('upload_embedded',$counter,
                   11121:                                                      $embed_file,\%mapping,
                   11122:                                                      $allfiles,$codebase,'modify').
                   11123:                               '</div></td>'.
                   11124:                               &end_data_table_row()."\n";
                   11125:             $counter ++;
                   11126:         } else {
                   11127:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11128:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11129:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11130:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11131:                               &Apache::loncommon::end_data_table_row()."\n";
                   11132:         }
                   11133:     }
                   11134:     my $delidx = $counter;
                   11135:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11136:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11137:         $delete_output .= &start_data_table_row().
                   11138:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11139:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11140:                           '<td>'.$size.'</td>'.
                   11141:                           '<td>'.$mtime.'</td>'.
                   11142:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11143:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11144:                           &embedded_file_element('upload_embedded',$delidx,
                   11145:                                                  $oldfile,\%mapping,$allfiles,
                   11146:                                                  $codebase,'delete').'</td>'.
                   11147:                           &end_data_table_row()."\n"; 
                   11148:         $numunused ++;
                   11149:         $delidx ++;
1.987     raeburn  11150:     }
                   11151:     if ($upload_output) {
                   11152:         $upload_output = &start_data_table().
                   11153:                          $upload_output.
                   11154:                          &end_data_table()."\n";
                   11155:     }
1.1071    raeburn  11156:     if ($modify_output) {
                   11157:         $modify_output = &start_data_table().
                   11158:                          &start_data_table_header_row().
                   11159:                          '<th>'.&mt('File').'</th>'.
                   11160:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11161:                          '<th>'.&mt('Modified').'</th>'.
                   11162:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11163:                          &end_data_table_header_row().
                   11164:                          $modify_output.
                   11165:                          &end_data_table()."\n";
                   11166:     }
                   11167:     if ($delete_output) {
                   11168:         $delete_output = &start_data_table().
                   11169:                          &start_data_table_header_row().
                   11170:                          '<th>'.&mt('File').'</th>'.
                   11171:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11172:                          '<th>'.&mt('Modified').'</th>'.
                   11173:                          '<th>'.&mt('Delete?').'</th>'.
                   11174:                          &end_data_table_header_row().
                   11175:                          $delete_output.
                   11176:                          &end_data_table()."\n";
                   11177:     }
1.987     raeburn  11178:     my $applies = 0;
                   11179:     if ($numremref) {
                   11180:         $applies ++;
                   11181:     }
                   11182:     if ($numinvalid) {
                   11183:         $applies ++;
                   11184:     }
                   11185:     if ($numexisting) {
                   11186:         $applies ++;
                   11187:     }
1.1071    raeburn  11188:     if ($counter || $numunused) {
1.987     raeburn  11189:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11190:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11191:                   $state.'<h3>'.$heading.'</h3>'; 
                   11192:         if ($actionurl eq '/adm/dependencies') {
                   11193:             if ($numnew) {
                   11194:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11195:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11196:                            $upload_output.'<br />'."\n";
                   11197:             }
                   11198:             if ($numexisting) {
                   11199:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11200:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11201:                            $modify_output.'<br />'."\n";
                   11202:                            $buttontext = &mt('Save changes');
                   11203:             }
                   11204:             if ($numunused) {
                   11205:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11206:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11207:                            $delete_output.'<br />'."\n";
                   11208:                            $buttontext = &mt('Save changes');
                   11209:             }
                   11210:         } else {
                   11211:             $output .= $upload_output.'<br />'."\n";
                   11212:         }
                   11213:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11214:                    $counter.'" />'."\n";
                   11215:         if ($actionurl eq '/adm/dependencies') { 
                   11216:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11217:                        $numnew.'" />'."\n";
                   11218:         } elsif ($actionurl eq '') {
1.987     raeburn  11219:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11220:         }
                   11221:     } elsif ($applies) {
                   11222:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11223:         if ($applies > 1) {
                   11224:             $output .=  
1.1075.2.35  raeburn  11225:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11226:             if ($numremref) {
                   11227:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11228:             }
                   11229:             if ($numinvalid) {
                   11230:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11231:             }
                   11232:             if ($numexisting) {
                   11233:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11234:             }
                   11235:             $output .= '</ul><br />';
                   11236:         } elsif ($numremref) {
                   11237:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11238:         } elsif ($numinvalid) {
                   11239:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11240:         } elsif ($numexisting) {
                   11241:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11242:         }
                   11243:         $output .= $upload_output.'<br />';
                   11244:     }
                   11245:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11246:     $chgcount = $counter;
1.987     raeburn  11247:     if (keys(%pathchanges) > 0) {
                   11248:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11249:             if ($counter) {
1.987     raeburn  11250:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11251:                                                   $embed_file,\%mapping,
1.1071    raeburn  11252:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11253:             } else {
                   11254:                 $pathchange_output .= 
                   11255:                     &start_data_table_row().
                   11256:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11257:                     $chgcount.'" checked="checked" /></td>'.
                   11258:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11259:                     '<td>'.$embed_file.
                   11260:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11261:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11262:                     '</td>'.&end_data_table_row();
1.660     raeburn  11263:             }
1.987     raeburn  11264:             $numpathchg ++;
                   11265:             $chgcount ++;
1.660     raeburn  11266:         }
                   11267:     }
1.1075.2.35  raeburn  11268:     if (($counter) || ($numunused)) {
1.987     raeburn  11269:         if ($numpathchg) {
                   11270:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11271:                        $numpathchg.'" />'."\n";
                   11272:         }
                   11273:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11274:             ($actionurl eq '/adm/imsimport')) {
                   11275:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11276:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11277:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11278:         } elsif ($actionurl eq '/adm/dependencies') {
                   11279:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11280:         }
1.1075.2.35  raeburn  11281:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11282:     } elsif ($numpathchg) {
                   11283:         my %pathchange = ();
                   11284:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11285:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11286:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11287:         }
1.987     raeburn  11288:     }
1.1071    raeburn  11289:     return ($output,$counter,$numpathchg);
1.987     raeburn  11290: }
                   11291: 
1.1075.2.47  raeburn  11292: =pod
                   11293: 
                   11294: =item * clean_path($name)
                   11295: 
                   11296: Performs clean-up of directories, subdirectories and filename in an
                   11297: embedded object, referenced in an HTML file which is being uploaded
                   11298: to a course or portfolio, where
                   11299: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11300: checked.
                   11301: 
                   11302: Clean-up is similar to replacements in lonnet::clean_filename()
                   11303: except each / between sub-directory and next level is preserved.
                   11304: 
                   11305: =cut
                   11306: 
                   11307: sub clean_path {
                   11308:     my ($embed_file) = @_;
                   11309:     $embed_file =~s{^/+}{};
                   11310:     my @contents;
                   11311:     if ($embed_file =~ m{/}) {
                   11312:         @contents = split(/\//,$embed_file);
                   11313:     } else {
                   11314:         @contents = ($embed_file);
                   11315:     }
                   11316:     my $lastidx = scalar(@contents)-1;
                   11317:     for (my $i=0; $i<=$lastidx; $i++) {
                   11318:         $contents[$i]=~s{\\}{/}g;
                   11319:         $contents[$i]=~s/\s+/\_/g;
                   11320:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11321:         if ($i == $lastidx) {
                   11322:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11323:         }
                   11324:     }
                   11325:     if ($lastidx > 0) {
                   11326:         return join('/',@contents);
                   11327:     } else {
                   11328:         return $contents[0];
                   11329:     }
                   11330: }
                   11331: 
1.987     raeburn  11332: sub embedded_file_element {
1.1071    raeburn  11333:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11334:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11335:                    (ref($codebase) eq 'HASH'));
                   11336:     my $output;
1.1071    raeburn  11337:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11338:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11339:     }
                   11340:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11341:                &escape($embed_file).'" />';
                   11342:     unless (($context eq 'upload_embedded') && 
                   11343:             ($mapping->{$embed_file} eq $embed_file)) {
                   11344:         $output .='
                   11345:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11346:     }
                   11347:     my $attrib;
                   11348:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11349:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11350:     }
                   11351:     $output .=
                   11352:         "\n\t\t".
                   11353:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11354:         $attrib.'" />';
                   11355:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11356:         $output .=
                   11357:             "\n\t\t".
                   11358:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11359:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11360:     }
1.987     raeburn  11361:     return $output;
1.660     raeburn  11362: }
                   11363: 
1.1071    raeburn  11364: sub get_dependency_details {
                   11365:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11366:     my ($size,$mtime,$showsize,$showmtime);
                   11367:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11368:         if ($embed_file =~ m{/}) {
                   11369:             my ($path,$fname) = split(/\//,$embed_file);
                   11370:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11371:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11372:             }
                   11373:         } else {
                   11374:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11375:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11376:             }
                   11377:         }
                   11378:         $showsize = $size/1024.0;
                   11379:         $showsize = sprintf("%.1f",$showsize);
                   11380:         if ($mtime > 0) {
                   11381:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11382:         }
                   11383:     }
                   11384:     return ($showsize,$showmtime);
                   11385: }
                   11386: 
                   11387: sub ask_embedded_js {
                   11388:     return <<"END";
                   11389: <script type="text/javascript"">
                   11390: // <![CDATA[
                   11391: function toggleBrowse(counter) {
                   11392:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11393:     var fileid = document.getElementById('embedded_item_'+counter);
                   11394:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11395:     if (chkboxid.checked == true) {
                   11396:         uploaddivid.style.display='block';
                   11397:     } else {
                   11398:         uploaddivid.style.display='none';
                   11399:         fileid.value = '';
                   11400:     }
                   11401: }
                   11402: // ]]>
                   11403: </script>
                   11404: 
                   11405: END
                   11406: }
                   11407: 
1.661     raeburn  11408: sub upload_embedded {
                   11409:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11410:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11411:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11412:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11413:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11414:         my $orig_uploaded_filename =
                   11415:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11416:         foreach my $type ('orig','ref','attrib','codebase') {
                   11417:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11418:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11419:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11420:             }
                   11421:         }
1.661     raeburn  11422:         my ($path,$fname) =
                   11423:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11424:         # no path, whole string is fname
                   11425:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11426:         $fname = &Apache::lonnet::clean_filename($fname);
                   11427:         # See if there is anything left
                   11428:         next if ($fname eq '');
                   11429: 
                   11430:         # Check if file already exists as a file or directory.
                   11431:         my ($state,$msg);
                   11432:         if ($context eq 'portfolio') {
                   11433:             my $port_path = $dirpath;
                   11434:             if ($group ne '') {
                   11435:                 $port_path = "groups/$group/$port_path";
                   11436:             }
1.987     raeburn  11437:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11438:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11439:                                               $dir_root,$port_path,$disk_quota,
                   11440:                                               $current_disk_usage,$uname,$udom);
                   11441:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11442:                 || $state eq 'file_locked') {
1.661     raeburn  11443:                 $output .= $msg;
                   11444:                 next;
                   11445:             }
                   11446:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11447:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11448:             if ($state eq 'exists') {
                   11449:                 $output .= $msg;
                   11450:                 next;
                   11451:             }
                   11452:         }
                   11453:         # Check if extension is valid
                   11454:         if (($fname =~ /\.(\w+)$/) &&
                   11455:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11456:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11457:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11458:             next;
                   11459:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11460:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11461:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11462:             next;
                   11463:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11464:             $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  11465:             next;
                   11466:         }
                   11467:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11468:         my $subdir = $path;
                   11469:         $subdir =~ s{/+$}{};
1.661     raeburn  11470:         if ($context eq 'portfolio') {
1.984     raeburn  11471:             my $result;
                   11472:             if ($state eq 'existingfile') {
                   11473:                 $result=
                   11474:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11475:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11476:             } else {
1.984     raeburn  11477:                 $result=
                   11478:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11479:                                                     $dirpath.
1.1075.2.35  raeburn  11480:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11481:                 if ($result !~ m|^/uploaded/|) {
                   11482:                     $output .= '<span class="LC_error">'
                   11483:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11484:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11485:                                .'</span><br />';
                   11486:                     next;
                   11487:                 } else {
1.987     raeburn  11488:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11489:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11490:                 }
1.661     raeburn  11491:             }
1.1075.2.35  raeburn  11492:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11493:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11494:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11495:             my $result =
1.1075.2.35  raeburn  11496:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11497:             if ($result !~ m|^/uploaded/|) {
                   11498:                 $output .= '<span class="LC_error">'
                   11499:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11500:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11501:                            .'</span><br />';
                   11502:                     next;
                   11503:             } else {
                   11504:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11505:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11506:                 if ($context eq 'syllabus') {
                   11507:                     &Apache::lonnet::make_public_indefinitely($result);
                   11508:                 }
1.987     raeburn  11509:             }
1.661     raeburn  11510:         } else {
                   11511: # Save the file
                   11512:             my $target = $env{'form.embedded_item_'.$i};
                   11513:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11514:             my $dest = $fullpath.$fname;
                   11515:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11516:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11517:             my $count;
                   11518:             my $filepath = $dir_root;
1.1027    raeburn  11519:             foreach my $subdir (@parts) {
                   11520:                 $filepath .= "/$subdir";
                   11521:                 if (!-e $filepath) {
1.661     raeburn  11522:                     mkdir($filepath,0770);
                   11523:                 }
                   11524:             }
                   11525:             my $fh;
                   11526:             if (!open($fh,'>'.$dest)) {
                   11527:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11528:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11529:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11530:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11531:                            '</span><br />';
                   11532:             } else {
                   11533:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11534:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11535:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11536:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11537:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11538:                               '</span><br />';
                   11539:                 } else {
1.987     raeburn  11540:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11541:                                $url.'</span>').'<br />';
                   11542:                     unless ($context eq 'testbank') {
                   11543:                         $footer .= &mt('View embedded file: [_1]',
                   11544:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11545:                     }
                   11546:                 }
                   11547:                 close($fh);
                   11548:             }
                   11549:         }
                   11550:         if ($env{'form.embedded_ref_'.$i}) {
                   11551:             $pathchange{$i} = 1;
                   11552:         }
                   11553:     }
                   11554:     if ($output) {
                   11555:         $output = '<p>'.$output.'</p>';
                   11556:     }
                   11557:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11558:     $returnflag = 'ok';
1.1071    raeburn  11559:     my $numpathchgs = scalar(keys(%pathchange));
                   11560:     if ($numpathchgs > 0) {
1.987     raeburn  11561:         if ($context eq 'portfolio') {
                   11562:             $output .= '<p>'.&mt('or').'</p>';
                   11563:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11564:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11565:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11566:             $returnflag = 'modify_orightml';
                   11567:         }
                   11568:     }
1.1071    raeburn  11569:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11570: }
                   11571: 
                   11572: sub modify_html_form {
                   11573:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11574:     my $end = 0;
                   11575:     my $modifyform;
                   11576:     if ($context eq 'upload_embedded') {
                   11577:         return unless (ref($pathchange) eq 'HASH');
                   11578:         if ($env{'form.number_embedded_items'}) {
                   11579:             $end += $env{'form.number_embedded_items'};
                   11580:         }
                   11581:         if ($env{'form.number_pathchange_items'}) {
                   11582:             $end += $env{'form.number_pathchange_items'};
                   11583:         }
                   11584:         if ($end) {
                   11585:             for (my $i=0; $i<$end; $i++) {
                   11586:                 if ($i < $env{'form.number_embedded_items'}) {
                   11587:                     next unless($pathchange->{$i});
                   11588:                 }
                   11589:                 $modifyform .=
                   11590:                     &start_data_table_row().
                   11591:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11592:                     'checked="checked" /></td>'.
                   11593:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11594:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11595:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11596:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11597:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11598:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11599:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11600:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11601:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11602:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11603:                     &end_data_table_row();
1.1071    raeburn  11604:             }
1.987     raeburn  11605:         }
                   11606:     } else {
                   11607:         $modifyform = $pathchgtable;
                   11608:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11609:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11610:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11611:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11612:         }
                   11613:     }
                   11614:     if ($modifyform) {
1.1071    raeburn  11615:         if ($actionurl eq '/adm/dependencies') {
                   11616:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11617:         }
1.987     raeburn  11618:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11619:                '<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".
                   11620:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11621:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11622:                '</ol></p>'."\n".'<p>'.
                   11623:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11624:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11625:                &start_data_table()."\n".
                   11626:                &start_data_table_header_row().
                   11627:                '<th>'.&mt('Change?').'</th>'.
                   11628:                '<th>'.&mt('Current reference').'</th>'.
                   11629:                '<th>'.&mt('Required reference').'</th>'.
                   11630:                &end_data_table_header_row()."\n".
                   11631:                $modifyform.
                   11632:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11633:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11634:                '</form>'."\n";
                   11635:     }
                   11636:     return;
                   11637: }
                   11638: 
                   11639: sub modify_html_refs {
1.1075.2.35  raeburn  11640:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11641:     my $container;
                   11642:     if ($context eq 'portfolio') {
                   11643:         $container = $env{'form.container'};
                   11644:     } elsif ($context eq 'coursedoc') {
                   11645:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11646:     } elsif ($context eq 'manage_dependencies') {
                   11647:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11648:         $container = "/$container";
1.1075.2.35  raeburn  11649:     } elsif ($context eq 'syllabus') {
                   11650:         $container = $url;
1.987     raeburn  11651:     } else {
1.1027    raeburn  11652:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11653:     }
                   11654:     my (%allfiles,%codebase,$output,$content);
                   11655:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11656:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11657:         if (wantarray) {
                   11658:             return ('',0,0); 
                   11659:         } else {
                   11660:             return;
                   11661:         }
                   11662:     }
                   11663:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11664:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11665:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11666:             if (wantarray) {
                   11667:                 return ('',0,0);
                   11668:             } else {
                   11669:                 return;
                   11670:             }
                   11671:         } 
1.987     raeburn  11672:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11673:         if ($content eq '-1') {
                   11674:             if (wantarray) {
                   11675:                 return ('',0,0);
                   11676:             } else {
                   11677:                 return;
                   11678:             }
                   11679:         }
1.987     raeburn  11680:     } else {
1.1071    raeburn  11681:         unless ($container =~ /^\Q$dir_root\E/) {
                   11682:             if (wantarray) {
                   11683:                 return ('',0,0);
                   11684:             } else {
                   11685:                 return;
                   11686:             }
                   11687:         } 
1.1075.2.128  raeburn  11688:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11689:             $content = join('', <$fh>);
                   11690:             close($fh);
                   11691:         } else {
1.1071    raeburn  11692:             if (wantarray) {
                   11693:                 return ('',0,0);
                   11694:             } else {
                   11695:                 return;
                   11696:             }
1.987     raeburn  11697:         }
                   11698:     }
                   11699:     my ($count,$codebasecount) = (0,0);
                   11700:     my $mm = new File::MMagic;
                   11701:     my $mime_type = $mm->checktype_contents($content);
                   11702:     if ($mime_type eq 'text/html') {
                   11703:         my $parse_result = 
                   11704:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11705:                                                     \%codebase,\$content);
                   11706:         if ($parse_result eq 'ok') {
                   11707:             foreach my $i (@changes) {
                   11708:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11709:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11710:                 if ($allfiles{$ref}) {
                   11711:                     my $newname =  $orig;
                   11712:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11713:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11714:                     if ($attrib_regexp =~ /:/) {
                   11715:                         $attrib_regexp =~ s/\:/|/g;
                   11716:                     }
                   11717:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11718:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11719:                         $count += $numchg;
1.1075.2.35  raeburn  11720:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11721:                         delete($allfiles{$ref});
1.987     raeburn  11722:                     }
                   11723:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11724:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11725:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11726:                         $codebasecount ++;
                   11727:                     }
                   11728:                 }
                   11729:             }
1.1075.2.35  raeburn  11730:             my $skiprewrites;
1.987     raeburn  11731:             if ($count || $codebasecount) {
                   11732:                 my $saveresult;
1.1071    raeburn  11733:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11734:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11735:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11736:                     if ($url eq $container) {
                   11737:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11738:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11739:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11740:                                             $fname.'</span>').'</p>';
1.987     raeburn  11741:                     } else {
                   11742:                          $output = '<p class="LC_error">'.
                   11743:                                    &mt('Error: update failed for: [_1].',
                   11744:                                    '<span class="LC_filename">'.
                   11745:                                    $container.'</span>').'</p>';
                   11746:                     }
1.1075.2.35  raeburn  11747:                     if ($context eq 'syllabus') {
                   11748:                         unless ($saveresult eq 'ok') {
                   11749:                             $skiprewrites = 1;
                   11750:                         }
                   11751:                     }
1.987     raeburn  11752:                 } else {
1.1075.2.128  raeburn  11753:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11754:                         print $fh $content;
                   11755:                         close($fh);
                   11756:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11757:                                   $count,'<span class="LC_filename">'.
                   11758:                                   $container.'</span>').'</p>';
1.661     raeburn  11759:                     } else {
1.987     raeburn  11760:                          $output = '<p class="LC_error">'.
                   11761:                                    &mt('Error: could not update [_1].',
                   11762:                                    '<span class="LC_filename">'.
                   11763:                                    $container.'</span>').'</p>';
1.661     raeburn  11764:                     }
                   11765:                 }
                   11766:             }
1.1075.2.35  raeburn  11767:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11768:                 my ($actionurl,$state);
                   11769:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11770:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11771:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11772:                                               \%codebase,
                   11773:                                               {'context' => 'rewrites',
                   11774:                                                'ignore_remote_references' => 1,});
                   11775:                 if (ref($mapping) eq 'HASH') {
                   11776:                     my $rewrites = 0;
                   11777:                     foreach my $key (keys(%{$mapping})) {
                   11778:                         next if ($key =~ m{^https?://});
                   11779:                         my $ref = $mapping->{$key};
                   11780:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11781:                         my $attrib;
                   11782:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11783:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11784:                         }
                   11785:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11786:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11787:                             $rewrites += $numchg;
                   11788:                         }
                   11789:                     }
                   11790:                     if ($rewrites) {
                   11791:                         my $saveresult;
                   11792:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11793:                         if ($url eq $container) {
                   11794:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11795:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11796:                                             $count,'<span class="LC_filename">'.
                   11797:                                             $fname.'</span>').'</p>';
                   11798:                         } else {
                   11799:                             $output .= '<p class="LC_error">'.
                   11800:                                        &mt('Error: could not update links in [_1].',
                   11801:                                        '<span class="LC_filename">'.
                   11802:                                        $container.'</span>').'</p>';
                   11803: 
                   11804:                         }
                   11805:                     }
                   11806:                 }
                   11807:             }
1.987     raeburn  11808:         } else {
                   11809:             &logthis('Failed to parse '.$container.
                   11810:                      ' to modify references: '.$parse_result);
1.661     raeburn  11811:         }
                   11812:     }
1.1071    raeburn  11813:     if (wantarray) {
                   11814:         return ($output,$count,$codebasecount);
                   11815:     } else {
                   11816:         return $output;
                   11817:     }
1.661     raeburn  11818: }
                   11819: 
                   11820: sub check_for_existing {
                   11821:     my ($path,$fname,$element) = @_;
                   11822:     my ($state,$msg);
                   11823:     if (-d $path.'/'.$fname) {
                   11824:         $state = 'exists';
                   11825:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11826:     } elsif (-e $path.'/'.$fname) {
                   11827:         $state = 'exists';
                   11828:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11829:     }
                   11830:     if ($state eq 'exists') {
                   11831:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11832:     }
                   11833:     return ($state,$msg);
                   11834: }
                   11835: 
                   11836: sub check_for_upload {
                   11837:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11838:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11839:     my $filesize = length($env{'form.'.$element});
                   11840:     if (!$filesize) {
                   11841:         my $msg = '<span class="LC_error">'.
                   11842:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11843:                       '<span class="LC_filename">'.$fname.'</span>',
                   11844:                       $filesize).'<br />'.
1.1007    raeburn  11845:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11846:                   '</span>';
                   11847:         return ('zero_bytes',$msg);
                   11848:     }
                   11849:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11850:     my $getpropath = 1;
1.1021    raeburn  11851:     my ($dirlistref,$listerror) =
                   11852:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11853:     my $found_file = 0;
                   11854:     my $locked_file = 0;
1.991     raeburn  11855:     my @lockers;
                   11856:     my $navmap;
                   11857:     if ($env{'request.course.id'}) {
                   11858:         $navmap = Apache::lonnavmaps::navmap->new();
                   11859:     }
1.1021    raeburn  11860:     if (ref($dirlistref) eq 'ARRAY') {
                   11861:         foreach my $line (@{$dirlistref}) {
                   11862:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11863:             if ($file_name eq $fname){
                   11864:                 $file_name = $path.$file_name;
                   11865:                 if ($group ne '') {
                   11866:                     $file_name = $group.$file_name;
                   11867:                 }
                   11868:                 $found_file = 1;
                   11869:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11870:                     foreach my $lock (@lockers) {
                   11871:                         if (ref($lock) eq 'ARRAY') {
                   11872:                             my ($symb,$crsid) = @{$lock};
                   11873:                             if ($crsid eq $env{'request.course.id'}) {
                   11874:                                 if (ref($navmap)) {
                   11875:                                     my $res = $navmap->getBySymb($symb);
                   11876:                                     foreach my $part (@{$res->parts()}) { 
                   11877:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11878:                                         unless (($slot_status == $res->RESERVED) ||
                   11879:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11880:                                             $locked_file = 1;
                   11881:                                         }
1.991     raeburn  11882:                                     }
1.1021    raeburn  11883:                                 } else {
                   11884:                                     $locked_file = 1;
1.991     raeburn  11885:                                 }
                   11886:                             } else {
                   11887:                                 $locked_file = 1;
                   11888:                             }
                   11889:                         }
1.1021    raeburn  11890:                    }
                   11891:                 } else {
                   11892:                     my @info = split(/\&/,$rest);
                   11893:                     my $currsize = $info[6]/1000;
                   11894:                     if ($currsize < $filesize) {
                   11895:                         my $extra = $filesize - $currsize;
                   11896:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11897:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11898:                                       &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.1075.2.69  raeburn  11899:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11900:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11901:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11902:                             return ('will_exceed_quota',$msg);
                   11903:                         }
1.984     raeburn  11904:                     }
                   11905:                 }
1.661     raeburn  11906:             }
                   11907:         }
                   11908:     }
                   11909:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11910:         my $msg = '<p class="LC_warning">'.
                   11911:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11912:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11913:         return ('will_exceed_quota',$msg);
                   11914:     } elsif ($found_file) {
                   11915:         if ($locked_file) {
1.1075.2.69  raeburn  11916:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11917:             $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.1075.2.69  raeburn  11918:             $msg .= '</p>';
1.661     raeburn  11919:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11920:             return ('file_locked',$msg);
                   11921:         } else {
1.1075.2.69  raeburn  11922:             my $msg = '<p class="LC_error">';
1.984     raeburn  11923:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1075.2.69  raeburn  11924:             $msg .= '</p>';
1.984     raeburn  11925:             return ('existingfile',$msg);
1.661     raeburn  11926:         }
                   11927:     }
                   11928: }
                   11929: 
1.987     raeburn  11930: sub check_for_traversal {
                   11931:     my ($path,$url,$toplevel) = @_;
                   11932:     my @parts=split(/\//,$path);
                   11933:     my $cleanpath;
                   11934:     my $fullpath = $url;
                   11935:     for (my $i=0;$i<@parts;$i++) {
                   11936:         next if ($parts[$i] eq '.');
                   11937:         if ($parts[$i] eq '..') {
                   11938:             $fullpath =~ s{([^/]+/)$}{};
                   11939:         } else {
                   11940:             $fullpath .= $parts[$i].'/';
                   11941:         }
                   11942:     }
                   11943:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11944:         $cleanpath = $1;
                   11945:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11946:         my $curr_toprel = $1;
                   11947:         my @parts = split(/\//,$curr_toprel);
                   11948:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11949:         my @urlparts = split(/\//,$url_toprel);
                   11950:         my $doubledots;
                   11951:         my $startdiff = -1;
                   11952:         for (my $i=0; $i<@urlparts; $i++) {
                   11953:             if ($startdiff == -1) {
                   11954:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11955:                     $startdiff = $i;
                   11956:                     $doubledots .= '../';
                   11957:                 }
                   11958:             } else {
                   11959:                 $doubledots .= '../';
                   11960:             }
                   11961:         }
                   11962:         if ($startdiff > -1) {
                   11963:             $cleanpath = $doubledots;
                   11964:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11965:                 $cleanpath .= $parts[$i].'/';
                   11966:             }
                   11967:         }
                   11968:     }
                   11969:     $cleanpath =~ s{(/)$}{};
                   11970:     return $cleanpath;
                   11971: }
1.31      albertel 11972: 
1.1053    raeburn  11973: sub is_archive_file {
                   11974:     my ($mimetype) = @_;
                   11975:     if (($mimetype eq 'application/octet-stream') ||
                   11976:         ($mimetype eq 'application/x-stuffit') ||
                   11977:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11978:         return 1;
                   11979:     }
                   11980:     return;
                   11981: }
                   11982: 
                   11983: sub decompress_form {
1.1065    raeburn  11984:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11985:     my %lt = &Apache::lonlocal::texthash (
                   11986:         this => 'This file is an archive file.',
1.1067    raeburn  11987:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11988:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11989:         youm => 'You may wish to extract its contents.',
                   11990:         extr => 'Extract contents',
1.1067    raeburn  11991:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11992:         proa => 'Process automatically?',
1.1053    raeburn  11993:         yes  => 'Yes',
                   11994:         no   => 'No',
1.1067    raeburn  11995:         fold => 'Title for folder containing movie',
                   11996:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11997:     );
1.1065    raeburn  11998:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11999:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12000:     my $info = &list_archive_contents($fileloc,\@paths);
                   12001:     if (@paths) {
                   12002:         foreach my $path (@paths) {
                   12003:             $path =~ s{^/}{};
1.1067    raeburn  12004:             if ($path =~ m{^([^/]+)/$}) {
                   12005:                 $topdir = $1;
                   12006:             }
1.1065    raeburn  12007:             if ($path =~ m{^([^/]+)/}) {
                   12008:                 $toplevel{$1} = $path;
                   12009:             } else {
                   12010:                 $toplevel{$path} = $path;
                   12011:             }
                   12012:         }
                   12013:     }
1.1067    raeburn  12014:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12015:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12016:                         "$topdir/media/",
                   12017:                         "$topdir/media/$topdir.mp4",
                   12018:                         "$topdir/media/FirstFrame.png",
                   12019:                         "$topdir/media/player.swf",
                   12020:                         "$topdir/media/swfobject.js",
                   12021:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12022:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12023:                          "$topdir/$topdir.mp4",
                   12024:                          "$topdir/$topdir\_config.xml",
                   12025:                          "$topdir/$topdir\_controller.swf",
                   12026:                          "$topdir/$topdir\_embed.css",
                   12027:                          "$topdir/$topdir\_First_Frame.png",
                   12028:                          "$topdir/$topdir\_player.html",
                   12029:                          "$topdir/$topdir\_Thumbnails.png",
                   12030:                          "$topdir/playerProductInstall.swf",
                   12031:                          "$topdir/scripts/",
                   12032:                          "$topdir/scripts/config_xml.js",
                   12033:                          "$topdir/scripts/handlebars.js",
                   12034:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12035:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12036:                          "$topdir/scripts/modernizr.js",
                   12037:                          "$topdir/scripts/player-min.js",
                   12038:                          "$topdir/scripts/swfobject.js",
                   12039:                          "$topdir/skins/",
                   12040:                          "$topdir/skins/configuration_express.xml",
                   12041:                          "$topdir/skins/express_show/",
                   12042:                          "$topdir/skins/express_show/player-min.css",
                   12043:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12044:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12045:                          "$topdir/$topdir.mp4",
                   12046:                          "$topdir/$topdir\_config.xml",
                   12047:                          "$topdir/$topdir\_controller.swf",
                   12048:                          "$topdir/$topdir\_embed.css",
                   12049:                          "$topdir/$topdir\_First_Frame.png",
                   12050:                          "$topdir/$topdir\_player.html",
                   12051:                          "$topdir/$topdir\_Thumbnails.png",
                   12052:                          "$topdir/playerProductInstall.swf",
                   12053:                          "$topdir/scripts/",
                   12054:                          "$topdir/scripts/config_xml.js",
                   12055:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12056:                          "$topdir/skins/",
                   12057:                          "$topdir/skins/configuration_express.xml",
                   12058:                          "$topdir/skins/express_show/",
                   12059:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12060:                          "$topdir/skins/express_show/spritesheet.png",
                   12061:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12062:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12063:         if (@diffs == 0) {
1.1075.2.59  raeburn  12064:             $is_camtasia = 6;
                   12065:         } else {
1.1075.2.81  raeburn  12066:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12067:             if (@diffs == 0) {
                   12068:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12069:             } else {
                   12070:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12071:                 if (@diffs == 0) {
                   12072:                     $is_camtasia = 8;
                   12073:                 }
1.1075.2.59  raeburn  12074:             }
1.1067    raeburn  12075:         }
                   12076:     }
                   12077:     my $output;
                   12078:     if ($is_camtasia) {
                   12079:         $output = <<"ENDCAM";
                   12080: <script type="text/javascript" language="Javascript">
                   12081: // <![CDATA[
                   12082: 
                   12083: function camtasiaToggle() {
                   12084:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12085:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12086:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12087:                 document.getElementById('camtasia_titles').style.display='block';
                   12088:             } else {
                   12089:                 document.getElementById('camtasia_titles').style.display='none';
                   12090:             }
                   12091:         }
                   12092:     }
                   12093:     return;
                   12094: }
                   12095: 
                   12096: // ]]>
                   12097: </script>
                   12098: <p>$lt{'camt'}</p>
                   12099: ENDCAM
1.1065    raeburn  12100:     } else {
1.1067    raeburn  12101:         $output = '<p>'.$lt{'this'};
                   12102:         if ($info eq '') {
                   12103:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12104:         } else {
                   12105:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12106:                        '<div><pre>'.$info.'</pre></div>';
                   12107:         }
1.1065    raeburn  12108:     }
1.1067    raeburn  12109:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12110:     my $duplicates;
                   12111:     my $num = 0;
                   12112:     if (ref($dirlist) eq 'ARRAY') {
                   12113:         foreach my $item (@{$dirlist}) {
                   12114:             if (ref($item) eq 'ARRAY') {
                   12115:                 if (exists($toplevel{$item->[0]})) {
                   12116:                     $duplicates .= 
                   12117:                         &start_data_table_row().
                   12118:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12119:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12120:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12121:                         'value="1" />'.&mt('Yes').'</label>'.
                   12122:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12123:                         '<td>'.$item->[0].'</td>';
                   12124:                     if ($item->[2]) {
                   12125:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12126:                     } else {
                   12127:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12128:                     }
                   12129:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12130:                                    '<td>'.
                   12131:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12132:                                    '</td>'.
                   12133:                                    &end_data_table_row();
                   12134:                     $num ++;
                   12135:                 }
                   12136:             }
                   12137:         }
                   12138:     }
                   12139:     my $itemcount;
                   12140:     if (@paths > 0) {
                   12141:         $itemcount = scalar(@paths);
                   12142:     } else {
                   12143:         $itemcount = 1;
                   12144:     }
1.1067    raeburn  12145:     if ($is_camtasia) {
                   12146:         $output .= $lt{'auto'}.'<br />'.
                   12147:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12148:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12149:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12150:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12151:                    $lt{'no'}.'</label></span><br />'.
                   12152:                    '<div id="camtasia_titles" style="display:block">'.
                   12153:                    &Apache::lonhtmlcommon::start_pick_box().
                   12154:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12155:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12156:                    &Apache::lonhtmlcommon::row_closure().
                   12157:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12158:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12159:                    &Apache::lonhtmlcommon::row_closure(1).
                   12160:                    &Apache::lonhtmlcommon::end_pick_box().
                   12161:                    '</div>';
                   12162:     }
1.1065    raeburn  12163:     $output .= 
                   12164:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12165:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12166:         "\n";
1.1065    raeburn  12167:     if ($duplicates ne '') {
                   12168:         $output .= '<p><span class="LC_warning">'.
                   12169:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12170:                    &start_data_table().
                   12171:                    &start_data_table_header_row().
                   12172:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12173:                    '<th>'.&mt('Name').'</th>'.
                   12174:                    '<th>'.&mt('Type').'</th>'.
                   12175:                    '<th>'.&mt('Size').'</th>'.
                   12176:                    '<th>'.&mt('Last modified').'</th>'.
                   12177:                    &end_data_table_header_row().
                   12178:                    $duplicates.
                   12179:                    &end_data_table().
                   12180:                    '</p>';
                   12181:     }
1.1067    raeburn  12182:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12183:     if (ref($hiddenelements) eq 'HASH') {
                   12184:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12185:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12186:         }
                   12187:     }
                   12188:     $output .= <<"END";
1.1067    raeburn  12189: <br />
1.1053    raeburn  12190: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12191: </form>
                   12192: $noextract
                   12193: END
                   12194:     return $output;
                   12195: }
                   12196: 
1.1065    raeburn  12197: sub decompression_utility {
                   12198:     my ($program) = @_;
                   12199:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12200:     my $location;
                   12201:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12202:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12203:                          '/usr/sbin/') {
                   12204:             if (-x $dir.$program) {
                   12205:                 $location = $dir.$program;
                   12206:                 last;
                   12207:             }
                   12208:         }
                   12209:     }
                   12210:     return $location;
                   12211: }
                   12212: 
                   12213: sub list_archive_contents {
                   12214:     my ($file,$pathsref) = @_;
                   12215:     my (@cmd,$output);
                   12216:     my $needsregexp;
                   12217:     if ($file =~ /\.zip$/) {
                   12218:         @cmd = (&decompression_utility('unzip'),"-l");
                   12219:         $needsregexp = 1;
                   12220:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12221:              ($file =~ /\.tgz$/)) {
                   12222:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12223:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12224:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12225:     } elsif ($file =~ m|\.tar$|) {
                   12226:         @cmd = (&decompression_utility('tar'),"-tf");
                   12227:     }
                   12228:     if (@cmd) {
                   12229:         undef($!);
                   12230:         undef($@);
                   12231:         if (open(my $fh,"-|", @cmd, $file)) {
                   12232:             while (my $line = <$fh>) {
                   12233:                 $output .= $line;
                   12234:                 chomp($line);
                   12235:                 my $item;
                   12236:                 if ($needsregexp) {
                   12237:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12238:                 } else {
                   12239:                     $item = $line;
                   12240:                 }
                   12241:                 if ($item ne '') {
                   12242:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12243:                         push(@{$pathsref},$item);
                   12244:                     } 
                   12245:                 }
                   12246:             }
                   12247:             close($fh);
                   12248:         }
                   12249:     }
                   12250:     return $output;
                   12251: }
                   12252: 
1.1053    raeburn  12253: sub decompress_uploaded_file {
                   12254:     my ($file,$dir) = @_;
                   12255:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12256:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12257:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12258:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12259:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12260:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12261:     my $decompressed = $env{'cgi.decompressed'};
                   12262:     &Apache::lonnet::delenv('cgi.file');
                   12263:     &Apache::lonnet::delenv('cgi.dir');
                   12264:     &Apache::lonnet::delenv('cgi.decompressed');
                   12265:     return ($decompressed,$result);
                   12266: }
                   12267: 
1.1055    raeburn  12268: sub process_decompression {
                   12269:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12270:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12271:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12272:                &mt('Unexpected file path.').'</p>'."\n";
                   12273:     }
                   12274:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12275:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12276:                &mt('Unexpected course context.').'</p>'."\n";
                   12277:     }
                   12278:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12279:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12280:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12281:     }
1.1055    raeburn  12282:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12283:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12284:         $error = &mt('Filename not a supported archive file type.').
                   12285:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12286:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12287:     } else {
                   12288:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12289:         if ($docuhome eq 'no_host') {
                   12290:             $error = &mt('Could not determine home server for course.');
                   12291:         } else {
                   12292:             my @ids=&Apache::lonnet::current_machine_ids();
                   12293:             my $currdir = "$dir_root/$destination";
                   12294:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12295:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12296:                        "$dir_root/$destination";
                   12297:             } else {
                   12298:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12299:                        "$dir_root/$docudom/$docuname/$destination";
                   12300:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12301:                     $error = &mt('Archive file not found.');
                   12302:                 }
                   12303:             }
1.1065    raeburn  12304:             my (@to_overwrite,@to_skip);
                   12305:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12306:                 my $total = $env{'form.archive_overwrite_total'};
                   12307:                 for (my $i=0; $i<$total; $i++) {
                   12308:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12309:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12310:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12311:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12312:                     }
                   12313:                 }
                   12314:             }
                   12315:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12316:             my $numoverwrite = scalar(@to_overwrite);
                   12317:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12318:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12319:             } elsif ($dir eq '') {
1.1055    raeburn  12320:                 $error = &mt('Directory containing archive file unavailable.');
                   12321:             } elsif (!$error) {
1.1065    raeburn  12322:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12323:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12324:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12325:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12326:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12327:                         ($decompressed,$display) =
                   12328:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12329:                         foreach my $item (@to_skip) {
                   12330:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12331:                                 if (-f "$dir/$tempdir/$item") {
                   12332:                                     unlink("$dir/$tempdir/$item");
                   12333:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12334:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12335:                                 }
                   12336:                             }
                   12337:                         }
                   12338:                         foreach my $item (@to_overwrite) {
                   12339:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12340:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12341:                                     if (-f "$dir/$item") {
                   12342:                                         unlink("$dir/$item");
                   12343:                                     } elsif (-d "$dir/$item") {
                   12344:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12345:                                     }
                   12346:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12347:                                 }
1.1065    raeburn  12348:                             }
                   12349:                         }
1.1075.2.128  raeburn  12350:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12351:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12352:                         }
1.1065    raeburn  12353:                     }
                   12354:                 } else {
                   12355:                     ($decompressed,$display) = 
                   12356:                         &decompress_uploaded_file($file,$dir);
                   12357:                 }
1.1055    raeburn  12358:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12359:                     $output = '<p class="LC_info">'.
                   12360:                               &mt('Files extracted successfully from archive.').
                   12361:                               '</p>'."\n";
1.1055    raeburn  12362:                     my ($warning,$result,@contents);
                   12363:                     my ($newdirlistref,$newlisterror) =
                   12364:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12365:                                                  $docuname,1);
                   12366:                     my (%is_dir,%changes,@newitems);
                   12367:                     my $dirptr = 16384;
1.1065    raeburn  12368:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12369:                         foreach my $dir_line (@{$newdirlistref}) {
                   12370:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12371:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12372:                                 push(@newitems,$item);
                   12373:                                 if ($dirptr&$testdir) {
                   12374:                                     $is_dir{$item} = 1;
                   12375:                                 }
                   12376:                                 $changes{$item} = 1;
                   12377:                             }
                   12378:                         }
                   12379:                     }
                   12380:                     if (keys(%changes) > 0) {
                   12381:                         foreach my $item (sort(@newitems)) {
                   12382:                             if ($changes{$item}) {
                   12383:                                 push(@contents,$item);
                   12384:                             }
                   12385:                         }
                   12386:                     }
                   12387:                     if (@contents > 0) {
1.1067    raeburn  12388:                         my $wantform;
                   12389:                         unless ($env{'form.autoextract_camtasia'}) {
                   12390:                             $wantform = 1;
                   12391:                         }
1.1056    raeburn  12392:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12393:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12394:                                                                 $currdir,\%is_dir,
                   12395:                                                                 \%children,\%parent,
1.1056    raeburn  12396:                                                                 \@contents,\%dirorder,
                   12397:                                                                 \%titles,$wantform);
1.1055    raeburn  12398:                         if ($datatable ne '') {
                   12399:                             $output .= &archive_options_form('decompressed',$datatable,
                   12400:                                                              $count,$hiddenelem);
1.1065    raeburn  12401:                             my $startcount = 6;
1.1055    raeburn  12402:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12403:                                                            \%titles,\%children);
1.1055    raeburn  12404:                         }
1.1067    raeburn  12405:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12406:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12407:                             my %displayed;
                   12408:                             my $total = 1;
                   12409:                             $env{'form.archive_directory'} = [];
                   12410:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12411:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12412:                                 $path =~ s{/$}{};
                   12413:                                 my $item;
                   12414:                                 if ($path ne '') {
                   12415:                                     $item = "$path/$titles{$i}";
                   12416:                                 } else {
                   12417:                                     $item = $titles{$i};
                   12418:                                 }
                   12419:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12420:                                 if ($item eq $contents[0]) {
                   12421:                                     push(@{$env{'form.archive_directory'}},$i);
                   12422:                                     $env{'form.archive_'.$i} = 'display';
                   12423:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12424:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12425:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12426:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12427:                                     $env{'form.archive_'.$i} = 'display';
                   12428:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12429:                                     $displayed{'web'} = $i;
                   12430:                                 } else {
1.1075.2.59  raeburn  12431:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12432:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12433:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12434:                                         push(@{$env{'form.archive_directory'}},$i);
                   12435:                                     }
                   12436:                                     $env{'form.archive_'.$i} = 'dependency';
                   12437:                                 }
                   12438:                                 $total ++;
                   12439:                             }
                   12440:                             for (my $i=1; $i<$total; $i++) {
                   12441:                                 next if ($i == $displayed{'web'});
                   12442:                                 next if ($i == $displayed{'folder'});
                   12443:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12444:                             }
                   12445:                             $env{'form.phase'} = 'decompress_cleanup';
                   12446:                             $env{'form.archivedelete'} = 1;
                   12447:                             $env{'form.archive_count'} = $total-1;
                   12448:                             $output .=
                   12449:                                 &process_extracted_files('coursedocs',$docudom,
                   12450:                                                          $docuname,$destination,
                   12451:                                                          $dir_root,$hiddenelem);
                   12452:                         }
1.1055    raeburn  12453:                     } else {
                   12454:                         $warning = &mt('No new items extracted from archive file.');
                   12455:                     }
                   12456:                 } else {
                   12457:                     $output = $display;
                   12458:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12459:                 }
                   12460:             }
                   12461:         }
                   12462:     }
                   12463:     if ($error) {
                   12464:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12465:                    $error.'</p>'."\n";
                   12466:     }
                   12467:     if ($warning) {
                   12468:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12469:     }
                   12470:     return $output;
                   12471: }
                   12472: 
                   12473: sub get_extracted {
1.1056    raeburn  12474:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12475:         $titles,$wantform) = @_;
1.1055    raeburn  12476:     my $count = 0;
                   12477:     my $depth = 0;
                   12478:     my $datatable;
1.1056    raeburn  12479:     my @hierarchy;
1.1055    raeburn  12480:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12481:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12482:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12483:     foreach my $item (@{$contents}) {
                   12484:         $count ++;
1.1056    raeburn  12485:         @{$dirorder->{$count}} = @hierarchy;
                   12486:         $titles->{$count} = $item;
1.1055    raeburn  12487:         &archive_hierarchy($depth,$count,$parent,$children);
                   12488:         if ($wantform) {
                   12489:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12490:                                        $currdir,$depth,$count);
                   12491:         }
                   12492:         if ($is_dir->{$item}) {
                   12493:             $depth ++;
1.1056    raeburn  12494:             push(@hierarchy,$count);
                   12495:             $parent->{$depth} = $count;
1.1055    raeburn  12496:             $datatable .=
                   12497:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12498:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12499:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12500:             $depth --;
1.1056    raeburn  12501:             pop(@hierarchy);
1.1055    raeburn  12502:         }
                   12503:     }
                   12504:     return ($count,$datatable);
                   12505: }
                   12506: 
                   12507: sub recurse_extracted_archive {
1.1056    raeburn  12508:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12509:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12510:     my $result='';
1.1056    raeburn  12511:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12512:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12513:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12514:         return $result;
                   12515:     }
                   12516:     my $dirptr = 16384;
                   12517:     my ($newdirlistref,$newlisterror) =
                   12518:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12519:     if (ref($newdirlistref) eq 'ARRAY') {
                   12520:         foreach my $dir_line (@{$newdirlistref}) {
                   12521:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12522:             unless ($item =~ /^\.+$/) {
                   12523:                 $$count ++;
1.1056    raeburn  12524:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12525:                 $titles->{$$count} = $item;
1.1055    raeburn  12526:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12527: 
1.1055    raeburn  12528:                 my $is_dir;
                   12529:                 if ($dirptr&$testdir) {
                   12530:                     $is_dir = 1;
                   12531:                 }
                   12532:                 if ($wantform) {
                   12533:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12534:                 }
                   12535:                 if ($is_dir) {
                   12536:                     $$depth ++;
1.1056    raeburn  12537:                     push(@{$hierarchy},$$count);
                   12538:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12539:                     $result .=
                   12540:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12541:                                                    $docuname,$depth,$count,
1.1056    raeburn  12542:                                                    $hierarchy,$dirorder,$children,
                   12543:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12544:                     $$depth --;
1.1056    raeburn  12545:                     pop(@{$hierarchy});
1.1055    raeburn  12546:                 }
                   12547:             }
                   12548:         }
                   12549:     }
                   12550:     return $result;
                   12551: }
                   12552: 
                   12553: sub archive_hierarchy {
                   12554:     my ($depth,$count,$parent,$children) =@_;
                   12555:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12556:         if (exists($parent->{$depth})) {
                   12557:              $children->{$parent->{$depth}} .= $count.':';
                   12558:         }
                   12559:     }
                   12560:     return;
                   12561: }
                   12562: 
                   12563: sub archive_row {
                   12564:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12565:     my ($name) = ($item =~ m{([^/]+)$});
                   12566:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12567:                                        'display'    => 'Add as file',
1.1055    raeburn  12568:                                        'dependency' => 'Include as dependency',
                   12569:                                        'discard'    => 'Discard',
                   12570:                                       );
                   12571:     if ($is_dir) {
1.1059    raeburn  12572:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12573:     }
1.1056    raeburn  12574:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12575:     my $offset = 0;
1.1055    raeburn  12576:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12577:         $offset ++;
1.1065    raeburn  12578:         if ($action ne 'display') {
                   12579:             $offset ++;
                   12580:         }  
1.1055    raeburn  12581:         $output .= '<td><span class="LC_nobreak">'.
                   12582:                    '<label><input type="radio" name="archive_'.$count.
                   12583:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12584:         my $text = $choices{$action};
                   12585:         if ($is_dir) {
                   12586:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12587:             if ($action eq 'display') {
1.1059    raeburn  12588:                 $text = &mt('Add as folder');
1.1055    raeburn  12589:             }
1.1056    raeburn  12590:         } else {
                   12591:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12592: 
                   12593:         }
                   12594:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12595:         if ($action eq 'dependency') {
                   12596:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12597:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12598:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12599:                        '<option value=""></option>'."\n".
                   12600:                        '</select>'."\n".
                   12601:                        '</div>';
1.1059    raeburn  12602:         } elsif ($action eq 'display') {
                   12603:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12604:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12605:                        '</div>';
1.1055    raeburn  12606:         }
1.1056    raeburn  12607:         $output .= '</td>';
1.1055    raeburn  12608:     }
                   12609:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12610:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12611:     for (my $i=0; $i<$depth; $i++) {
                   12612:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12613:     }
                   12614:     if ($is_dir) {
                   12615:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12616:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12617:     } else {
                   12618:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12619:     }
                   12620:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12621:                &end_data_table_row();
                   12622:     return $output;
                   12623: }
                   12624: 
                   12625: sub archive_options_form {
1.1065    raeburn  12626:     my ($form,$display,$count,$hiddenelem) = @_;
                   12627:     my %lt = &Apache::lonlocal::texthash(
                   12628:                perm => 'Permanently remove archive file?',
                   12629:                hows => 'How should each extracted item be incorporated in the course?',
                   12630:                cont => 'Content actions for all',
                   12631:                addf => 'Add as folder/file',
                   12632:                incd => 'Include as dependency for a displayed file',
                   12633:                disc => 'Discard',
                   12634:                no   => 'No',
                   12635:                yes  => 'Yes',
                   12636:                save => 'Save',
                   12637:     );
                   12638:     my $output = <<"END";
                   12639: <form name="$form" method="post" action="">
                   12640: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12641: <label>
                   12642:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12643: </label>
                   12644: &nbsp;
                   12645: <label>
                   12646:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12647: </span>
                   12648: </p>
                   12649: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12650: <br />$lt{'hows'}
                   12651: <div class="LC_columnSection">
                   12652:   <fieldset>
                   12653:     <legend>$lt{'cont'}</legend>
                   12654:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12655:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12656:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12657:   </fieldset>
                   12658: </div>
                   12659: END
                   12660:     return $output.
1.1055    raeburn  12661:            &start_data_table()."\n".
1.1065    raeburn  12662:            $display."\n".
1.1055    raeburn  12663:            &end_data_table()."\n".
                   12664:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12665:            $hiddenelem.
1.1065    raeburn  12666:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12667:            '</form>';
                   12668: }
                   12669: 
                   12670: sub archive_javascript {
1.1056    raeburn  12671:     my ($startcount,$numitems,$titles,$children) = @_;
                   12672:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12673:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12674:     my $scripttag = <<START;
                   12675: <script type="text/javascript">
                   12676: // <![CDATA[
                   12677: 
                   12678: function checkAll(form,prefix) {
                   12679:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12680:     for (var i=0; i < form.elements.length; i++) {
                   12681:         var id = form.elements[i].id;
                   12682:         if ((id != '') && (id != undefined)) {
                   12683:             if (idstr.test(id)) {
                   12684:                 if (form.elements[i].type == 'radio') {
                   12685:                     form.elements[i].checked = true;
1.1056    raeburn  12686:                     var nostart = i-$startcount;
1.1059    raeburn  12687:                     var offset = nostart%7;
                   12688:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12689:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12690:                 }
                   12691:             }
                   12692:         }
                   12693:     }
                   12694: }
                   12695: 
                   12696: function propagateCheck(form,count) {
                   12697:     if (count > 0) {
1.1059    raeburn  12698:         var startelement = $startcount + ((count-1) * 7);
                   12699:         for (var j=1; j<6; j++) {
                   12700:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12701:                 var item = startelement + j; 
                   12702:                 if (form.elements[item].type == 'radio') {
                   12703:                     if (form.elements[item].checked) {
                   12704:                         containerCheck(form,count,j);
                   12705:                         break;
                   12706:                     }
1.1055    raeburn  12707:                 }
                   12708:             }
                   12709:         }
                   12710:     }
                   12711: }
                   12712: 
                   12713: numitems = $numitems
1.1056    raeburn  12714: var titles = new Array(numitems);
                   12715: var parents = new Array(numitems);
1.1055    raeburn  12716: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12717:     parents[i] = new Array;
1.1055    raeburn  12718: }
1.1059    raeburn  12719: var maintitle = '$maintitle';
1.1055    raeburn  12720: 
                   12721: START
                   12722: 
1.1056    raeburn  12723:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12724:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12725:         for (my $i=0; $i<@contents; $i ++) {
                   12726:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12727:         }
                   12728:     }
                   12729: 
1.1056    raeburn  12730:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12731:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12732:     }
                   12733: 
1.1055    raeburn  12734:     $scripttag .= <<END;
                   12735: 
                   12736: function containerCheck(form,count,offset) {
                   12737:     if (count > 0) {
1.1056    raeburn  12738:         dependencyCheck(form,count,offset);
1.1059    raeburn  12739:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12740:         form.elements[item].checked = true;
                   12741:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12742:             if (parents[count].length > 0) {
                   12743:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12744:                     containerCheck(form,parents[count][j],offset);
                   12745:                 }
                   12746:             }
                   12747:         }
                   12748:     }
                   12749: }
                   12750: 
                   12751: function dependencyCheck(form,count,offset) {
                   12752:     if (count > 0) {
1.1059    raeburn  12753:         var chosen = (offset+$startcount)+7*(count-1);
                   12754:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12755:         var currtype = form.elements[depitem].type;
                   12756:         if (form.elements[chosen].value == 'dependency') {
                   12757:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12758:             form.elements[depitem].options.length = 0;
                   12759:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12760:             for (var i=1; i<=numitems; i++) {
                   12761:                 if (i == count) {
                   12762:                     continue;
                   12763:                 }
1.1059    raeburn  12764:                 var startelement = $startcount + (i-1) * 7;
                   12765:                 for (var j=1; j<6; j++) {
                   12766:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12767:                         var item = startelement + j;
                   12768:                         if (form.elements[item].type == 'radio') {
                   12769:                             if (form.elements[item].checked) {
                   12770:                                 if (form.elements[item].value == 'display') {
                   12771:                                     var n = form.elements[depitem].options.length;
                   12772:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12773:                                 }
                   12774:                             }
                   12775:                         }
                   12776:                     }
                   12777:                 }
                   12778:             }
                   12779:         } else {
                   12780:             document.getElementById('arc_depon_'+count).style.display='none';
                   12781:             form.elements[depitem].options.length = 0;
                   12782:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12783:         }
1.1059    raeburn  12784:         titleCheck(form,count,offset);
1.1056    raeburn  12785:     }
                   12786: }
                   12787: 
                   12788: function propagateSelect(form,count,offset) {
                   12789:     if (count > 0) {
1.1065    raeburn  12790:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12791:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12792:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12793:             if (parents[count].length > 0) {
                   12794:                 for (var j=0; j<parents[count].length; j++) {
                   12795:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12796:                 }
                   12797:             }
                   12798:         }
                   12799:     }
                   12800: }
1.1056    raeburn  12801: 
                   12802: function containerSelect(form,count,offset,picked) {
                   12803:     if (count > 0) {
1.1065    raeburn  12804:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12805:         if (form.elements[item].type == 'radio') {
                   12806:             if (form.elements[item].value == 'dependency') {
                   12807:                 if (form.elements[item+1].type == 'select-one') {
                   12808:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12809:                         if (form.elements[item+1].options[i].value == picked) {
                   12810:                             form.elements[item+1].selectedIndex = i;
                   12811:                             break;
                   12812:                         }
                   12813:                     }
                   12814:                 }
                   12815:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12816:                     if (parents[count].length > 0) {
                   12817:                         for (var j=0; j<parents[count].length; j++) {
                   12818:                             containerSelect(form,parents[count][j],offset,picked);
                   12819:                         }
                   12820:                     }
                   12821:                 }
                   12822:             }
                   12823:         }
                   12824:     }
                   12825: }
                   12826: 
1.1059    raeburn  12827: function titleCheck(form,count,offset) {
                   12828:     if (count > 0) {
                   12829:         var chosen = (offset+$startcount)+7*(count-1);
                   12830:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12831:         var currtype = form.elements[depitem].type;
                   12832:         if (form.elements[chosen].value == 'display') {
                   12833:             document.getElementById('arc_title_'+count).style.display='block';
                   12834:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12835:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12836:             }
                   12837:         } else {
                   12838:             document.getElementById('arc_title_'+count).style.display='none';
                   12839:             if (currtype == 'text') { 
                   12840:                 document.getElementById('archive_title_'+count).value='';
                   12841:             }
                   12842:         }
                   12843:     }
                   12844:     return;
                   12845: }
                   12846: 
1.1055    raeburn  12847: // ]]>
                   12848: </script>
                   12849: END
                   12850:     return $scripttag;
                   12851: }
                   12852: 
                   12853: sub process_extracted_files {
1.1067    raeburn  12854:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12855:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  12856:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  12857:     my @ids=&Apache::lonnet::current_machine_ids();
                   12858:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12859:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12860:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12861:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12862:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12863:         $pathtocheck = "$dir_root/$destination";
                   12864:         $dir = $dir_root;
                   12865:         $ishome = 1;
                   12866:     } else {
                   12867:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12868:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  12869:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  12870:     }
                   12871:     my $currdir = "$dir_root/$destination";
                   12872:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12873:     if ($env{'form.folderpath'}) {
                   12874:         my @items = split('&',$env{'form.folderpath'});
                   12875:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12876:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12877:             $containers{'0'}='page';
                   12878:         } else {
                   12879:             $containers{'0'}='sequence';
                   12880:         }
1.1055    raeburn  12881:     }
                   12882:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12883:     if ($numitems) {
                   12884:         for (my $i=1; $i<=$numitems; $i++) {
                   12885:             my $path = $env{'form.archive_content_'.$i};
                   12886:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12887:                 my $item = $1;
                   12888:                 $toplevelitems{$item} = $i;
                   12889:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12890:                     $is_dir{$item} = 1;
                   12891:                 }
                   12892:             }
                   12893:         }
                   12894:     }
1.1067    raeburn  12895:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12896:     if (keys(%toplevelitems) > 0) {
                   12897:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12898:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12899:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12900:     }
1.1066    raeburn  12901:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12902:     if ($numitems) {
                   12903:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12904:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12905:             my $path = $env{'form.archive_content_'.$i};
                   12906:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12907:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12908:                     if ($prefix ne '' && $path ne '') {
                   12909:                         if (-e $prefix.$path) {
1.1066    raeburn  12910:                             if ((@archdirs > 0) && 
                   12911:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12912:                                 $todeletedir{$prefix.$path} = 1;
                   12913:                             } else {
                   12914:                                 $todelete{$prefix.$path} = 1;
                   12915:                             }
1.1055    raeburn  12916:                         }
                   12917:                     }
                   12918:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12919:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12920:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12921:                     $docstitle = $env{'form.archive_title_'.$i};
                   12922:                     if ($docstitle eq '') {
                   12923:                         $docstitle = $title;
                   12924:                     }
1.1055    raeburn  12925:                     $outer = 0;
1.1056    raeburn  12926:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12927:                         if (@{$dirorder{$i}} > 0) {
                   12928:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12929:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12930:                                     $outer = $item;
                   12931:                                     last;
                   12932:                                 }
                   12933:                             }
                   12934:                         }
                   12935:                     }
                   12936:                     my ($errtext,$fatal) = 
                   12937:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12938:                                                '/'.$folders{$outer}.'.'.
                   12939:                                                $containers{$outer});
                   12940:                     next if ($fatal);
                   12941:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12942:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12943:                             $mapinner{$i} = time;
1.1055    raeburn  12944:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12945:                             $containers{$i} = 'sequence';
                   12946:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12947:                                       $folders{$i}.'.'.$containers{$i};
                   12948:                             my $newidx = &LONCAPA::map::getresidx();
                   12949:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12950:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12951:                             push(@LONCAPA::map::order,$newidx);
                   12952:                             my ($outtext,$errtext) =
                   12953:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12954:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12955:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12956:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12957:                             unless ($errtext) {
1.1075.2.128  raeburn  12958:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   12959:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   12960:                                             '</li>'."\n";
1.1067    raeburn  12961:                             }
1.1055    raeburn  12962:                         }
                   12963:                     } else {
                   12964:                         if ($context eq 'coursedocs') {
                   12965:                             my $newidx=&LONCAPA::map::getresidx();
                   12966:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12967:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12968:                                       $title;
1.1075.2.128  raeburn  12969:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   12970:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12971:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  12972:                                 }
1.1075.2.128  raeburn  12973:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12974:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12975:                                 }
                   12976:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12977:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   12978:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   12979:                                         unless ($ishome) {
                   12980:                                             my $fetch = "$newdest{$i}/$title";
                   12981:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   12982:                                             $prompttofetch{$fetch} = 1;
                   12983:                                         }
                   12984:                                    }
                   12985:                                 }
                   12986:                                 $LONCAPA::map::resources[$newidx]=
                   12987:                                     $docstitle.':'.$url.':false:normal:res';
                   12988:                                 push(@LONCAPA::map::order, $newidx);
                   12989:                                 my ($outtext,$errtext)=
                   12990:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12991:                                                             $docuname.'/'.$folders{$outer}.
                   12992:                                                             '.'.$containers{$outer},1,1);
                   12993:                                 unless ($errtext) {
                   12994:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12995:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   12996:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   12997:                                                    '</li>'."\n";
                   12998:                                     }
1.1067    raeburn  12999:                                 }
1.1075.2.128  raeburn  13000:                             } else {
                   13001:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13002:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  13003:                             }
1.1055    raeburn  13004:                         }
                   13005:                     }
1.1075.2.11  raeburn  13006:                 }
                   13007:             } else {
1.1075.2.128  raeburn  13008:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13009:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  13010:             }
                   13011:         }
                   13012:         for (my $i=1; $i<=$numitems; $i++) {
                   13013:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13014:             my $path = $env{'form.archive_content_'.$i};
                   13015:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13016:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13017:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13018:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13019:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13020:                         my ($itemidx,$fullpath,$relpath);
                   13021:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13022:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13023:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13024:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13025:                                     $itemidx = $j;
1.1056    raeburn  13026:                                 }
                   13027:                             }
1.1075.2.11  raeburn  13028:                         }
                   13029:                         if ($itemidx eq '') {
                   13030:                             $itemidx =  0;
                   13031:                         }
                   13032:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13033:                             if ($mapinner{$referrer{$i}}) {
                   13034:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13035:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13036:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13037:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13038:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13039:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13040:                                             if (!-e $fullpath) {
                   13041:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13042:                                             }
                   13043:                                         }
1.1075.2.11  raeburn  13044:                                     } else {
                   13045:                                         last;
1.1056    raeburn  13046:                                     }
1.1075.2.11  raeburn  13047:                                 }
                   13048:                             }
                   13049:                         } elsif ($newdest{$referrer{$i}}) {
                   13050:                             $fullpath = $newdest{$referrer{$i}};
                   13051:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13052:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13053:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13054:                                     last;
                   13055:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13056:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13057:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13058:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13059:                                         if (!-e $fullpath) {
                   13060:                                             mkdir($fullpath,0755);
1.1056    raeburn  13061:                                         }
                   13062:                                     }
1.1075.2.11  raeburn  13063:                                 } else {
                   13064:                                     last;
1.1056    raeburn  13065:                                 }
1.1075.2.11  raeburn  13066:                             }
                   13067:                         }
                   13068:                         if ($fullpath ne '') {
                   13069:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13070:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13071:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13072:                                 }
1.1075.2.11  raeburn  13073:                             }
                   13074:                             if (-e "$fullpath/$title") {
                   13075:                                 my $showpath;
                   13076:                                 if ($relpath ne '') {
                   13077:                                     $showpath = "$relpath/$title";
                   13078:                                 } else {
                   13079:                                     $showpath = "/$title";
1.1056    raeburn  13080:                                 }
1.1075.2.128  raeburn  13081:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13082:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13083:                                            '</li>'."\n";
                   13084:                                 unless ($ishome) {
                   13085:                                     my $fetch = "$fullpath/$title";
                   13086:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13087:                                     $prompttofetch{$fetch} = 1;
                   13088:                                 }
1.1055    raeburn  13089:                             }
                   13090:                         }
                   13091:                     }
1.1075.2.11  raeburn  13092:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13093:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13094:                                     &HTML::Entities::encode($path,'<>&"'),
                   13095:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13096:                                 '<br />';
1.1055    raeburn  13097:                 }
                   13098:             } else {
1.1075.2.128  raeburn  13099:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13100:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13101:             }
                   13102:         }
                   13103:         if (keys(%todelete)) {
                   13104:             foreach my $key (keys(%todelete)) {
                   13105:                 unlink($key);
1.1066    raeburn  13106:             }
                   13107:         }
                   13108:         if (keys(%todeletedir)) {
                   13109:             foreach my $key (keys(%todeletedir)) {
                   13110:                 rmdir($key);
                   13111:             }
                   13112:         }
                   13113:         foreach my $dir (sort(keys(%is_dir))) {
                   13114:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13115:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13116:             }
                   13117:         }
1.1067    raeburn  13118:         if ($result ne '') {
                   13119:             $output .= '<ul>'."\n".
                   13120:                        $result."\n".
                   13121:                        '</ul>';
                   13122:         }
                   13123:         unless ($ishome) {
                   13124:             my $replicationfail;
                   13125:             foreach my $item (keys(%prompttofetch)) {
                   13126:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13127:                 unless ($fetchresult eq 'ok') {
                   13128:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13129:                 }
                   13130:             }
                   13131:             if ($replicationfail) {
                   13132:                 $output .= '<p class="LC_error">'.
                   13133:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13134:                            $replicationfail.
                   13135:                            '</ul></p>';
                   13136:             }
                   13137:         }
1.1055    raeburn  13138:     } else {
                   13139:         $warning = &mt('No items found in archive.');
                   13140:     }
                   13141:     if ($error) {
                   13142:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13143:                    $error.'</p>'."\n";
                   13144:     }
                   13145:     if ($warning) {
                   13146:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13147:     }
                   13148:     return $output;
                   13149: }
                   13150: 
1.1066    raeburn  13151: sub cleanup_empty_dirs {
                   13152:     my ($path) = @_;
                   13153:     if (($path ne '') && (-d $path)) {
                   13154:         if (opendir(my $dirh,$path)) {
                   13155:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13156:             my $numitems = 0;
                   13157:             foreach my $item (@dircontents) {
                   13158:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13159:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13160:                     if (-e "$path/$item") {
                   13161:                         $numitems ++;
                   13162:                     }
                   13163:                 } else {
                   13164:                     $numitems ++;
                   13165:                 }
                   13166:             }
                   13167:             if ($numitems == 0) {
                   13168:                 rmdir($path);
                   13169:             }
                   13170:             closedir($dirh);
                   13171:         }
                   13172:     }
                   13173:     return;
                   13174: }
                   13175: 
1.41      ng       13176: =pod
1.45      matthew  13177: 
1.1075.2.56  raeburn  13178: =item * &get_folder_hierarchy()
1.1068    raeburn  13179: 
                   13180: Provides hierarchy of names of folders/sub-folders containing the current
                   13181: item,
                   13182: 
                   13183: Inputs: 3
                   13184:      - $navmap - navmaps object
                   13185: 
                   13186:      - $map - url for map (either the trigger itself, or map containing
                   13187:                            the resource, which is the trigger).
                   13188: 
                   13189:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13190: 
                   13191: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13192: 
                   13193: =cut
                   13194: 
                   13195: sub get_folder_hierarchy {
                   13196:     my ($navmap,$map,$showitem) = @_;
                   13197:     my @pathitems;
                   13198:     if (ref($navmap)) {
                   13199:         my $mapres = $navmap->getResourceByUrl($map);
                   13200:         if (ref($mapres)) {
                   13201:             my $pcslist = $mapres->map_hierarchy();
                   13202:             if ($pcslist ne '') {
                   13203:                 my @pcs = split(/,/,$pcslist);
                   13204:                 foreach my $pc (@pcs) {
                   13205:                     if ($pc == 1) {
1.1075.2.38  raeburn  13206:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13207:                     } else {
                   13208:                         my $res = $navmap->getByMapPc($pc);
                   13209:                         if (ref($res)) {
                   13210:                             my $title = $res->compTitle();
                   13211:                             $title =~ s/\W+/_/g;
                   13212:                             if ($title ne '') {
                   13213:                                 push(@pathitems,$title);
                   13214:                             }
                   13215:                         }
                   13216:                     }
                   13217:                 }
                   13218:             }
1.1071    raeburn  13219:             if ($showitem) {
                   13220:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13221:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13222:                 } else {
                   13223:                     my $maptitle = $mapres->compTitle();
                   13224:                     $maptitle =~ s/\W+/_/g;
                   13225:                     if ($maptitle ne '') {
                   13226:                         push(@pathitems,$maptitle);
                   13227:                     }
1.1068    raeburn  13228:                 }
                   13229:             }
                   13230:         }
                   13231:     }
                   13232:     return @pathitems;
                   13233: }
                   13234: 
                   13235: =pod
                   13236: 
1.1015    raeburn  13237: =item * &get_turnedin_filepath()
                   13238: 
                   13239: Determines path in a user's portfolio file for storage of files uploaded
                   13240: to a specific essayresponse or dropbox item.
                   13241: 
                   13242: Inputs: 3 required + 1 optional.
                   13243: $symb is symb for resource, $uname and $udom are for current user (required).
                   13244: $caller is optional (can be "submission", if routine is called when storing
                   13245: an upoaded file when "Submit Answer" button was pressed).
                   13246: 
                   13247: Returns array containing $path and $multiresp. 
                   13248: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13249: than one file upload item.  Callers of routine should append partid as a 
                   13250: subdirectory to $path in cases where $multiresp is 1.
                   13251: 
                   13252: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13253: 
                   13254: =cut
                   13255: 
                   13256: sub get_turnedin_filepath {
                   13257:     my ($symb,$uname,$udom,$caller) = @_;
                   13258:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13259:     my $turnindir;
                   13260:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13261:     $turnindir = $userhash{'turnindir'};
                   13262:     my ($path,$multiresp);
                   13263:     if ($turnindir eq '') {
                   13264:         if ($caller eq 'submission') {
                   13265:             $turnindir = &mt('turned in');
                   13266:             $turnindir =~ s/\W+/_/g;
                   13267:             my %newhash = (
                   13268:                             'turnindir' => $turnindir,
                   13269:                           );
                   13270:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13271:         }
                   13272:     }
                   13273:     if ($turnindir ne '') {
                   13274:         $path = '/'.$turnindir.'/';
                   13275:         my ($multipart,$turnin,@pathitems);
                   13276:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13277:         if (defined($navmap)) {
                   13278:             my $mapres = $navmap->getResourceByUrl($map);
                   13279:             if (ref($mapres)) {
                   13280:                 my $pcslist = $mapres->map_hierarchy();
                   13281:                 if ($pcslist ne '') {
                   13282:                     foreach my $pc (split(/,/,$pcslist)) {
                   13283:                         my $res = $navmap->getByMapPc($pc);
                   13284:                         if (ref($res)) {
                   13285:                             my $title = $res->compTitle();
                   13286:                             $title =~ s/\W+/_/g;
                   13287:                             if ($title ne '') {
1.1075.2.48  raeburn  13288:                                 if (($pc > 1) && (length($title) > 12)) {
                   13289:                                     $title = substr($title,0,12);
                   13290:                                 }
1.1015    raeburn  13291:                                 push(@pathitems,$title);
                   13292:                             }
                   13293:                         }
                   13294:                     }
                   13295:                 }
                   13296:                 my $maptitle = $mapres->compTitle();
                   13297:                 $maptitle =~ s/\W+/_/g;
                   13298:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13299:                     if (length($maptitle) > 12) {
                   13300:                         $maptitle = substr($maptitle,0,12);
                   13301:                     }
1.1015    raeburn  13302:                     push(@pathitems,$maptitle);
                   13303:                 }
                   13304:                 unless ($env{'request.state'} eq 'construct') {
                   13305:                     my $res = $navmap->getBySymb($symb);
                   13306:                     if (ref($res)) {
                   13307:                         my $partlist = $res->parts();
                   13308:                         my $totaluploads = 0;
                   13309:                         if (ref($partlist) eq 'ARRAY') {
                   13310:                             foreach my $part (@{$partlist}) {
                   13311:                                 my @types = $res->responseType($part);
                   13312:                                 my @ids = $res->responseIds($part);
                   13313:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13314:                                     if ($types[$i] eq 'essay') {
                   13315:                                         my $partid = $part.'_'.$ids[$i];
                   13316:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13317:                                             $totaluploads ++;
                   13318:                                         }
                   13319:                                     }
                   13320:                                 }
                   13321:                             }
                   13322:                             if ($totaluploads > 1) {
                   13323:                                 $multiresp = 1;
                   13324:                             }
                   13325:                         }
                   13326:                     }
                   13327:                 }
                   13328:             } else {
                   13329:                 return;
                   13330:             }
                   13331:         } else {
                   13332:             return;
                   13333:         }
                   13334:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13335:         $restitle =~ s/\W+/_/g;
                   13336:         if ($restitle eq '') {
                   13337:             $restitle = ($resurl =~ m{/[^/]+$});
                   13338:             if ($restitle eq '') {
                   13339:                 $restitle = time;
                   13340:             }
                   13341:         }
1.1075.2.48  raeburn  13342:         if (length($restitle) > 12) {
                   13343:             $restitle = substr($restitle,0,12);
                   13344:         }
1.1015    raeburn  13345:         push(@pathitems,$restitle);
                   13346:         $path .= join('/',@pathitems);
                   13347:     }
                   13348:     return ($path,$multiresp);
                   13349: }
                   13350: 
                   13351: =pod
                   13352: 
1.464     albertel 13353: =back
1.41      ng       13354: 
1.112     bowersj2 13355: =head1 CSV Upload/Handling functions
1.38      albertel 13356: 
1.41      ng       13357: =over 4
                   13358: 
1.648     raeburn  13359: =item * &upfile_store($r)
1.41      ng       13360: 
                   13361: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13362: needs $env{'form.upfile'}
1.41      ng       13363: returns $datatoken to be put into hidden field
                   13364: 
                   13365: =cut
1.31      albertel 13366: 
                   13367: sub upfile_store {
                   13368:     my $r=shift;
1.258     albertel 13369:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13370:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13371:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13372:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13373: 
1.1075.2.128  raeburn  13374:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13375:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13376:                                      time.'_'.$$);
                   13377:     return if ($datatoken eq '');
                   13378: 
1.31      albertel 13379:     {
1.158     raeburn  13380:         my $datafile = $r->dir_config('lonDaemons').
                   13381:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13382:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13383:             print $fh $env{'form.upfile'};
1.158     raeburn  13384:             close($fh);
                   13385:         }
1.31      albertel 13386:     }
                   13387:     return $datatoken;
                   13388: }
                   13389: 
1.56      matthew  13390: =pod
                   13391: 
1.1075.2.128  raeburn  13392: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13393: 
                   13394: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13395: $datatoken is the name to assign to the temporary file.
1.258     albertel 13396: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13397: 
                   13398: =cut
1.31      albertel 13399: 
                   13400: sub load_tmp_file {
1.1075.2.128  raeburn  13401:     my ($r,$datatoken) = @_;
                   13402:     return if ($datatoken eq '');
1.31      albertel 13403:     my @studentdata=();
                   13404:     {
1.158     raeburn  13405:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13406:                               '/tmp/'.$datatoken.'.tmp';
                   13407:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13408:             @studentdata=<$fh>;
                   13409:             close($fh);
                   13410:         }
1.31      albertel 13411:     }
1.258     albertel 13412:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13413: }
                   13414: 
1.1075.2.128  raeburn  13415: sub valid_datatoken {
                   13416:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13417:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13418:         return $datatoken;
                   13419:     }
                   13420:     return;
                   13421: }
                   13422: 
1.56      matthew  13423: =pod
                   13424: 
1.648     raeburn  13425: =item * &upfile_record_sep()
1.41      ng       13426: 
                   13427: Separate uploaded file into records
                   13428: returns array of records,
1.258     albertel 13429: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13430: 
                   13431: =cut
1.31      albertel 13432: 
                   13433: sub upfile_record_sep {
1.258     albertel 13434:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13435:     } else {
1.248     albertel 13436: 	my @records;
1.258     albertel 13437: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13438: 	    if ($line=~/^\s*$/) { next; }
                   13439: 	    push(@records,$line);
                   13440: 	}
                   13441: 	return @records;
1.31      albertel 13442:     }
                   13443: }
                   13444: 
1.56      matthew  13445: =pod
                   13446: 
1.648     raeburn  13447: =item * &record_sep($record)
1.41      ng       13448: 
1.258     albertel 13449: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13450: 
                   13451: =cut
                   13452: 
1.263     www      13453: sub takeleft {
                   13454:     my $index=shift;
                   13455:     return substr('0000'.$index,-4,4);
                   13456: }
                   13457: 
1.31      albertel 13458: sub record_sep {
                   13459:     my $record=shift;
                   13460:     my %components=();
1.258     albertel 13461:     if ($env{'form.upfiletype'} eq 'xml') {
                   13462:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13463:         my $i=0;
1.356     albertel 13464:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13465:             $field=~s/^(\"|\')//;
                   13466:             $field=~s/(\"|\')$//;
1.263     www      13467:             $components{&takeleft($i)}=$field;
1.31      albertel 13468:             $i++;
                   13469:         }
1.258     albertel 13470:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13471:         my $i=0;
1.356     albertel 13472:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13473:             $field=~s/^(\"|\')//;
                   13474:             $field=~s/(\"|\')$//;
1.263     www      13475:             $components{&takeleft($i)}=$field;
1.31      albertel 13476:             $i++;
                   13477:         }
                   13478:     } else {
1.561     www      13479:         my $separator=',';
1.480     banghart 13480:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13481:             $separator=';';
1.480     banghart 13482:         }
1.31      albertel 13483:         my $i=0;
1.561     www      13484: # the character we are looking for to indicate the end of a quote or a record 
                   13485:         my $looking_for=$separator;
                   13486: # do not add the characters to the fields
                   13487:         my $ignore=0;
                   13488: # we just encountered a separator (or the beginning of the record)
                   13489:         my $just_found_separator=1;
                   13490: # store the field we are working on here
                   13491:         my $field='';
                   13492: # work our way through all characters in record
                   13493:         foreach my $character ($record=~/(.)/g) {
                   13494:             if ($character eq $looking_for) {
                   13495:                if ($character ne $separator) {
                   13496: # Found the end of a quote, again looking for separator
                   13497:                   $looking_for=$separator;
                   13498:                   $ignore=1;
                   13499:                } else {
                   13500: # Found a separator, store away what we got
                   13501:                   $components{&takeleft($i)}=$field;
                   13502: 	          $i++;
                   13503:                   $just_found_separator=1;
                   13504:                   $ignore=0;
                   13505:                   $field='';
                   13506:                }
                   13507:                next;
                   13508:             }
                   13509: # single or double quotation marks after a separator indicate beginning of a quote
                   13510: # we are now looking for the end of the quote and need to ignore separators
                   13511:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13512:                $looking_for=$character;
                   13513:                next;
                   13514:             }
                   13515: # ignore would be true after we reached the end of a quote
                   13516:             if ($ignore) { next; }
                   13517:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13518:             $field.=$character;
                   13519:             $just_found_separator=0; 
1.31      albertel 13520:         }
1.561     www      13521: # catch the very last entry, since we never encountered the separator
                   13522:         $components{&takeleft($i)}=$field;
1.31      albertel 13523:     }
                   13524:     return %components;
                   13525: }
                   13526: 
1.144     matthew  13527: ######################################################
                   13528: ######################################################
                   13529: 
1.56      matthew  13530: =pod
                   13531: 
1.648     raeburn  13532: =item * &upfile_select_html()
1.41      ng       13533: 
1.144     matthew  13534: Return HTML code to select a file from the users machine and specify 
                   13535: the file type.
1.41      ng       13536: 
                   13537: =cut
                   13538: 
1.144     matthew  13539: ######################################################
                   13540: ######################################################
1.31      albertel 13541: sub upfile_select_html {
1.144     matthew  13542:     my %Types = (
                   13543:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13544:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13545:                  space => &mt('Space separated'),
                   13546:                  tab   => &mt('Tabulator separated'),
                   13547: #                 xml   => &mt('HTML/XML'),
                   13548:                  );
                   13549:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13550:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13551:     foreach my $type (sort(keys(%Types))) {
                   13552:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13553:     }
                   13554:     $Str .= "</select>\n";
                   13555:     return $Str;
1.31      albertel 13556: }
                   13557: 
1.301     albertel 13558: sub get_samples {
                   13559:     my ($records,$toget) = @_;
                   13560:     my @samples=({});
                   13561:     my $got=0;
                   13562:     foreach my $rec (@$records) {
                   13563: 	my %temp = &record_sep($rec);
                   13564: 	if (! grep(/\S/, values(%temp))) { next; }
                   13565: 	if (%temp) {
                   13566: 	    $samples[$got]=\%temp;
                   13567: 	    $got++;
                   13568: 	    if ($got == $toget) { last; }
                   13569: 	}
                   13570:     }
                   13571:     return \@samples;
                   13572: }
                   13573: 
1.144     matthew  13574: ######################################################
                   13575: ######################################################
                   13576: 
1.56      matthew  13577: =pod
                   13578: 
1.648     raeburn  13579: =item * &csv_print_samples($r,$records)
1.41      ng       13580: 
                   13581: Prints a table of sample values from each column uploaded $r is an
                   13582: Apache Request ref, $records is an arrayref from
                   13583: &Apache::loncommon::upfile_record_sep
                   13584: 
                   13585: =cut
                   13586: 
1.144     matthew  13587: ######################################################
                   13588: ######################################################
1.31      albertel 13589: sub csv_print_samples {
                   13590:     my ($r,$records) = @_;
1.662     bisitz   13591:     my $samples = &get_samples($records,5);
1.301     albertel 13592: 
1.594     raeburn  13593:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13594:               &start_data_table_header_row());
1.356     albertel 13595:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13596:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13597:     $r->print(&end_data_table_header_row());
1.301     albertel 13598:     foreach my $hash (@$samples) {
1.594     raeburn  13599: 	$r->print(&start_data_table_row());
1.356     albertel 13600: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13601: 	    $r->print('<td>');
1.356     albertel 13602: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13603: 	    $r->print('</td>');
                   13604: 	}
1.594     raeburn  13605: 	$r->print(&end_data_table_row());
1.31      albertel 13606:     }
1.594     raeburn  13607:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13608: }
                   13609: 
1.144     matthew  13610: ######################################################
                   13611: ######################################################
                   13612: 
1.56      matthew  13613: =pod
                   13614: 
1.648     raeburn  13615: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13616: 
                   13617: Prints a table to create associations between values and table columns.
1.144     matthew  13618: 
1.41      ng       13619: $r is an Apache Request ref,
                   13620: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13621: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13622: 
                   13623: =cut
                   13624: 
1.144     matthew  13625: ######################################################
                   13626: ######################################################
1.31      albertel 13627: sub csv_print_select_table {
                   13628:     my ($r,$records,$d) = @_;
1.301     albertel 13629:     my $i=0;
                   13630:     my $samples = &get_samples($records,1);
1.144     matthew  13631:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13632: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13633:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13634:               '<th>'.&mt('Column').'</th>'.
                   13635:               &end_data_table_header_row()."\n");
1.356     albertel 13636:     foreach my $array_ref (@$d) {
                   13637: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13638: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13639: 
1.875     bisitz   13640: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13641: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13642: 	$r->print('<option value="none"></option>');
1.356     albertel 13643: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13644: 	    $r->print('<option value="'.$sample.'"'.
                   13645:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13646:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13647: 	}
1.594     raeburn  13648: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13649: 	$i++;
                   13650:     }
1.594     raeburn  13651:     $r->print(&end_data_table());
1.31      albertel 13652:     $i--;
                   13653:     return $i;
                   13654: }
1.56      matthew  13655: 
1.144     matthew  13656: ######################################################
                   13657: ######################################################
                   13658: 
1.56      matthew  13659: =pod
1.31      albertel 13660: 
1.648     raeburn  13661: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13662: 
                   13663: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13664: 
                   13665: $r is an Apache Request ref,
                   13666: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13667: $d is an array of 2 element arrays (internal name, displayed name)
                   13668: 
                   13669: =cut
                   13670: 
1.144     matthew  13671: ######################################################
                   13672: ######################################################
1.31      albertel 13673: sub csv_samples_select_table {
                   13674:     my ($r,$records,$d) = @_;
                   13675:     my $i=0;
1.144     matthew  13676:     #
1.662     bisitz   13677:     my $max_samples = 5;
                   13678:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13679:     $r->print(&start_data_table().
                   13680:               &start_data_table_header_row().'<th>'.
                   13681:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13682:               &end_data_table_header_row());
1.301     albertel 13683: 
                   13684:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13685: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13686: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13687: 	foreach my $option (@$d) {
                   13688: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13689: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13690:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13691:                       $display.'</option>');
1.31      albertel 13692: 	}
                   13693: 	$r->print('</select></td><td>');
1.662     bisitz   13694: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13695: 	    if (defined($samples->[$line]{$key})) { 
                   13696: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13697: 	    }
                   13698: 	}
1.594     raeburn  13699: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13700: 	$i++;
                   13701:     }
1.594     raeburn  13702:     $r->print(&end_data_table());
1.31      albertel 13703:     $i--;
                   13704:     return($i);
1.115     matthew  13705: }
                   13706: 
1.144     matthew  13707: ######################################################
                   13708: ######################################################
                   13709: 
1.115     matthew  13710: =pod
                   13711: 
1.648     raeburn  13712: =item * &clean_excel_name($name)
1.115     matthew  13713: 
                   13714: Returns a replacement for $name which does not contain any illegal characters.
                   13715: 
                   13716: =cut
                   13717: 
1.144     matthew  13718: ######################################################
                   13719: ######################################################
1.115     matthew  13720: sub clean_excel_name {
                   13721:     my ($name) = @_;
                   13722:     $name =~ s/[:\*\?\/\\]//g;
                   13723:     if (length($name) > 31) {
                   13724:         $name = substr($name,0,31);
                   13725:     }
                   13726:     return $name;
1.25      albertel 13727: }
1.84      albertel 13728: 
1.85      albertel 13729: =pod
                   13730: 
1.648     raeburn  13731: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13732: 
                   13733: Returns either 1 or undef
                   13734: 
                   13735: 1 if the part is to be hidden, undef if it is to be shown
                   13736: 
                   13737: Arguments are:
                   13738: 
                   13739: $id the id of the part to be checked
                   13740: $symb, optional the symb of the resource to check
                   13741: $udom, optional the domain of the user to check for
                   13742: $uname, optional the username of the user to check for
                   13743: 
                   13744: =cut
1.84      albertel 13745: 
                   13746: sub check_if_partid_hidden {
                   13747:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13748:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13749: 					 $symb,$udom,$uname);
1.141     albertel 13750:     my $truth=1;
                   13751:     #if the string starts with !, then the list is the list to show not hide
                   13752:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13753:     my @hiddenlist=split(/,/,$hiddenparts);
                   13754:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13755: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13756:     }
1.141     albertel 13757:     return !$truth;
1.84      albertel 13758: }
1.127     matthew  13759: 
1.138     matthew  13760: 
                   13761: ############################################################
                   13762: ############################################################
                   13763: 
                   13764: =pod
                   13765: 
1.157     matthew  13766: =back 
                   13767: 
1.138     matthew  13768: =head1 cgi-bin script and graphing routines
                   13769: 
1.157     matthew  13770: =over 4
                   13771: 
1.648     raeburn  13772: =item * &get_cgi_id()
1.138     matthew  13773: 
                   13774: Inputs: none
                   13775: 
                   13776: Returns an id which can be used to pass environment variables
                   13777: to various cgi-bin scripts.  These environment variables will
                   13778: be removed from the users environment after a given time by
                   13779: the routine &Apache::lonnet::transfer_profile_to_env.
                   13780: 
                   13781: =cut
                   13782: 
                   13783: ############################################################
                   13784: ############################################################
1.152     albertel 13785: my $uniq=0;
1.136     matthew  13786: sub get_cgi_id {
1.154     albertel 13787:     $uniq=($uniq+1)%100000;
1.280     albertel 13788:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13789: }
                   13790: 
1.127     matthew  13791: ############################################################
                   13792: ############################################################
                   13793: 
                   13794: =pod
                   13795: 
1.648     raeburn  13796: =item * &DrawBarGraph()
1.127     matthew  13797: 
1.138     matthew  13798: Facilitates the plotting of data in a (stacked) bar graph.
                   13799: Puts plot definition data into the users environment in order for 
                   13800: graph.png to plot it.  Returns an <img> tag for the plot.
                   13801: The bars on the plot are labeled '1','2',...,'n'.
                   13802: 
                   13803: Inputs:
                   13804: 
                   13805: =over 4
                   13806: 
                   13807: =item $Title: string, the title of the plot
                   13808: 
                   13809: =item $xlabel: string, text describing the X-axis of the plot
                   13810: 
                   13811: =item $ylabel: string, text describing the Y-axis of the plot
                   13812: 
                   13813: =item $Max: scalar, the maximum Y value to use in the plot
                   13814: If $Max is < any data point, the graph will not be rendered.
                   13815: 
1.140     matthew  13816: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13817: they are plotted.  If undefined, default values will be used.
                   13818: 
1.178     matthew  13819: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13820: 
1.138     matthew  13821: =item @Values: An array of array references.  Each array reference holds data
                   13822: to be plotted in a stacked bar chart.
                   13823: 
1.239     matthew  13824: =item If the final element of @Values is a hash reference the key/value
                   13825: pairs will be added to the graph definition.
                   13826: 
1.138     matthew  13827: =back
                   13828: 
                   13829: Returns:
                   13830: 
                   13831: An <img> tag which references graph.png and the appropriate identifying
                   13832: information for the plot.
                   13833: 
1.127     matthew  13834: =cut
                   13835: 
                   13836: ############################################################
                   13837: ############################################################
1.134     matthew  13838: sub DrawBarGraph {
1.178     matthew  13839:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13840:     #
                   13841:     if (! defined($colors)) {
                   13842:         $colors = ['#33ff00', 
                   13843:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13844:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13845:                   ]; 
                   13846:     }
1.228     matthew  13847:     my $extra_settings = {};
                   13848:     if (ref($Values[-1]) eq 'HASH') {
                   13849:         $extra_settings = pop(@Values);
                   13850:     }
1.127     matthew  13851:     #
1.136     matthew  13852:     my $identifier = &get_cgi_id();
                   13853:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13854:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13855:         return '';
                   13856:     }
1.225     matthew  13857:     #
                   13858:     my @Labels;
                   13859:     if (defined($labels)) {
                   13860:         @Labels = @$labels;
                   13861:     } else {
                   13862:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13863:             push(@Labels,$i+1);
1.225     matthew  13864:         }
                   13865:     }
                   13866:     #
1.129     matthew  13867:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13868:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13869:     my %ValuesHash;
                   13870:     my $NumSets=1;
                   13871:     foreach my $array (@Values) {
                   13872:         next if (! ref($array));
1.136     matthew  13873:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13874:             join(',',@$array);
1.129     matthew  13875:     }
1.127     matthew  13876:     #
1.136     matthew  13877:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13878:     if ($NumBars < 3) {
                   13879:         $width = 120+$NumBars*32;
1.220     matthew  13880:         $xskip = 1;
1.225     matthew  13881:         $bar_width = 30;
                   13882:     } elsif ($NumBars < 5) {
                   13883:         $width = 120+$NumBars*20;
                   13884:         $xskip = 1;
                   13885:         $bar_width = 20;
1.220     matthew  13886:     } elsif ($NumBars < 10) {
1.136     matthew  13887:         $width = 120+$NumBars*15;
                   13888:         $xskip = 1;
                   13889:         $bar_width = 15;
                   13890:     } elsif ($NumBars <= 25) {
                   13891:         $width = 120+$NumBars*11;
                   13892:         $xskip = 5;
                   13893:         $bar_width = 8;
                   13894:     } elsif ($NumBars <= 50) {
                   13895:         $width = 120+$NumBars*8;
                   13896:         $xskip = 5;
                   13897:         $bar_width = 4;
                   13898:     } else {
                   13899:         $width = 120+$NumBars*8;
                   13900:         $xskip = 5;
                   13901:         $bar_width = 4;
                   13902:     }
                   13903:     #
1.137     matthew  13904:     $Max = 1 if ($Max < 1);
                   13905:     if ( int($Max) < $Max ) {
                   13906:         $Max++;
                   13907:         $Max = int($Max);
                   13908:     }
1.127     matthew  13909:     $Title  = '' if (! defined($Title));
                   13910:     $xlabel = '' if (! defined($xlabel));
                   13911:     $ylabel = '' if (! defined($ylabel));
1.369     www      13912:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13913:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13914:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13915:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13916:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13917:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13918:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13919:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13920:     $ValuesHash{$id.'.height'}   = $height;
                   13921:     $ValuesHash{$id.'.width'}    = $width;
                   13922:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13923:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13924:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13925:     #
1.228     matthew  13926:     # Deal with other parameters
                   13927:     while (my ($key,$value) = each(%$extra_settings)) {
                   13928:         $ValuesHash{$id.'.'.$key} = $value;
                   13929:     }
                   13930:     #
1.646     raeburn  13931:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13932:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13933: }
                   13934: 
                   13935: ############################################################
                   13936: ############################################################
                   13937: 
                   13938: =pod
                   13939: 
1.648     raeburn  13940: =item * &DrawXYGraph()
1.137     matthew  13941: 
1.138     matthew  13942: Facilitates the plotting of data in an XY graph.
                   13943: Puts plot definition data into the users environment in order for 
                   13944: graph.png to plot it.  Returns an <img> tag for the plot.
                   13945: 
                   13946: Inputs:
                   13947: 
                   13948: =over 4
                   13949: 
                   13950: =item $Title: string, the title of the plot
                   13951: 
                   13952: =item $xlabel: string, text describing the X-axis of the plot
                   13953: 
                   13954: =item $ylabel: string, text describing the Y-axis of the plot
                   13955: 
                   13956: =item $Max: scalar, the maximum Y value to use in the plot
                   13957: If $Max is < any data point, the graph will not be rendered.
                   13958: 
                   13959: =item $colors: Array ref containing the hex color codes for the data to be 
                   13960: plotted in.  If undefined, default values will be used.
                   13961: 
                   13962: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13963: 
                   13964: =item $Ydata: Array ref containing Array refs.  
1.185     www      13965: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13966: 
                   13967: =item %Values: hash indicating or overriding any default values which are 
                   13968: passed to graph.png.  
                   13969: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13970: 
                   13971: =back
                   13972: 
                   13973: Returns:
                   13974: 
                   13975: An <img> tag which references graph.png and the appropriate identifying
                   13976: information for the plot.
                   13977: 
1.137     matthew  13978: =cut
                   13979: 
                   13980: ############################################################
                   13981: ############################################################
                   13982: sub DrawXYGraph {
                   13983:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13984:     #
                   13985:     # Create the identifier for the graph
                   13986:     my $identifier = &get_cgi_id();
                   13987:     my $id = 'cgi.'.$identifier;
                   13988:     #
                   13989:     $Title  = '' if (! defined($Title));
                   13990:     $xlabel = '' if (! defined($xlabel));
                   13991:     $ylabel = '' if (! defined($ylabel));
                   13992:     my %ValuesHash = 
                   13993:         (
1.369     www      13994:          $id.'.title'  => &escape($Title),
                   13995:          $id.'.xlabel' => &escape($xlabel),
                   13996:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13997:          $id.'.y_max_value'=> $Max,
                   13998:          $id.'.labels'     => join(',',@$Xlabels),
                   13999:          $id.'.PlotType'   => 'XY',
                   14000:          );
                   14001:     #
                   14002:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14003:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14004:     }
                   14005:     #
                   14006:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14007:         return '';
                   14008:     }
                   14009:     my $NumSets=1;
1.138     matthew  14010:     foreach my $array (@{$Ydata}){
1.137     matthew  14011:         next if (! ref($array));
                   14012:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14013:     }
1.138     matthew  14014:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14015:     #
                   14016:     # Deal with other parameters
                   14017:     while (my ($key,$value) = each(%Values)) {
                   14018:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14019:     }
                   14020:     #
1.646     raeburn  14021:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14022:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14023: }
                   14024: 
                   14025: ############################################################
                   14026: ############################################################
                   14027: 
                   14028: =pod
                   14029: 
1.648     raeburn  14030: =item * &DrawXYYGraph()
1.138     matthew  14031: 
                   14032: Facilitates the plotting of data in an XY graph with two Y axes.
                   14033: Puts plot definition data into the users environment in order for 
                   14034: graph.png to plot it.  Returns an <img> tag for the plot.
                   14035: 
                   14036: Inputs:
                   14037: 
                   14038: =over 4
                   14039: 
                   14040: =item $Title: string, the title of the plot
                   14041: 
                   14042: =item $xlabel: string, text describing the X-axis of the plot
                   14043: 
                   14044: =item $ylabel: string, text describing the Y-axis of the plot
                   14045: 
                   14046: =item $colors: Array ref containing the hex color codes for the data to be 
                   14047: plotted in.  If undefined, default values will be used.
                   14048: 
                   14049: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14050: 
                   14051: =item $Ydata1: The first data set
                   14052: 
                   14053: =item $Min1: The minimum value of the left Y-axis
                   14054: 
                   14055: =item $Max1: The maximum value of the left Y-axis
                   14056: 
                   14057: =item $Ydata2: The second data set
                   14058: 
                   14059: =item $Min2: The minimum value of the right Y-axis
                   14060: 
                   14061: =item $Max2: The maximum value of the left Y-axis
                   14062: 
                   14063: =item %Values: hash indicating or overriding any default values which are 
                   14064: passed to graph.png.  
                   14065: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14066: 
                   14067: =back
                   14068: 
                   14069: Returns:
                   14070: 
                   14071: An <img> tag which references graph.png and the appropriate identifying
                   14072: information for the plot.
1.136     matthew  14073: 
                   14074: =cut
                   14075: 
                   14076: ############################################################
                   14077: ############################################################
1.137     matthew  14078: sub DrawXYYGraph {
                   14079:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14080:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14081:     #
                   14082:     # Create the identifier for the graph
                   14083:     my $identifier = &get_cgi_id();
                   14084:     my $id = 'cgi.'.$identifier;
                   14085:     #
                   14086:     $Title  = '' if (! defined($Title));
                   14087:     $xlabel = '' if (! defined($xlabel));
                   14088:     $ylabel = '' if (! defined($ylabel));
                   14089:     my %ValuesHash = 
                   14090:         (
1.369     www      14091:          $id.'.title'  => &escape($Title),
                   14092:          $id.'.xlabel' => &escape($xlabel),
                   14093:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14094:          $id.'.labels' => join(',',@$Xlabels),
                   14095:          $id.'.PlotType' => 'XY',
                   14096:          $id.'.NumSets' => 2,
1.137     matthew  14097:          $id.'.two_axes' => 1,
                   14098:          $id.'.y1_max_value' => $Max1,
                   14099:          $id.'.y1_min_value' => $Min1,
                   14100:          $id.'.y2_max_value' => $Max2,
                   14101:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14102:          );
                   14103:     #
1.137     matthew  14104:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14105:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14106:     }
                   14107:     #
                   14108:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14109:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14110:         return '';
                   14111:     }
                   14112:     my $NumSets=1;
1.137     matthew  14113:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14114:         next if (! ref($array));
                   14115:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14116:     }
                   14117:     #
                   14118:     # Deal with other parameters
                   14119:     while (my ($key,$value) = each(%Values)) {
                   14120:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14121:     }
                   14122:     #
1.646     raeburn  14123:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14124:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14125: }
                   14126: 
                   14127: ############################################################
                   14128: ############################################################
                   14129: 
                   14130: =pod
                   14131: 
1.157     matthew  14132: =back 
                   14133: 
1.139     matthew  14134: =head1 Statistics helper routines?  
                   14135: 
                   14136: Bad place for them but what the hell.
                   14137: 
1.157     matthew  14138: =over 4
                   14139: 
1.648     raeburn  14140: =item * &chartlink()
1.139     matthew  14141: 
                   14142: Returns a link to the chart for a specific student.  
                   14143: 
                   14144: Inputs:
                   14145: 
                   14146: =over 4
                   14147: 
                   14148: =item $linktext: The text of the link
                   14149: 
                   14150: =item $sname: The students username
                   14151: 
                   14152: =item $sdomain: The students domain
                   14153: 
                   14154: =back
                   14155: 
1.157     matthew  14156: =back
                   14157: 
1.139     matthew  14158: =cut
                   14159: 
                   14160: ############################################################
                   14161: ############################################################
                   14162: sub chartlink {
                   14163:     my ($linktext, $sname, $sdomain) = @_;
                   14164:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14165:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14166:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14167:        '">'.$linktext.'</a>';
1.153     matthew  14168: }
                   14169: 
                   14170: #######################################################
                   14171: #######################################################
                   14172: 
                   14173: =pod
                   14174: 
                   14175: =head1 Course Environment Routines
1.157     matthew  14176: 
                   14177: =over 4
1.153     matthew  14178: 
1.648     raeburn  14179: =item * &restore_course_settings()
1.153     matthew  14180: 
1.648     raeburn  14181: =item * &store_course_settings()
1.153     matthew  14182: 
                   14183: Restores/Store indicated form parameters from the course environment.
                   14184: Will not overwrite existing values of the form parameters.
                   14185: 
                   14186: Inputs: 
                   14187: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14188: 
                   14189: a hash ref describing the data to be stored.  For example:
                   14190:    
                   14191: %Save_Parameters = ('Status' => 'scalar',
                   14192:     'chartoutputmode' => 'scalar',
                   14193:     'chartoutputdata' => 'scalar',
                   14194:     'Section' => 'array',
1.373     raeburn  14195:     'Group' => 'array',
1.153     matthew  14196:     'StudentData' => 'array',
                   14197:     'Maps' => 'array');
                   14198: 
                   14199: Returns: both routines return nothing
                   14200: 
1.631     raeburn  14201: =back
                   14202: 
1.153     matthew  14203: =cut
                   14204: 
                   14205: #######################################################
                   14206: #######################################################
                   14207: sub store_course_settings {
1.496     albertel 14208:     return &store_settings($env{'request.course.id'},@_);
                   14209: }
                   14210: 
                   14211: sub store_settings {
1.153     matthew  14212:     # save to the environment
                   14213:     # appenv the same items, just to be safe
1.300     albertel 14214:     my $udom  = $env{'user.domain'};
                   14215:     my $uname = $env{'user.name'};
1.496     albertel 14216:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14217:     my %SaveHash;
                   14218:     my %AppHash;
                   14219:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14220:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14221:         my $envname = 'environment.'.$basename;
1.258     albertel 14222:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14223:             # Save this value away
                   14224:             if ($type eq 'scalar' &&
1.258     albertel 14225:                 (! exists($env{$envname}) || 
                   14226:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14227:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14228:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14229:             } elsif ($type eq 'array') {
                   14230:                 my $stored_form;
1.258     albertel 14231:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14232:                     $stored_form = join(',',
                   14233:                                         map {
1.369     www      14234:                                             &escape($_);
1.258     albertel 14235:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14236:                 } else {
                   14237:                     $stored_form = 
1.369     www      14238:                         &escape($env{'form.'.$setting});
1.153     matthew  14239:                 }
                   14240:                 # Determine if the array contents are the same.
1.258     albertel 14241:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14242:                     $SaveHash{$basename} = $stored_form;
                   14243:                     $AppHash{$envname}   = $stored_form;
                   14244:                 }
                   14245:             }
                   14246:         }
                   14247:     }
                   14248:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14249:                                           $udom,$uname);
1.153     matthew  14250:     if ($put_result !~ /^(ok|delayed)/) {
                   14251:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14252:                                  'got error:'.$put_result);
                   14253:     }
                   14254:     # Make sure these settings stick around in this session, too
1.646     raeburn  14255:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14256:     return;
                   14257: }
                   14258: 
                   14259: sub restore_course_settings {
1.499     albertel 14260:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14261: }
                   14262: 
                   14263: sub restore_settings {
                   14264:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14265:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14266:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14267:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14268:             '.'.$setting;
1.258     albertel 14269:         if (exists($env{$envname})) {
1.153     matthew  14270:             if ($type eq 'scalar') {
1.258     albertel 14271:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14272:             } elsif ($type eq 'array') {
1.258     albertel 14273:                 $env{'form.'.$setting} = [ 
1.153     matthew  14274:                                            map { 
1.369     www      14275:                                                &unescape($_); 
1.258     albertel 14276:                                            } split(',',$env{$envname})
1.153     matthew  14277:                                            ];
                   14278:             }
                   14279:         }
                   14280:     }
1.127     matthew  14281: }
                   14282: 
1.618     raeburn  14283: #######################################################
                   14284: #######################################################
                   14285: 
                   14286: =pod
                   14287: 
                   14288: =head1 Domain E-mail Routines  
                   14289: 
                   14290: =over 4
                   14291: 
1.648     raeburn  14292: =item * &build_recipient_list()
1.618     raeburn  14293: 
1.1075.2.44  raeburn  14294: Build recipient lists for following types of e-mail:
1.766     raeburn  14295: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14296: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14297: module change checking, student/employee ID conflict checks, as
                   14298: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14299: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14300: 
                   14301: Inputs:
1.1075.2.44  raeburn  14302: defmail (scalar - email address of default recipient),
                   14303: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14304: requestsmail, updatesmail, or idconflictsmail).
                   14305: 
1.619     raeburn  14306: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14307: 
                   14308: origmail (scalar - email address of recipient from loncapa.conf,
                   14309: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14310: 
1.1075.2.139  raeburn  14311: $requname username of requester (if mailing type is helpdeskmail)
                   14312: 
                   14313: $requdom domain of requester (if mailing type is helpdeskmail)
                   14314: 
                   14315: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14316: 
1.655     raeburn  14317: Returns: comma separated list of addresses to which to send e-mail.
                   14318: 
                   14319: =back
1.618     raeburn  14320: 
                   14321: =cut
                   14322: 
                   14323: ############################################################
                   14324: ############################################################
                   14325: sub build_recipient_list {
1.1075.2.139  raeburn  14326:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14327:     my @recipients;
1.1075.2.122  raeburn  14328:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14329:     my %domconfig =
1.1075.2.122  raeburn  14330:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14331:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14332:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14333:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14334:                 my @contacts = ('adminemail','supportemail');
                   14335:                 foreach my $item (@contacts) {
                   14336:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14337:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14338:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14339:                             push(@recipients,$addr);
                   14340:                         }
1.619     raeburn  14341:                     }
1.1075.2.122  raeburn  14342:                 }
                   14343:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14344:                 if ($mailing eq 'helpdeskmail') {
                   14345:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14346:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14347:                         my @ok_bccs;
                   14348:                         foreach my $bcc (@bccs) {
                   14349:                             $bcc =~ s/^\s+//g;
                   14350:                             $bcc =~ s/\s+$//g;
                   14351:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14352:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14353:                                     push(@ok_bccs,$bcc);
                   14354:                                 }
                   14355:                             }
                   14356:                         }
                   14357:                         if (@ok_bccs > 0) {
                   14358:                             $allbcc = join(', ',@ok_bccs);
                   14359:                         }
                   14360:                     }
                   14361:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14362:                 }
                   14363:             }
1.766     raeburn  14364:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14365:             $lastresort = $origmail;
1.618     raeburn  14366:         }
1.1075.2.139  raeburn  14367:         if ($mailing eq 'helpdeskmail') {
                   14368:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14369:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14370:                 my ($inststatus,$inststatus_checked);
                   14371:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14372:                     ($env{'user.domain'} ne 'public')) {
                   14373:                     $inststatus_checked = 1;
                   14374:                     $inststatus = $env{'environment.inststatus'};
                   14375:                 }
                   14376:                 unless ($inststatus_checked) {
                   14377:                     if (($requname ne '') && ($requdom ne '')) {
                   14378:                         if (($requname =~ /^$match_username$/) &&
                   14379:                             ($requdom =~ /^$match_domain$/) &&
                   14380:                             (&Apache::lonnet::domain($requdom))) {
                   14381:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14382:                                                                       $requdom);
                   14383:                             unless ($requhome eq 'no_host') {
                   14384:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14385:                                 $inststatus = $userenv{'inststatus'};
                   14386:                                 $inststatus_checked = 1;
                   14387:                             }
                   14388:                         }
                   14389:                     }
                   14390:                 }
                   14391:                 unless ($inststatus_checked) {
                   14392:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14393:                         my %srch = (srchby     => 'email',
                   14394:                                     srchdomain => $defdom,
                   14395:                                     srchterm   => $reqemail,
                   14396:                                     srchtype   => 'exact');
                   14397:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14398:                         foreach my $uname (keys(%srch_results)) {
                   14399:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14400:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14401:                                 $inststatus_checked = 1;
                   14402:                                 last;
                   14403:                             }
                   14404:                         }
                   14405:                         unless ($inststatus_checked) {
                   14406:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14407:                             if ($dirsrchres eq 'ok') {
                   14408:                                 foreach my $uname (keys(%srch_results)) {
                   14409:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14410:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14411:                                         $inststatus_checked = 1;
                   14412:                                         last;
                   14413:                                     }
                   14414:                                 }
                   14415:                             }
                   14416:                         }
                   14417:                     }
                   14418:                 }
                   14419:                 if ($inststatus ne '') {
                   14420:                     foreach my $status (split(/\:/,$inststatus)) {
                   14421:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14422:                             my @contacts = ('adminemail','supportemail');
                   14423:                             foreach my $item (@contacts) {
                   14424:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14425:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14426:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14427:                                         push(@recipients,$addr);
                   14428:                                     }
                   14429:                                 }
                   14430:                             }
                   14431:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14432:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14433:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14434:                                 my @ok_bccs;
                   14435:                                 foreach my $bcc (@bccs) {
                   14436:                                     $bcc =~ s/^\s+//g;
                   14437:                                     $bcc =~ s/\s+$//g;
                   14438:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14439:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14440:                                             push(@ok_bccs,$bcc);
                   14441:                                         }
                   14442:                                     }
                   14443:                                 }
                   14444:                                 if (@ok_bccs > 0) {
                   14445:                                     $allbcc = join(', ',@ok_bccs);
                   14446:                                 }
                   14447:                             }
                   14448:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14449:                             last;
                   14450:                         }
                   14451:                     }
                   14452:                 }
                   14453:             }
                   14454:         }
1.619     raeburn  14455:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14456:         $lastresort = $origmail;
                   14457:     }
1.1075.2.128  raeburn  14458:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14459:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14460:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14461:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14462:             my %what = (
                   14463:                           perlvar => 1,
                   14464:                        );
                   14465:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14466:             if ($primary) {
                   14467:                 my $gotaddr;
                   14468:                 my ($result,$returnhash) =
                   14469:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14470:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14471:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14472:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14473:                         $gotaddr = 1;
                   14474:                     }
                   14475:                 }
                   14476:                 unless ($gotaddr) {
                   14477:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14478:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14479:                     unless ($uintdom eq $intdom) {
                   14480:                         my %domconfig =
                   14481:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14482:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14483:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14484:                                 my @contacts = ('adminemail','supportemail');
                   14485:                                 foreach my $item (@contacts) {
                   14486:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14487:                                         my $addr = $domconfig{'contacts'}{$item};
                   14488:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14489:                                             push(@recipients,$addr);
                   14490:                                         }
                   14491:                                     }
                   14492:                                 }
                   14493:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14494:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14495:                                 }
                   14496:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14497:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14498:                                     my @ok_bccs;
                   14499:                                     foreach my $bcc (@bccs) {
                   14500:                                         $bcc =~ s/^\s+//g;
                   14501:                                         $bcc =~ s/\s+$//g;
                   14502:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14503:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14504:                                                 push(@ok_bccs,$bcc);
                   14505:                                             }
                   14506:                                         }
                   14507:                                     }
                   14508:                                     if (@ok_bccs > 0) {
                   14509:                                         $allbcc = join(', ',@ok_bccs);
                   14510:                                     }
                   14511:                                 }
                   14512:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14513:                             }
                   14514:                         }
                   14515:                     }
                   14516:                 }
                   14517:             }
                   14518:         }
1.618     raeburn  14519:     }
1.688     raeburn  14520:     if (defined($defmail)) {
                   14521:         if ($defmail ne '') {
                   14522:             push(@recipients,$defmail);
                   14523:         }
1.618     raeburn  14524:     }
                   14525:     if ($otheremails) {
1.619     raeburn  14526:         my @others;
                   14527:         if ($otheremails =~ /,/) {
                   14528:             @others = split(/,/,$otheremails);
1.618     raeburn  14529:         } else {
1.619     raeburn  14530:             push(@others,$otheremails);
                   14531:         }
                   14532:         foreach my $addr (@others) {
                   14533:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14534:                 push(@recipients,$addr);
                   14535:             }
1.618     raeburn  14536:         }
                   14537:     }
1.1075.2.128  raeburn  14538:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14539:         if ((!@recipients) && ($lastresort ne '')) {
                   14540:             push(@recipients,$lastresort);
                   14541:         }
                   14542:     } elsif ($lastresort ne '') {
                   14543:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14544:             push(@recipients,$lastresort);
                   14545:         }
                   14546:     }
                   14547:     my $recipientlist = join(',',@recipients);
                   14548:     if (wantarray) {
                   14549:         return ($recipientlist,$allbcc,$addtext);
                   14550:     } else {
                   14551:         return $recipientlist;
                   14552:     }
1.618     raeburn  14553: }
                   14554: 
1.127     matthew  14555: ############################################################
                   14556: ############################################################
1.154     albertel 14557: 
1.655     raeburn  14558: =pod
                   14559: 
                   14560: =head1 Course Catalog Routines
                   14561: 
                   14562: =over 4
                   14563: 
                   14564: =item * &gather_categories()
                   14565: 
                   14566: Converts category definitions - keys of categories hash stored in  
                   14567: coursecategories in configuration.db on the primary library server in a 
                   14568: domain - to an array.  Also generates javascript and idx hash used to 
                   14569: generate Domain Coordinator interface for editing Course Categories.
                   14570: 
                   14571: Inputs:
1.663     raeburn  14572: 
1.655     raeburn  14573: categories (reference to hash of category definitions).
1.663     raeburn  14574: 
1.655     raeburn  14575: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14576:       categories and subcategories).
1.663     raeburn  14577: 
1.655     raeburn  14578: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14579:       editing Course Categories).
1.663     raeburn  14580: 
1.655     raeburn  14581: jsarray (reference to array of categories used to create Javascript arrays for
                   14582:          Domain Coordinator interface for editing Course Categories).
                   14583: 
                   14584: Returns: nothing
                   14585: 
                   14586: Side effects: populates cats, idx and jsarray. 
                   14587: 
                   14588: =cut
                   14589: 
                   14590: sub gather_categories {
                   14591:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14592:     my %counters;
                   14593:     my $num = 0;
                   14594:     foreach my $item (keys(%{$categories})) {
                   14595:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14596:         if ($container eq '' && $depth == 0) {
                   14597:             $cats->[$depth][$categories->{$item}] = $cat;
                   14598:         } else {
                   14599:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14600:         }
                   14601:         my ($escitem,$tail) = split(/:/,$item,2);
                   14602:         if ($counters{$tail} eq '') {
                   14603:             $counters{$tail} = $num;
                   14604:             $num ++;
                   14605:         }
                   14606:         if (ref($idx) eq 'HASH') {
                   14607:             $idx->{$item} = $counters{$tail};
                   14608:         }
                   14609:         if (ref($jsarray) eq 'ARRAY') {
                   14610:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14611:         }
                   14612:     }
                   14613:     return;
                   14614: }
                   14615: 
                   14616: =pod
                   14617: 
                   14618: =item * &extract_categories()
                   14619: 
                   14620: Used to generate breadcrumb trails for course categories.
                   14621: 
                   14622: Inputs:
1.663     raeburn  14623: 
1.655     raeburn  14624: categories (reference to hash of category definitions).
1.663     raeburn  14625: 
1.655     raeburn  14626: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14627:       categories and subcategories).
1.663     raeburn  14628: 
1.655     raeburn  14629: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14630: 
1.655     raeburn  14631: allitems (reference to hash - key is category key 
                   14632:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14633: 
1.655     raeburn  14634: idx (reference to hash of counters used in Domain Coordinator interface for
                   14635:       editing Course Categories).
1.663     raeburn  14636: 
1.655     raeburn  14637: jsarray (reference to array of categories used to create Javascript arrays for
                   14638:          Domain Coordinator interface for editing Course Categories).
                   14639: 
1.665     raeburn  14640: subcats (reference to hash of arrays containing all subcategories within each 
                   14641:          category, -recursive)
                   14642: 
1.1075.2.132  raeburn  14643: maxd (reference to hash used to hold max depth for all top-level categories).
                   14644: 
1.655     raeburn  14645: Returns: nothing
                   14646: 
                   14647: Side effects: populates trails and allitems hash references.
                   14648: 
                   14649: =cut
                   14650: 
                   14651: sub extract_categories {
1.1075.2.132  raeburn  14652:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14653:     if (ref($categories) eq 'HASH') {
                   14654:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14655:         if (ref($cats->[0]) eq 'ARRAY') {
                   14656:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14657:                 my $name = $cats->[0][$i];
                   14658:                 my $item = &escape($name).'::0';
                   14659:                 my $trailstr;
                   14660:                 if ($name eq 'instcode') {
                   14661:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14662:                 } elsif ($name eq 'communities') {
                   14663:                     $trailstr = &mt('Communities');
1.655     raeburn  14664:                 } else {
                   14665:                     $trailstr = $name;
                   14666:                 }
                   14667:                 if ($allitems->{$item} eq '') {
                   14668:                     push(@{$trails},$trailstr);
                   14669:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14670:                 }
                   14671:                 my @parents = ($name);
                   14672:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14673:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14674:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14675:                         if (ref($subcats) eq 'HASH') {
                   14676:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14677:                         }
1.1075.2.132  raeburn  14678:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14679:                     }
                   14680:                 } else {
                   14681:                     if (ref($subcats) eq 'HASH') {
                   14682:                         $subcats->{$item} = [];
1.655     raeburn  14683:                     }
1.1075.2.132  raeburn  14684:                     if (ref($maxd) eq 'HASH') {
                   14685:                         $maxd->{$name} = 1;
                   14686:                     }
1.655     raeburn  14687:                 }
                   14688:             }
                   14689:         }
                   14690:     }
                   14691:     return;
                   14692: }
                   14693: 
                   14694: =pod
                   14695: 
1.1075.2.56  raeburn  14696: =item * &recurse_categories()
1.655     raeburn  14697: 
                   14698: Recursively used to generate breadcrumb trails for course categories.
                   14699: 
                   14700: Inputs:
1.663     raeburn  14701: 
1.655     raeburn  14702: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14703:       categories and subcategories).
1.663     raeburn  14704: 
1.655     raeburn  14705: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14706: 
                   14707: category (current course category, for which breadcrumb trail is being generated).
                   14708: 
                   14709: trails (reference to array of breadcrumb trails for each category).
                   14710: 
1.655     raeburn  14711: allitems (reference to hash - key is category key
                   14712:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14713: 
1.655     raeburn  14714: parents (array containing containers directories for current category, 
                   14715:          back to top level). 
                   14716: 
                   14717: Returns: nothing
                   14718: 
                   14719: Side effects: populates trails and allitems hash references
                   14720: 
                   14721: =cut
                   14722: 
                   14723: sub recurse_categories {
1.1075.2.132  raeburn  14724:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14725:     my $shallower = $depth - 1;
                   14726:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14727:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14728:             my $name = $cats->[$depth]{$category}[$k];
                   14729:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14730:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14731:             if ($allitems->{$item} eq '') {
                   14732:                 push(@{$trails},$trailstr);
                   14733:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14734:             }
                   14735:             my $deeper = $depth+1;
                   14736:             push(@{$parents},$category);
1.665     raeburn  14737:             if (ref($subcats) eq 'HASH') {
                   14738:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14739:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14740:                     my $higher;
                   14741:                     if ($j > 0) {
                   14742:                         $higher = &escape($parents->[$j]).':'.
                   14743:                                   &escape($parents->[$j-1]).':'.$j;
                   14744:                     } else {
                   14745:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14746:                     }
                   14747:                     push(@{$subcats->{$higher}},$subcat);
                   14748:                 }
                   14749:             }
                   14750:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14751:                                 $subcats,$maxd);
1.655     raeburn  14752:             pop(@{$parents});
                   14753:         }
                   14754:     } else {
                   14755:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14756:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14757:         if ($allitems->{$item} eq '') {
                   14758:             push(@{$trails},$trailstr);
                   14759:             $allitems->{$item} = scalar(@{$trails})-1;
                   14760:         }
1.1075.2.132  raeburn  14761:         if (ref($maxd) eq 'HASH') {
                   14762:             if ($depth > $maxd->{$parents->[0]}) {
                   14763:                 $maxd->{$parents->[0]} = $depth;
                   14764:             }
                   14765:         }
1.655     raeburn  14766:     }
                   14767:     return;
                   14768: }
                   14769: 
1.663     raeburn  14770: =pod
                   14771: 
1.1075.2.56  raeburn  14772: =item * &assign_categories_table()
1.663     raeburn  14773: 
                   14774: Create a datatable for display of hierarchical categories in a domain,
                   14775: with checkboxes to allow a course to be categorized. 
                   14776: 
                   14777: Inputs:
                   14778: 
                   14779: cathash - reference to hash of categories defined for the domain (from
                   14780:           configuration.db)
                   14781: 
                   14782: currcat - scalar with an & separated list of categories assigned to a course. 
                   14783: 
1.919     raeburn  14784: type    - scalar contains course type (Course or Community).
                   14785: 
1.1075.2.117  raeburn  14786: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14787:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14788: 
1.663     raeburn  14789: Returns: $output (markup to be displayed) 
                   14790: 
                   14791: =cut
                   14792: 
                   14793: sub assign_categories_table {
1.1075.2.117  raeburn  14794:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14795:     my $output;
                   14796:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14797:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14798:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14799:         $maxdepth = scalar(@cats);
                   14800:         if (@cats > 0) {
                   14801:             my $itemcount = 0;
                   14802:             if (ref($cats[0]) eq 'ARRAY') {
                   14803:                 my @currcategories;
                   14804:                 if ($currcat ne '') {
                   14805:                     @currcategories = split('&',$currcat);
                   14806:                 }
1.919     raeburn  14807:                 my $table;
1.663     raeburn  14808:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14809:                     my $parent = $cats[0][$i];
1.919     raeburn  14810:                     next if ($parent eq 'instcode');
                   14811:                     if ($type eq 'Community') {
                   14812:                         next unless ($parent eq 'communities');
                   14813:                     } else {
                   14814:                         next if ($parent eq 'communities');
                   14815:                     }
1.663     raeburn  14816:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14817:                     my $item = &escape($parent).'::0';
                   14818:                     my $checked = '';
                   14819:                     if (@currcategories > 0) {
                   14820:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14821:                             $checked = ' checked="checked"';
1.663     raeburn  14822:                         }
                   14823:                     }
1.919     raeburn  14824:                     my $parent_title = $parent;
                   14825:                     if ($parent eq 'communities') {
                   14826:                         $parent_title = &mt('Communities');
                   14827:                     }
                   14828:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14829:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14830:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14831:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14832:                     my $depth = 1;
                   14833:                     push(@path,$parent);
1.1075.2.117  raeburn  14834:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14835:                     pop(@path);
1.919     raeburn  14836:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14837:                     $itemcount ++;
                   14838:                 }
1.919     raeburn  14839:                 if ($itemcount) {
                   14840:                     $output = &Apache::loncommon::start_data_table().
                   14841:                               $table.
                   14842:                               &Apache::loncommon::end_data_table();
                   14843:                 }
1.663     raeburn  14844:             }
                   14845:         }
                   14846:     }
                   14847:     return $output;
                   14848: }
                   14849: 
                   14850: =pod
                   14851: 
1.1075.2.56  raeburn  14852: =item * &assign_category_rows()
1.663     raeburn  14853: 
                   14854: Create a datatable row for display of nested categories in a domain,
                   14855: with checkboxes to allow a course to be categorized,called recursively.
                   14856: 
                   14857: Inputs:
                   14858: 
                   14859: itemcount - track row number for alternating colors
                   14860: 
                   14861: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14862:       categories and subcategories.
                   14863: 
                   14864: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14865: 
                   14866: parent - parent of current category item
                   14867: 
                   14868: path - Array containing all categories back up through the hierarchy from the
                   14869:        current category to the top level.
                   14870: 
                   14871: currcategories - reference to array of current categories assigned to the course
                   14872: 
1.1075.2.117  raeburn  14873: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14874:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14875: 
1.663     raeburn  14876: Returns: $output (markup to be displayed).
                   14877: 
                   14878: =cut
                   14879: 
                   14880: sub assign_category_rows {
1.1075.2.117  raeburn  14881:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14882:     my ($text,$name,$item,$chgstr);
                   14883:     if (ref($cats) eq 'ARRAY') {
                   14884:         my $maxdepth = scalar(@{$cats});
                   14885:         if (ref($cats->[$depth]) eq 'HASH') {
                   14886:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14887:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14888:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14889:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14890:                 for (my $j=0; $j<$numchildren; $j++) {
                   14891:                     $name = $cats->[$depth]{$parent}[$j];
                   14892:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14893:                     my $deeper = $depth+1;
                   14894:                     my $checked = '';
                   14895:                     if (ref($currcategories) eq 'ARRAY') {
                   14896:                         if (@{$currcategories} > 0) {
                   14897:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14898:                                 $checked = ' checked="checked"';
1.663     raeburn  14899:                             }
                   14900:                         }
                   14901:                     }
1.664     raeburn  14902:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14903:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14904:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14905:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14906:                              '</td><td>';
1.663     raeburn  14907:                     if (ref($path) eq 'ARRAY') {
                   14908:                         push(@{$path},$name);
1.1075.2.117  raeburn  14909:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14910:                         pop(@{$path});
                   14911:                     }
                   14912:                     $text .= '</td></tr>';
                   14913:                 }
                   14914:                 $text .= '</table></td>';
                   14915:             }
                   14916:         }
                   14917:     }
                   14918:     return $text;
                   14919: }
                   14920: 
1.1075.2.69  raeburn  14921: =pod
                   14922: 
                   14923: =back
                   14924: 
                   14925: =cut
                   14926: 
1.655     raeburn  14927: ############################################################
                   14928: ############################################################
                   14929: 
                   14930: 
1.443     albertel 14931: sub commit_customrole {
1.664     raeburn  14932:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14933:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14934:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14935:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14936:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14937:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14938:                  '</b><br />';
                   14939:     return $output;
                   14940: }
                   14941: 
                   14942: sub commit_standardrole {
1.1075.2.31  raeburn  14943:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14944:     my ($output,$logmsg,$linefeed);
                   14945:     if ($context eq 'auto') {
                   14946:         $linefeed = "\n";
                   14947:     } else {
                   14948:         $linefeed = "<br />\n";
                   14949:     }  
1.443     albertel 14950:     if ($three eq 'st') {
1.541     raeburn  14951:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14952:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14953:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14954:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14955:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14956:         } else {
1.541     raeburn  14957:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14958:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14959:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14960:             if ($context eq 'auto') {
                   14961:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14962:             } else {
                   14963:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14964:                &mt('Add to classlist').': <b>ok</b>';
                   14965:             }
                   14966:             $output .= $linefeed;
1.443     albertel 14967:         }
                   14968:     } else {
                   14969:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14970:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14971:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14972:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14973:         if ($context eq 'auto') {
                   14974:             $output .= $result.$linefeed;
                   14975:         } else {
                   14976:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14977:         }
1.443     albertel 14978:     }
                   14979:     return $output;
                   14980: }
                   14981: 
                   14982: sub commit_studentrole {
1.1075.2.31  raeburn  14983:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14984:         $credits) = @_;
1.626     raeburn  14985:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14986:     if ($context eq 'auto') {
                   14987:         $linefeed = "\n";
                   14988:     } else {
                   14989:         $linefeed = '<br />'."\n";
                   14990:     }
1.443     albertel 14991:     if (defined($one) && defined($two)) {
                   14992:         my $cid=$one.'_'.$two;
                   14993:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14994:         my $secchange = 0;
                   14995:         my $expire_role_result;
                   14996:         my $modify_section_result;
1.628     raeburn  14997:         if ($oldsec ne '-1') { 
                   14998:             if ($oldsec ne $sec) {
1.443     albertel 14999:                 $secchange = 1;
1.628     raeburn  15000:                 my $now = time;
1.443     albertel 15001:                 my $uurl='/'.$cid;
                   15002:                 $uurl=~s/\_/\//g;
                   15003:                 if ($oldsec) {
                   15004:                     $uurl.='/'.$oldsec;
                   15005:                 }
1.626     raeburn  15006:                 $oldsecurl = $uurl;
1.628     raeburn  15007:                 $expire_role_result = 
1.652     raeburn  15008:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15009:                 if ($env{'request.course.sec'} ne '') { 
                   15010:                     if ($expire_role_result eq 'refused') {
                   15011:                         my @roles = ('st');
                   15012:                         my @statuses = ('previous');
                   15013:                         my @roledoms = ($one);
                   15014:                         my $withsec = 1;
                   15015:                         my %roleshash = 
                   15016:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15017:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15018:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15019:                             my ($oldstart,$oldend) = 
                   15020:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15021:                             if ($oldend > 0 && $oldend <= $now) {
                   15022:                                 $expire_role_result = 'ok';
                   15023:                             }
                   15024:                         }
                   15025:                     }
                   15026:                 }
1.443     albertel 15027:                 $result = $expire_role_result;
                   15028:             }
                   15029:         }
                   15030:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15031:             $modify_section_result = 
                   15032:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15033:                                                            undef,undef,undef,$sec,
                   15034:                                                            $end,$start,'','',$cid,
                   15035:                                                            '',$context,$credits);
1.443     albertel 15036:             if ($modify_section_result =~ /^ok/) {
                   15037:                 if ($secchange == 1) {
1.628     raeburn  15038:                     if ($sec eq '') {
                   15039:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15040:                     } else {
                   15041:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15042:                     }
1.443     albertel 15043:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15044:                     if ($sec eq '') {
                   15045:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15046:                     } else {
                   15047:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15048:                     }
1.443     albertel 15049:                 } else {
1.628     raeburn  15050:                     if ($sec eq '') {
                   15051:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15052:                     } else {
                   15053:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15054:                     }
1.443     albertel 15055:                 }
                   15056:             } else {
1.628     raeburn  15057:                 if ($secchange) {       
                   15058:                     $$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;
                   15059:                 } else {
                   15060:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15061:                 }
1.443     albertel 15062:             }
                   15063:             $result = $modify_section_result;
                   15064:         } elsif ($secchange == 1) {
1.628     raeburn  15065:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15066:                 $$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  15067:             } else {
                   15068:                 $$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;
                   15069:             }
1.626     raeburn  15070:             if ($expire_role_result eq 'refused') {
                   15071:                 my $newsecurl = '/'.$cid;
                   15072:                 $newsecurl =~ s/\_/\//g;
                   15073:                 if ($sec ne '') {
                   15074:                     $newsecurl.='/'.$sec;
                   15075:                 }
                   15076:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15077:                     if ($sec eq '') {
                   15078:                         $$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;
                   15079:                     } else {
                   15080:                         $$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;
                   15081:                     }
                   15082:                 }
                   15083:             }
1.443     albertel 15084:         }
                   15085:     } else {
1.626     raeburn  15086:         $$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 15087:         $result = "error: incomplete course id\n";
                   15088:     }
                   15089:     return $result;
                   15090: }
                   15091: 
1.1075.2.25  raeburn  15092: sub show_role_extent {
                   15093:     my ($scope,$context,$role) = @_;
                   15094:     $scope =~ s{^/}{};
                   15095:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15096:     push(@courseroles,'co');
                   15097:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15098:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15099:         $scope =~ s{/}{_};
                   15100:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15101:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15102:         my ($audom,$auname) = split(/\//,$scope);
                   15103:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15104:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15105:     } else {
                   15106:         $scope =~ s{/$}{};
                   15107:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15108:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15109:     }
                   15110: }
                   15111: 
1.443     albertel 15112: ############################################################
                   15113: ############################################################
                   15114: 
1.566     albertel 15115: sub check_clone {
1.578     raeburn  15116:     my ($args,$linefeed) = @_;
1.566     albertel 15117:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15118:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15119:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15120:     my $clonemsg;
                   15121:     my $can_clone = 0;
1.944     raeburn  15122:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15123:     if ($lctype ne 'community') {
                   15124:         $lctype = 'course';
                   15125:     }
1.566     albertel 15126:     if ($clonehome eq 'no_host') {
1.944     raeburn  15127:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15128:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15129:         } else {
                   15130:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15131:         }     
1.566     albertel 15132:     } else {
                   15133: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15134:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15135:             if ($clonedesc{'type'} ne 'Community') {
                   15136:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15137:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15138:             }
                   15139:         }
1.1075.2.119  raeburn  15140: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15141:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15142: 	    $can_clone = 1;
                   15143: 	} else {
1.1075.2.95  raeburn  15144: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15145: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15146:             if ($clonehash{'cloners'} eq '') {
                   15147:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15148:                 if ($domdefs{'canclone'}) {
                   15149:                     unless ($domdefs{'canclone'} eq 'none') {
                   15150:                         if ($domdefs{'canclone'} eq 'domain') {
                   15151:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15152:                                 $can_clone = 1;
                   15153:                             }
                   15154:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15155:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15156:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15157:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15158:                                 $can_clone = 1;
                   15159:                             }
                   15160:                         }
                   15161:                     }
1.908     raeburn  15162:                 }
1.1075.2.95  raeburn  15163:             } else {
                   15164: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15165:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15166:                     $can_clone = 1;
1.1075.2.95  raeburn  15167:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15168:                     $can_clone = 1;
1.1075.2.96  raeburn  15169:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15170:                     $can_clone = 1;
1.1075.2.95  raeburn  15171:                 }
                   15172:                 unless ($can_clone) {
1.1075.2.96  raeburn  15173:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15174:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15175:                         my (%gotdomdefaults,%gotcodedefaults);
                   15176:                         foreach my $cloner (@cloners) {
                   15177:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15178:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15179:                                 my (%codedefaults,@code_order);
                   15180:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15181:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15182:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15183:                                     }
                   15184:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15185:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15186:                                     }
                   15187:                                 } else {
                   15188:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15189:                                                                             \%codedefaults,
                   15190:                                                                             \@code_order);
                   15191:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15192:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15193:                                 }
                   15194:                                 if (@code_order > 0) {
                   15195:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15196:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15197:                                                                                 $args->{'crscode'})) {
                   15198:                                         $can_clone = 1;
                   15199:                                         last;
                   15200:                                     }
                   15201:                                 }
                   15202:                             }
                   15203:                         }
                   15204:                     }
1.1075.2.96  raeburn  15205:                 }
                   15206:             }
                   15207:             unless ($can_clone) {
                   15208:                 my $ccrole = 'cc';
                   15209:                 if ($args->{'crstype'} eq 'Community') {
                   15210:                     $ccrole = 'co';
                   15211:                 }
                   15212:                 my %roleshash =
                   15213:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15214:                                                   $args->{'ccdomain'},
                   15215:                                                   'userroles',['active'],[$ccrole],
                   15216:                                                   [$args->{'clonedomain'}]);
                   15217:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15218:                     $can_clone = 1;
                   15219:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15220:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15221:                     $can_clone = 1;
1.1075.2.95  raeburn  15222:                 }
                   15223:             }
                   15224:             unless ($can_clone) {
                   15225:                 if ($args->{'crstype'} eq 'Community') {
                   15226:                     $clonemsg = &mt('No new community created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   15227:                 } else {
                   15228:                     $clonemsg = &mt('No new course created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
1.578     raeburn  15229: 	        }
1.566     albertel 15230: 	    }
1.578     raeburn  15231:         }
1.566     albertel 15232:     }
                   15233:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15234: }
                   15235: 
1.444     albertel 15236: sub construct_course {
1.1075.2.119  raeburn  15237:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15238:         $cnum,$category,$coderef) = @_;
1.444     albertel 15239:     my $outcome;
1.541     raeburn  15240:     my $linefeed =  '<br />'."\n";
                   15241:     if ($context eq 'auto') {
                   15242:         $linefeed = "\n";
                   15243:     }
1.566     albertel 15244: 
                   15245: #
                   15246: # Are we cloning?
                   15247: #
                   15248:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15249:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15250: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15251: 	if ($context ne 'auto') {
1.578     raeburn  15252:             if ($clonemsg ne '') {
                   15253: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15254:             }
1.566     albertel 15255: 	}
                   15256: 	$outcome .= $clonemsg.$linefeed;
                   15257: 
                   15258:         if (!$can_clone) {
                   15259: 	    return (0,$outcome);
                   15260: 	}
                   15261:     }
                   15262: 
1.444     albertel 15263: #
                   15264: # Open course
                   15265: #
                   15266:     my $crstype = lc($args->{'crstype'});
                   15267:     my %cenv=();
                   15268:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15269:                                              $args->{'cdescr'},
                   15270:                                              $args->{'curl'},
                   15271:                                              $args->{'course_home'},
                   15272:                                              $args->{'nonstandard'},
                   15273:                                              $args->{'crscode'},
                   15274:                                              $args->{'ccuname'}.':'.
                   15275:                                              $args->{'ccdomain'},
1.882     raeburn  15276:                                              $args->{'crstype'},
1.885     raeburn  15277:                                              $cnum,$context,$category);
1.444     albertel 15278: 
                   15279:     # Note: The testing routines depend on this being output; see 
                   15280:     # Utils::Course. This needs to at least be output as a comment
                   15281:     # if anyone ever decides to not show this, and Utils::Course::new
                   15282:     # will need to be suitably modified.
1.541     raeburn  15283:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  15284:     if ($$courseid =~ /^error:/) {
                   15285:         return (0,$outcome);
                   15286:     }
                   15287: 
1.444     albertel 15288: #
                   15289: # Check if created correctly
                   15290: #
1.479     albertel 15291:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15292:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15293:     if ($crsuhome eq 'no_host') {
                   15294:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15295:         return (0,$outcome);
                   15296:     }
1.541     raeburn  15297:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15298: 
1.444     albertel 15299: #
1.566     albertel 15300: # Do the cloning
                   15301: #   
                   15302:     if ($can_clone && $cloneid) {
                   15303: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   15304: 	if ($context ne 'auto') {
                   15305: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15306: 	}
                   15307: 	$outcome .= $clonemsg.$linefeed;
                   15308: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15309: # Copy all files
1.637     www      15310: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15311: # Restore URL
1.566     albertel 15312: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15313: # Restore title
1.566     albertel 15314: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15315: # Restore creation date, creator and creation context.
                   15316:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15317:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15318:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15319: # Mark as cloned
1.566     albertel 15320: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15321: # Need to clone grading mode
                   15322:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15323:         $cenv{'grading'}=$newenv{'grading'};
                   15324: # Do not clone these environment entries
                   15325:         &Apache::lonnet::del('environment',
                   15326:                   ['default_enrollment_start_date',
                   15327:                    'default_enrollment_end_date',
                   15328:                    'question.email',
                   15329:                    'policy.email',
                   15330:                    'comment.email',
                   15331:                    'pch.users.denied',
1.725     raeburn  15332:                    'plc.users.denied',
                   15333:                    'hidefromcat',
1.1075.2.36  raeburn  15334:                    'checkforpriv',
1.1075.2.59  raeburn  15335:                    'categories',
                   15336:                    'internal.uniquecode'],
1.638     www      15337:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15338:         if ($args->{'textbook'}) {
                   15339:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15340:         }
1.444     albertel 15341:     }
1.566     albertel 15342: 
1.444     albertel 15343: #
                   15344: # Set environment (will override cloned, if existing)
                   15345: #
                   15346:     my @sections = ();
                   15347:     my @xlists = ();
                   15348:     if ($args->{'crstype'}) {
                   15349:         $cenv{'type'}=$args->{'crstype'};
                   15350:     }
                   15351:     if ($args->{'crsid'}) {
                   15352:         $cenv{'courseid'}=$args->{'crsid'};
                   15353:     }
                   15354:     if ($args->{'crscode'}) {
                   15355:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15356:     }
                   15357:     if ($args->{'crsquota'} ne '') {
                   15358:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15359:     } else {
                   15360:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15361:     }
                   15362:     if ($args->{'ccuname'}) {
                   15363:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15364:                                         ':'.$args->{'ccdomain'};
                   15365:     } else {
                   15366:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15367:     }
1.1075.2.31  raeburn  15368:     if ($args->{'defaultcredits'}) {
                   15369:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15370:     }
1.444     albertel 15371:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15372:     if ($args->{'crssections'}) {
                   15373:         $cenv{'internal.sectionnums'} = '';
                   15374:         if ($args->{'crssections'} =~ m/,/) {
                   15375:             @sections = split/,/,$args->{'crssections'};
                   15376:         } else {
                   15377:             $sections[0] = $args->{'crssections'};
                   15378:         }
                   15379:         if (@sections > 0) {
                   15380:             foreach my $item (@sections) {
                   15381:                 my ($sec,$gp) = split/:/,$item;
                   15382:                 my $class = $args->{'crscode'}.$sec;
                   15383:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15384:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15385:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15386:                     push(@badclasses,$class);
1.444     albertel 15387:                 }
                   15388:             }
                   15389:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15390:         }
                   15391:     }
                   15392: # do not hide course coordinator from staff listing, 
                   15393: # even if privileged
                   15394:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15395: # add course coordinator's domain to domains to check for privileged users
                   15396: # if different to course domain
                   15397:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15398:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15399:     }
1.444     albertel 15400: # add crosslistings
                   15401:     if ($args->{'crsxlist'}) {
                   15402:         $cenv{'internal.crosslistings'}='';
                   15403:         if ($args->{'crsxlist'} =~ m/,/) {
                   15404:             @xlists = split/,/,$args->{'crsxlist'};
                   15405:         } else {
                   15406:             $xlists[0] = $args->{'crsxlist'};
                   15407:         }
                   15408:         if (@xlists > 0) {
                   15409:             foreach my $item (@xlists) {
                   15410:                 my ($xl,$gp) = split/:/,$item;
                   15411:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15412:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15413:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15414:                     push(@badclasses,$xl);
1.444     albertel 15415:                 }
                   15416:             }
                   15417:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15418:         }
                   15419:     }
                   15420:     if ($args->{'autoadds'}) {
                   15421:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15422:     }
                   15423:     if ($args->{'autodrops'}) {
                   15424:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15425:     }
                   15426: # check for notification of enrollment changes
                   15427:     my @notified = ();
                   15428:     if ($args->{'notify_owner'}) {
                   15429:         if ($args->{'ccuname'} ne '') {
                   15430:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15431:         }
                   15432:     }
                   15433:     if ($args->{'notify_dc'}) {
                   15434:         if ($uname ne '') { 
1.630     raeburn  15435:             push(@notified,$uname.':'.$udom);
1.444     albertel 15436:         }
                   15437:     }
                   15438:     if (@notified > 0) {
                   15439:         my $notifylist;
                   15440:         if (@notified > 1) {
                   15441:             $notifylist = join(',',@notified);
                   15442:         } else {
                   15443:             $notifylist = $notified[0];
                   15444:         }
                   15445:         $cenv{'internal.notifylist'} = $notifylist;
                   15446:     }
                   15447:     if (@badclasses > 0) {
                   15448:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15449:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15450:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15451:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15452:         );
1.1075.2.119  raeburn  15453:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15454:                            &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  15455:         if ($context eq 'auto') {
                   15456:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15457:         } else {
1.566     albertel 15458:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15459:         }
                   15460:         foreach my $item (@badclasses) {
1.541     raeburn  15461:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15462:                 $outcome .= " - $item\n";
1.541     raeburn  15463:             } else {
1.1075.2.119  raeburn  15464:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15465:             }
1.1075.2.119  raeburn  15466:         }
                   15467:         if ($context eq 'auto') {
                   15468:             $outcome .= $linefeed;
                   15469:         } else {
                   15470:             $outcome .= "</ul><br /><br /></div>\n";
                   15471:         }
1.444     albertel 15472:     }
                   15473:     if ($args->{'no_end_date'}) {
                   15474:         $args->{'endaccess'} = 0;
                   15475:     }
                   15476:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15477:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15478:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15479:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15480:     if ($args->{'showphotos'}) {
                   15481:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15482:     }
                   15483:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15484:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15485:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15486:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15487:             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'); 
                   15488:             if ($context eq 'auto') {
                   15489:                 $outcome .= $krb_msg;
                   15490:             } else {
1.566     albertel 15491:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15492:             }
                   15493:             $outcome .= $linefeed;
1.444     albertel 15494:         }
                   15495:     }
                   15496:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15497:        if ($args->{'setpolicy'}) {
                   15498:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15499:        }
                   15500:        if ($args->{'setcontent'}) {
                   15501:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15502:        }
1.1075.2.110  raeburn  15503:        if ($args->{'setcomment'}) {
                   15504:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15505:        }
1.444     albertel 15506:     }
                   15507:     if ($args->{'reshome'}) {
                   15508: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15509: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15510:     }
                   15511: #
                   15512: # course has keyed access
                   15513: #
                   15514:     if ($args->{'setkeys'}) {
                   15515:        $cenv{'keyaccess'}='yes';
                   15516:     }
                   15517: # if specified, key authority is not course, but user
                   15518: # only active if keyaccess is yes
                   15519:     if ($args->{'keyauth'}) {
1.487     albertel 15520: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15521: 	$user = &LONCAPA::clean_username($user);
                   15522: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15523: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15524: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15525: 	}
                   15526:     }
                   15527: 
1.1075.2.59  raeburn  15528: #
                   15529: #  generate and store uniquecode (available to course requester), if course should have one.
                   15530: #
                   15531:     if ($args->{'uniquecode'}) {
                   15532:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15533:         if ($code) {
                   15534:             $cenv{'internal.uniquecode'} = $code;
                   15535:             my %crsinfo =
                   15536:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15537:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15538:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15539:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15540:             }
                   15541:             if (ref($coderef)) {
                   15542:                 $$coderef = $code;
                   15543:             }
                   15544:         }
                   15545:     }
                   15546: 
1.444     albertel 15547:     if ($args->{'disresdis'}) {
                   15548:         $cenv{'pch.roles.denied'}='st';
                   15549:     }
                   15550:     if ($args->{'disablechat'}) {
                   15551:         $cenv{'plc.roles.denied'}='st';
                   15552:     }
                   15553: 
                   15554:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15555:     # course
                   15556:     $cenv{'course.helper.not.run'} = 1;
                   15557:     #
                   15558:     # Use new Randomseed
                   15559:     #
                   15560:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15561:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15562:     #
                   15563:     # The encryption code and receipt prefix for this course
                   15564:     #
                   15565:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15566:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15567:     #
                   15568:     # By default, use standard grading
                   15569:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15570: 
1.541     raeburn  15571:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15572:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15573: #
                   15574: # Open all assignments
                   15575: #
                   15576:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  15577:        my $opendate = time;
                   15578:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   15579:            $opendate = $args->{'openallfrom'};
                   15580:        }
1.444     albertel 15581:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  15582:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 15583:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  15584:        $outcome .= &mt('All assignments open starting [_1]',
                   15585:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   15586:                    &Apache::lonnet::cput
                   15587:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15588:    }
                   15589: #
                   15590: # Set first page
                   15591: #
                   15592:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15593: 	    || ($cloneid)) {
1.445     albertel 15594: 	use LONCAPA::map;
1.444     albertel 15595: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15596: 
                   15597: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15598:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15599: 
1.444     albertel 15600:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15601:         my $title; my $url;
                   15602:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15603: 	    $title=&mt('Syllabus');
1.444     albertel 15604:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15605:         } else {
1.963     raeburn  15606:             $title=&mt('Table of Contents');
1.444     albertel 15607:             $url='/adm/navmaps';
                   15608:         }
1.445     albertel 15609: 
                   15610:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15611: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15612: 
                   15613: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15614:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15615:     }
1.566     albertel 15616: 
                   15617:     return (1,$outcome);
1.444     albertel 15618: }
                   15619: 
1.1075.2.59  raeburn  15620: sub make_unique_code {
                   15621:     my ($cdom,$cnum) = @_;
                   15622:     # get lock on uniquecodes db
                   15623:     my $lockhash = {
                   15624:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15625:                                                   ':'.$env{'user.domain'},
                   15626:                    };
                   15627:     my $tries = 0;
                   15628:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15629:     my ($code,$error);
                   15630: 
                   15631:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15632:         $tries ++;
                   15633:         sleep 1;
                   15634:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15635:     }
                   15636:     if ($gotlock eq 'ok') {
                   15637:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15638:         my $gotcode;
                   15639:         my $attempts = 0;
                   15640:         while ((!$gotcode) && ($attempts < 100)) {
                   15641:             $code = &generate_code();
                   15642:             if (!exists($currcodes{$code})) {
                   15643:                 $gotcode = 1;
                   15644:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15645:                     $error = 'nostore';
                   15646:                 }
                   15647:             }
                   15648:             $attempts ++;
                   15649:         }
                   15650:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15651:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15652:     } else {
                   15653:         $error = 'nolock';
                   15654:     }
                   15655:     return ($code,$error);
                   15656: }
                   15657: 
                   15658: sub generate_code {
                   15659:     my $code;
                   15660:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15661:     for (my $i=0; $i<6; $i++) {
                   15662:         my $lettnum = int (rand 2);
                   15663:         my $item = '';
                   15664:         if ($lettnum) {
                   15665:             $item = $letts[int( rand(18) )];
                   15666:         } else {
                   15667:             $item = 1+int( rand(8) );
                   15668:         }
                   15669:         $code .= $item;
                   15670:     }
                   15671:     return $code;
                   15672: }
                   15673: 
1.444     albertel 15674: ############################################################
                   15675: ############################################################
                   15676: 
1.953     droeschl 15677: #SD
                   15678: # only Community and Course, or anything else?
1.378     raeburn  15679: sub course_type {
                   15680:     my ($cid) = @_;
                   15681:     if (!defined($cid)) {
                   15682:         $cid = $env{'request.course.id'};
                   15683:     }
1.404     albertel 15684:     if (defined($env{'course.'.$cid.'.type'})) {
                   15685:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15686:     } else {
                   15687:         return 'Course';
1.377     raeburn  15688:     }
                   15689: }
1.156     albertel 15690: 
1.406     raeburn  15691: sub group_term {
                   15692:     my $crstype = &course_type();
                   15693:     my %names = (
                   15694:                   'Course' => 'group',
1.865     raeburn  15695:                   'Community' => 'group',
1.406     raeburn  15696:                 );
                   15697:     return $names{$crstype};
                   15698: }
                   15699: 
1.902     raeburn  15700: sub course_types {
1.1075.2.59  raeburn  15701:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15702:     my %typename = (
                   15703:                          official   => 'Official course',
                   15704:                          unofficial => 'Unofficial course',
                   15705:                          community  => 'Community',
1.1075.2.59  raeburn  15706:                          textbook   => 'Textbook course',
1.902     raeburn  15707:                    );
                   15708:     return (\@types,\%typename);
                   15709: }
                   15710: 
1.156     albertel 15711: sub icon {
                   15712:     my ($file)=@_;
1.505     albertel 15713:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15714:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15715:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15716:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15717: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15718: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15719: 	            $curfext.".gif") {
                   15720: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15721: 		$curfext.".gif";
                   15722: 	}
                   15723:     }
1.249     albertel 15724:     return &lonhttpdurl($iconname);
1.154     albertel 15725: } 
1.84      albertel 15726: 
1.575     albertel 15727: sub lonhttpdurl {
1.692     www      15728: #
                   15729: # Had been used for "small fry" static images on separate port 8080.
                   15730: # Modify here if lightweight http functionality desired again.
                   15731: # Currently eliminated due to increasing firewall issues.
                   15732: #
1.575     albertel 15733:     my ($url)=@_;
1.692     www      15734:     return $url;
1.215     albertel 15735: }
                   15736: 
1.213     albertel 15737: sub connection_aborted {
                   15738:     my ($r)=@_;
                   15739:     $r->print(" ");$r->rflush();
                   15740:     my $c = $r->connection;
                   15741:     return $c->aborted();
                   15742: }
                   15743: 
1.221     foxr     15744: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15745: #    strings as 'strings'.
                   15746: sub escape_single {
1.221     foxr     15747:     my ($input) = @_;
1.223     albertel 15748:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15749:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15750:     return $input;
                   15751: }
1.223     albertel 15752: 
1.222     foxr     15753: #  Same as escape_single, but escape's "'s  This 
                   15754: #  can be used for  "strings"
                   15755: sub escape_double {
                   15756:     my ($input) = @_;
                   15757:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15758:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15759:     return $input;
                   15760: }
1.223     albertel 15761:  
1.222     foxr     15762: #   Escapes the last element of a full URL.
                   15763: sub escape_url {
                   15764:     my ($url)   = @_;
1.238     raeburn  15765:     my @urlslices = split(/\//, $url,-1);
1.369     www      15766:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15767:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15768: }
1.462     albertel 15769: 
1.820     raeburn  15770: sub compare_arrays {
                   15771:     my ($arrayref1,$arrayref2) = @_;
                   15772:     my (@difference,%count);
                   15773:     @difference = ();
                   15774:     %count = ();
                   15775:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15776:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15777:         foreach my $element (keys(%count)) {
                   15778:             if ($count{$element} == 1) {
                   15779:                 push(@difference,$element);
                   15780:             }
                   15781:         }
                   15782:     }
                   15783:     return @difference;
                   15784: }
                   15785: 
1.817     bisitz   15786: # -------------------------------------------------------- Initialize user login
1.462     albertel 15787: sub init_user_environment {
1.463     albertel 15788:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15789:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15790: 
                   15791:     my $public=($username eq 'public' && $domain eq 'public');
                   15792: 
                   15793: # See if old ID present, if so, remove
                   15794: 
1.1062    raeburn  15795:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15796:     my $now=time;
                   15797: 
                   15798:     if ($public) {
                   15799: 	my $max_public=100;
                   15800: 	my $oldest;
                   15801: 	my $oldest_time=0;
                   15802: 	for(my $next=1;$next<=$max_public;$next++) {
                   15803: 	    if (-e $lonids."/publicuser_$next.id") {
                   15804: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15805: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15806: 		    $oldest_time=$mtime;
                   15807: 		    $oldest=$next;
                   15808: 		}
                   15809: 	    } else {
                   15810: 		$cookie="publicuser_$next";
                   15811: 		last;
                   15812: 	    }
                   15813: 	}
                   15814: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15815:     } else {
1.463     albertel 15816: 	# if this isn't a robot, kill any existing non-robot sessions
                   15817: 	if (!$args->{'robot'}) {
                   15818: 	    opendir(DIR,$lonids);
                   15819: 	    while ($filename=readdir(DIR)) {
                   15820: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  15821:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   15822:                             &GDBM_READER(),0640)) {
                   15823:                         my $linkedfile;
                   15824:                         if (exists($oldenv{'user.linkedenv'})) {
                   15825:                             $linkedfile = $oldenv{'user.linkedenv'};
                   15826:                         }
                   15827:                         untie(%oldenv);
                   15828:                         if (unlink("$lonids/$filename")) {
                   15829:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   15830:                                 if (-l "$lonids/$linkedfile.id") {
                   15831:                                     unlink("$lonids/$linkedfile.id");
                   15832:                                 }
                   15833:                             }
                   15834:                         }
                   15835:                     } else {
                   15836:                         unlink($lonids.'/'.$filename);
                   15837:                     }
1.463     albertel 15838: 		}
1.462     albertel 15839: 	    }
1.463     albertel 15840: 	    closedir(DIR);
1.1075.2.84  raeburn  15841: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15842:             my $namespace = 'nohist_courseeditor';
                   15843:             my $lockingkey = 'paste'."\0".'locked_num';
                   15844:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15845:                                                 $domain,$username);
                   15846:             if (exists($lockhash{$lockingkey})) {
                   15847:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15848:                 unless ($delresult eq 'ok') {
                   15849:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15850:                 }
                   15851:             }
1.462     albertel 15852: 	}
                   15853: # Give them a new cookie
1.463     albertel 15854: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15855: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15856: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15857:     
                   15858: # Initialize roles
                   15859: 
1.1062    raeburn  15860: 	($userroles,$firstaccenv,$timerintenv) = 
                   15861:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15862:     }
                   15863: # ------------------------------------ Check browser type and MathML capability
                   15864: 
1.1075.2.77  raeburn  15865:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15866:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15867: 
                   15868: # ------------------------------------------------------------- Get environment
                   15869: 
                   15870:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15871:     my ($tmp) = keys(%userenv);
                   15872:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15873:     } else {
                   15874: 	undef(%userenv);
                   15875:     }
                   15876:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15877: 	$form->{'interface'}=$userenv{'interface'};
                   15878:     }
                   15879:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15880: 
                   15881: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15882:     foreach my $option ('interface','localpath','localres') {
                   15883:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15884:     }
                   15885: # --------------------------------------------------------- Write first profile
                   15886: 
                   15887:     {
                   15888: 	my %initial_env = 
                   15889: 	    ("user.name"          => $username,
                   15890: 	     "user.domain"        => $domain,
                   15891: 	     "user.home"          => $authhost,
                   15892: 	     "browser.type"       => $clientbrowser,
                   15893: 	     "browser.version"    => $clientversion,
                   15894: 	     "browser.mathml"     => $clientmathml,
                   15895: 	     "browser.unicode"    => $clientunicode,
                   15896: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15897:              "browser.mobile"     => $clientmobile,
                   15898:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15899:              "browser.osversion"  => $clientosversion,
1.462     albertel 15900: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15901: 	     "request.course.fn"  => '',
                   15902: 	     "request.course.uri" => '',
                   15903: 	     "request.course.sec" => '',
                   15904: 	     "request.role"       => 'cm',
                   15905: 	     "request.role.adv"   => $env{'user.adv'},
                   15906: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15907: 
                   15908:         if ($form->{'localpath'}) {
                   15909: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15910: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15911:         }
                   15912: 	
                   15913: 	if ($form->{'interface'}) {
                   15914: 	    $form->{'interface'}=~s/\W//gs;
                   15915: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15916: 	    $env{'browser.interface'}=$form->{'interface'};
                   15917: 	}
                   15918: 
1.1075.2.54  raeburn  15919:         if ($form->{'iptoken'}) {
                   15920:             my $lonhost = $r->dir_config('lonHostID');
                   15921:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15922:             $env{'user.noloadbalance'} = $lonhost;
                   15923:         }
                   15924: 
1.1075.2.120  raeburn  15925:         if ($form->{'noloadbalance'}) {
                   15926:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15927:             my $hosthere = $form->{'noloadbalance'};
                   15928:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15929:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15930:                 $env{'user.noloadbalance'} = $hosthere;
                   15931:             }
                   15932:         }
                   15933: 
1.1016    raeburn  15934:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15935:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15936:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15937: 
1.1075.2.125  raeburn  15938:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15939:                 $userenv{'availabletools.'.$tool} = 
                   15940:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15941:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15942:             }
1.724     raeburn  15943: 
1.1075.2.125  raeburn  15944:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15945:                 $userenv{'canrequest.'.$crstype} =
                   15946:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15947:                                                       'reload','requestcourses',
                   15948:                                                       \%userenv,\%domdef,\%is_adv);
                   15949:             }
1.765     raeburn  15950: 
1.1075.2.125  raeburn  15951:             $userenv{'canrequest.author'} =
                   15952:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15953:                                                   'reload','requestauthor',
                   15954:                                                   \%userenv,\%domdef,\%is_adv);
                   15955:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15956:                                                  $domain,$username);
                   15957:             my $reqstatus = $reqauthor{'author_status'};
                   15958:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15959:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15960:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15961:                                                       $reqauthor{'author'}{'timestamp'};
                   15962:                 }
1.1075.2.14  raeburn  15963:             }
                   15964:         }
                   15965: 
1.462     albertel 15966: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15967: 
1.462     albertel 15968: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15969: 		 &GDBM_WRCREAT(),0640)) {
                   15970: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15971: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15972: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15973:             if (ref($firstaccenv) eq 'HASH') {
                   15974:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15975:             }
                   15976:             if (ref($timerintenv) eq 'HASH') {
                   15977:                 &_add_to_env(\%disk_env,$timerintenv);
                   15978:             }
1.463     albertel 15979: 	    if (ref($args->{'extra_env'})) {
                   15980: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15981: 	    }
1.462     albertel 15982: 	    untie(%disk_env);
                   15983: 	} else {
1.705     tempelho 15984: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15985: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15986: 	    return 'error: '.$!;
                   15987: 	}
                   15988:     }
                   15989:     $env{'request.role'}='cm';
                   15990:     $env{'request.role.adv'}=$env{'user.adv'};
                   15991:     $env{'browser.type'}=$clientbrowser;
                   15992: 
                   15993:     return $cookie;
                   15994: 
                   15995: }
                   15996: 
                   15997: sub _add_to_env {
                   15998:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15999:     if (ref($env_data) eq 'HASH') {
                   16000:         while (my ($key,$value) = each(%$env_data)) {
                   16001: 	    $idf->{$prefix.$key} = $value;
                   16002: 	    $env{$prefix.$key}   = $value;
                   16003:         }
1.462     albertel 16004:     }
                   16005: }
                   16006: 
1.685     tempelho 16007: # --- Get the symbolic name of a problem and the url
                   16008: sub get_symb {
                   16009:     my ($request,$silent) = @_;
1.726     raeburn  16010:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16011:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16012:     if ($symb eq '') {
                   16013:         if (!$silent) {
1.1071    raeburn  16014:             if (ref($request)) { 
                   16015:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16016:             }
1.685     tempelho 16017:             return ();
                   16018:         }
                   16019:     }
                   16020:     &Apache::lonenc::check_decrypt(\$symb);
                   16021:     return ($symb);
                   16022: }
                   16023: 
                   16024: # --------------------------------------------------------------Get annotation
                   16025: 
                   16026: sub get_annotation {
                   16027:     my ($symb,$enc) = @_;
                   16028: 
                   16029:     my $key = $symb;
                   16030:     if (!$enc) {
                   16031:         $key =
                   16032:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16033:     }
                   16034:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16035:     return $annotation{$key};
                   16036: }
                   16037: 
                   16038: sub clean_symb {
1.731     raeburn  16039:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16040: 
                   16041:     &Apache::lonenc::check_decrypt(\$symb);
                   16042:     my $enc = $env{'request.enc'};
1.731     raeburn  16043:     if ($delete_enc) {
1.730     raeburn  16044:         delete($env{'request.enc'});
                   16045:     }
1.685     tempelho 16046: 
                   16047:     return ($symb,$enc);
                   16048: }
1.462     albertel 16049: 
1.1075.2.69  raeburn  16050: ############################################################
                   16051: ############################################################
                   16052: 
                   16053: =pod
                   16054: 
                   16055: =head1 Routines for building display used to search for courses
                   16056: 
                   16057: 
                   16058: =over 4
                   16059: 
                   16060: =item * &build_filters()
                   16061: 
                   16062: Create markup for a table used to set filters to use when selecting
                   16063: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16064: and quotacheck.pl
                   16065: 
                   16066: 
                   16067: Inputs:
                   16068: 
                   16069: filterlist - anonymous array of fields to include as potential filters
                   16070: 
                   16071: crstype - course type
                   16072: 
                   16073: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16074:               to pop-open a course selector (will contain "extra element").
                   16075: 
                   16076: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16077: 
                   16078: filter - anonymous hash of criteria and their values
                   16079: 
                   16080: action - form action
                   16081: 
                   16082: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16083: 
                   16084: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16085: 
                   16086: cloneruname - username of owner of new course who wants to clone
                   16087: 
                   16088: clonerudom - domain of owner of new course who wants to clone
                   16089: 
                   16090: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16091: 
                   16092: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16093: 
                   16094: codedom - domain
                   16095: 
                   16096: formname - value of form element named "form".
                   16097: 
                   16098: fixeddom - domain, if fixed.
                   16099: 
                   16100: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16101: 
                   16102: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16103: 
                   16104: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16105: 
                   16106: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16107: 
                   16108: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16109: 
                   16110: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16111: 
                   16112: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16113: 
                   16114: 
                   16115: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16116: 
                   16117: 
                   16118: Side Effects: None
                   16119: 
                   16120: =cut
                   16121: 
                   16122: # ---------------------------------------------- search for courses based on last activity etc.
                   16123: 
                   16124: sub build_filters {
                   16125:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16126:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16127:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16128:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16129:         $clonetext,$clonewarning) = @_;
                   16130:     my ($list,$jscript);
                   16131:     my $onchange = 'javascript:updateFilters(this)';
                   16132:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16133:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16134:         $typeselectform,$instcodetitle);
                   16135:     if ($formname eq '') {
                   16136:         $formname = $caller;
                   16137:     }
                   16138:     foreach my $item (@{$filterlist}) {
                   16139:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16140:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16141:             if ($item eq 'domainfilter') {
                   16142:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16143:             } elsif ($item eq 'coursefilter') {
                   16144:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16145:             } elsif ($item eq 'ownerfilter') {
                   16146:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16147:             } elsif ($item eq 'ownerdomfilter') {
                   16148:                 $filter->{'ownerdomfilter'} =
                   16149:                     &LONCAPA::clean_domain($filter->{$item});
                   16150:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16151:                                                        'ownerdomfilter',1);
                   16152:             } elsif ($item eq 'personfilter') {
                   16153:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16154:             } elsif ($item eq 'persondomfilter') {
                   16155:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16156:                                                         'persondomfilter',1);
                   16157:             } else {
                   16158:                 $filter->{$item} =~ s/\W//g;
                   16159:             }
                   16160:             if (!$filter->{$item}) {
                   16161:                 $filter->{$item} = '';
                   16162:             }
                   16163:         }
                   16164:         if ($item eq 'domainfilter') {
                   16165:             my $allow_blank = 1;
                   16166:             if ($formname eq 'portform') {
                   16167:                 $allow_blank=0;
                   16168:             } elsif ($formname eq 'studentform') {
                   16169:                 $allow_blank=0;
                   16170:             }
                   16171:             if ($fixeddom) {
                   16172:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16173:                                     ' value="'.$codedom.'" />'.
                   16174:                                     &Apache::lonnet::domain($codedom,'description');
                   16175:             } else {
                   16176:                 $domainselectform = &select_dom_form($filter->{$item},
                   16177:                                                      'domainfilter',
                   16178:                                                       $allow_blank,'',$onchange);
                   16179:             }
                   16180:         } else {
                   16181:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16182:         }
                   16183:     }
                   16184: 
                   16185:     # last course activity filter and selection
                   16186:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16187: 
                   16188:     # course created filter and selection
                   16189:     if (exists($filter->{'createdfilter'})) {
                   16190:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16191:     }
                   16192: 
                   16193:     my %lt = &Apache::lonlocal::texthash(
                   16194:                 'cac' => "$crstype Activity",
                   16195:                 'ccr' => "$crstype Created",
                   16196:                 'cde' => "$crstype Title",
                   16197:                 'cdo' => "$crstype Domain",
                   16198:                 'ins' => 'Institutional Code',
                   16199:                 'inc' => 'Institutional Categorization',
                   16200:                 'cow' => "$crstype Owner/Co-owner",
                   16201:                 'cop' => "$crstype Personnel Includes",
                   16202:                 'cog' => 'Type',
                   16203:              );
                   16204: 
                   16205:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16206:         my $typeval = 'Course';
                   16207:         if ($crstype eq 'Community') {
                   16208:             $typeval = 'Community';
                   16209:         }
                   16210:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16211:     } else {
                   16212:         $typeselectform =  '<select name="type" size="1"';
                   16213:         if ($onchange) {
                   16214:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16215:         }
                   16216:         $typeselectform .= '>'."\n";
                   16217:         foreach my $posstype ('Course','Community') {
                   16218:             $typeselectform.='<option value="'.$posstype.'"'.
                   16219:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16220:         }
                   16221:         $typeselectform.="</select>";
                   16222:     }
                   16223: 
                   16224:     my ($cloneableonlyform,$cloneabletitle);
                   16225:     if (exists($filter->{'cloneableonly'})) {
                   16226:         my $cloneableon = '';
                   16227:         my $cloneableoff = ' checked="checked"';
                   16228:         if ($filter->{'cloneableonly'}) {
                   16229:             $cloneableon = $cloneableoff;
                   16230:             $cloneableoff = '';
                   16231:         }
                   16232:         $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>';
                   16233:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16234:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16235:         } else {
                   16236:             $cloneabletitle = &mt('Cloneable by you');
                   16237:         }
                   16238:     }
                   16239:     my $officialjs;
                   16240:     if ($crstype eq 'Course') {
                   16241:         if (exists($filter->{'instcodefilter'})) {
                   16242: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16243: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16244:             if ($codedom) {
                   16245:                 $officialjs = 1;
                   16246:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16247:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16248:                                                                   $officialjs,$codetitlesref);
                   16249:                 if ($jscript) {
                   16250:                     $jscript = '<script type="text/javascript">'."\n".
                   16251:                                '// <![CDATA['."\n".
                   16252:                                $jscript."\n".
                   16253:                                '// ]]>'."\n".
                   16254:                                '</script>'."\n";
                   16255:                 }
                   16256:             }
                   16257:             if ($instcodeform eq '') {
                   16258:                 $instcodeform =
                   16259:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16260:                     $list->{'instcodefilter'}.'" />';
                   16261:                 $instcodetitle = $lt{'ins'};
                   16262:             } else {
                   16263:                 $instcodetitle = $lt{'inc'};
                   16264:             }
                   16265:             if ($fixeddom) {
                   16266:                 $instcodetitle .= '<br />('.$codedom.')';
                   16267:             }
                   16268:         }
                   16269:     }
                   16270:     my $output = qq|
                   16271: <form method="post" name="filterpicker" action="$action">
                   16272: <input type="hidden" name="form" value="$formname" />
                   16273: |;
                   16274:     if ($formname eq 'modifycourse') {
                   16275:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16276:                    '<input type="hidden" name="prevphase" value="'.
                   16277:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16278:     } elsif ($formname eq 'quotacheck') {
                   16279:         $output .= qq|
                   16280: <input type="hidden" name="sortby" value="" />
                   16281: <input type="hidden" name="sortorder" value="" />
                   16282: |;
                   16283:     } else {
1.1075.2.69  raeburn  16284:         my $name_input;
                   16285:         if ($cnameelement ne '') {
                   16286:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16287:                           $cnameelement.'" />';
                   16288:         }
                   16289:         $output .= qq|
                   16290: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16291: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16292: $name_input
                   16293: $roleelement
                   16294: $multelement
                   16295: $typeelement
                   16296: |;
                   16297:         if ($formname eq 'portform') {
                   16298:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16299:         }
                   16300:     }
                   16301:     if ($fixeddom) {
                   16302:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16303:     }
                   16304:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16305:     if ($sincefilterform) {
                   16306:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16307:                   .$sincefilterform
                   16308:                   .&Apache::lonhtmlcommon::row_closure();
                   16309:     }
                   16310:     if ($createdfilterform) {
                   16311:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16312:                   .$createdfilterform
                   16313:                   .&Apache::lonhtmlcommon::row_closure();
                   16314:     }
                   16315:     if ($domainselectform) {
                   16316:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16317:                   .$domainselectform
                   16318:                   .&Apache::lonhtmlcommon::row_closure();
                   16319:     }
                   16320:     if ($typeselectform) {
                   16321:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16322:             $output .= $typeselectform;
                   16323:         } else {
                   16324:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16325:                       .$typeselectform
                   16326:                       .&Apache::lonhtmlcommon::row_closure();
                   16327:         }
                   16328:     }
                   16329:     if ($instcodeform) {
                   16330:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16331:                   .$instcodeform
                   16332:                   .&Apache::lonhtmlcommon::row_closure();
                   16333:     }
                   16334:     if (exists($filter->{'ownerfilter'})) {
                   16335:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16336:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16337:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16338:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16339:                    $ownerdomselectform.'</td></tr></table>'.
                   16340:                    &Apache::lonhtmlcommon::row_closure();
                   16341:     }
                   16342:     if (exists($filter->{'personfilter'})) {
                   16343:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16344:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16345:                    '<input type="text" name="personfilter" size="20" value="'.
                   16346:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16347:                    $persondomselectform.'</td></tr></table>'.
                   16348:                    &Apache::lonhtmlcommon::row_closure();
                   16349:     }
                   16350:     if (exists($filter->{'coursefilter'})) {
                   16351:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16352:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16353:                   .$list->{'coursefilter'}.'" />'
                   16354:                   .&Apache::lonhtmlcommon::row_closure();
                   16355:     }
                   16356:     if ($cloneableonlyform) {
                   16357:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16358:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16359:     }
                   16360:     if (exists($filter->{'descriptfilter'})) {
                   16361:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16362:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16363:                   .$list->{'descriptfilter'}.'" />'
                   16364:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16365:     }
                   16366:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16367:                '<input type="hidden" name="updater" value="" />'."\n".
                   16368:                '<input type="submit" name="gosearch" value="'.
                   16369:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16370:     return $jscript.$clonewarning.$output;
                   16371: }
                   16372: 
                   16373: =pod
                   16374: 
                   16375: =item * &timebased_select_form()
                   16376: 
                   16377: Create markup for a dropdown list used to select a time-based
                   16378: filter e.g., Course Activity, Course Created, when searching for courses
                   16379: or communities
                   16380: 
                   16381: Inputs:
                   16382: 
                   16383: item - name of form element (sincefilter or createdfilter)
                   16384: 
                   16385: filter - anonymous hash of criteria and their values
                   16386: 
                   16387: Returns: HTML for a select box contained a blank, then six time selections,
                   16388:          with value set in incoming form variables currently selected.
                   16389: 
                   16390: Side Effects: None
                   16391: 
                   16392: =cut
                   16393: 
                   16394: sub timebased_select_form {
                   16395:     my ($item,$filter) = @_;
                   16396:     if (ref($filter) eq 'HASH') {
                   16397:         $filter->{$item} =~ s/[^\d-]//g;
                   16398:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16399:         return &select_form(
                   16400:                             $filter->{$item},
                   16401:                             $item,
                   16402:                             {      '-1' => '',
                   16403:                                 '86400' => &mt('today'),
                   16404:                                '604800' => &mt('last week'),
                   16405:                               '2592000' => &mt('last month'),
                   16406:                               '7776000' => &mt('last three months'),
                   16407:                              '15552000' => &mt('last six months'),
                   16408:                              '31104000' => &mt('last year'),
                   16409:                     'select_form_order' =>
                   16410:                            ['-1','86400','604800','2592000','7776000',
                   16411:                             '15552000','31104000']});
                   16412:     }
                   16413: }
                   16414: 
                   16415: =pod
                   16416: 
                   16417: =item * &js_changer()
                   16418: 
                   16419: Create script tag containing Javascript used to submit course search form
                   16420: when course type or domain is changed, and also to hide 'Searching ...' on
                   16421: page load completion for page showing search result.
                   16422: 
                   16423: Inputs: None
                   16424: 
                   16425: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16426: 
                   16427: Side Effects: None
                   16428: 
                   16429: =cut
                   16430: 
                   16431: sub js_changer {
                   16432:     return <<ENDJS;
                   16433: <script type="text/javascript">
                   16434: // <![CDATA[
                   16435: function updateFilters(caller) {
                   16436:     if (typeof(caller) != "undefined") {
                   16437:         document.filterpicker.updater.value = caller.name;
                   16438:     }
                   16439:     document.filterpicker.submit();
                   16440: }
                   16441: 
                   16442: function hideSearching() {
                   16443:     if (document.getElementById('searching')) {
                   16444:         document.getElementById('searching').style.display = 'none';
                   16445:     }
                   16446:     return;
                   16447: }
                   16448: 
                   16449: // ]]>
                   16450: </script>
                   16451: 
                   16452: ENDJS
                   16453: }
                   16454: 
                   16455: =pod
                   16456: 
                   16457: =item * &search_courses()
                   16458: 
                   16459: Process selected filters form course search form and pass to lonnet::courseiddump
                   16460: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16461: 
                   16462: Inputs:
                   16463: 
                   16464: dom - domain being searched
                   16465: 
                   16466: type - course type ('Course' or 'Community' or '.' if any).
                   16467: 
                   16468: filter - anonymous hash of criteria and their values
                   16469: 
                   16470: numtitles - for institutional codes - number of categories
                   16471: 
                   16472: cloneruname - optional username of new course owner
                   16473: 
                   16474: clonerudom - optional domain of new course owner
                   16475: 
1.1075.2.95  raeburn  16476: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16477:             (used when DC is using course creation form)
                   16478: 
                   16479: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16480: 
1.1075.2.95  raeburn  16481: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16482:            (and so can clone automatically)
                   16483: 
                   16484: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16485: 
                   16486: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16487:               courses to clone
1.1075.2.69  raeburn  16488: 
                   16489: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16490: 
                   16491: 
                   16492: Side Effects: None
                   16493: 
                   16494: =cut
                   16495: 
                   16496: 
                   16497: sub search_courses {
1.1075.2.95  raeburn  16498:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16499:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16500:     my (%courses,%showcourses,$cloner);
                   16501:     if (($filter->{'ownerfilter'} ne '') ||
                   16502:         ($filter->{'ownerdomfilter'} ne '')) {
                   16503:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16504:                                        $filter->{'ownerdomfilter'};
                   16505:     }
                   16506:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16507:         if (!$filter->{$item}) {
                   16508:             $filter->{$item}='.';
                   16509:         }
                   16510:     }
                   16511:     my $now = time;
                   16512:     my $timefilter =
                   16513:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16514:     my ($createdbefore,$createdafter);
                   16515:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16516:         $createdbefore = $now;
                   16517:         $createdafter = $now-$filter->{'createdfilter'};
                   16518:     }
                   16519:     my ($instcodefilter,$regexpok);
                   16520:     if ($numtitles) {
                   16521:         if ($env{'form.official'} eq 'on') {
                   16522:             $instcodefilter =
                   16523:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16524:             $regexpok = 1;
                   16525:         } elsif ($env{'form.official'} eq 'off') {
                   16526:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16527:             unless ($instcodefilter eq '') {
                   16528:                 $regexpok = -1;
                   16529:             }
                   16530:         }
                   16531:     } else {
                   16532:         $instcodefilter = $filter->{'instcodefilter'};
                   16533:     }
                   16534:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16535:     if ($type eq '') { $type = '.'; }
                   16536: 
                   16537:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16538:         $cloner = $cloneruname.':'.$clonerudom;
                   16539:     }
                   16540:     %courses = &Apache::lonnet::courseiddump($dom,
                   16541:                                              $filter->{'descriptfilter'},
                   16542:                                              $timefilter,
                   16543:                                              $instcodefilter,
                   16544:                                              $filter->{'combownerfilter'},
                   16545:                                              $filter->{'coursefilter'},
                   16546:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16547:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16548:                                              $filter->{'cloneableonly'},
                   16549:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16550:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16551:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16552:         my $ccrole;
                   16553:         if ($type eq 'Community') {
                   16554:             $ccrole = 'co';
                   16555:         } else {
                   16556:             $ccrole = 'cc';
                   16557:         }
                   16558:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16559:                                                      $filter->{'persondomfilter'},
                   16560:                                                      'userroles',undef,
                   16561:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16562:                                                      $dom);
                   16563:         foreach my $role (keys(%rolehash)) {
                   16564:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16565:             my $cid = $cdom.'_'.$cnum;
                   16566:             if (exists($courses{$cid})) {
                   16567:                 if (ref($courses{$cid}) eq 'HASH') {
                   16568:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16569:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16570:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16571:                         }
                   16572:                     } else {
                   16573:                         $courses{$cid}{roles} = [$courserole];
                   16574:                     }
                   16575:                     $showcourses{$cid} = $courses{$cid};
                   16576:                 }
                   16577:             }
                   16578:         }
                   16579:         %courses = %showcourses;
                   16580:     }
                   16581:     return %courses;
                   16582: }
                   16583: 
                   16584: =pod
                   16585: 
                   16586: =back
                   16587: 
1.1075.2.88  raeburn  16588: =head1 Routines for version requirements for current course.
                   16589: 
                   16590: =over 4
                   16591: 
                   16592: =item * &check_release_required()
                   16593: 
                   16594: Compares required LON-CAPA version with version on server, and
                   16595: if required version is newer looks for a server with the required version.
                   16596: 
                   16597: Looks first at servers in user's owen domain; if none suitable, looks at
                   16598: servers in course's domain are permitted to host sessions for user's domain.
                   16599: 
                   16600: Inputs:
                   16601: 
                   16602: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16603: 
                   16604: $courseid - Course ID of current course
                   16605: 
                   16606: $rolecode - User's current role in course (for switchserver query string).
                   16607: 
                   16608: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16609: 
                   16610: 
                   16611: Returns:
                   16612: 
                   16613: $switchserver - query string tp append to /adm/switchserver call (if
                   16614:                 current server's LON-CAPA version is too old.
                   16615: 
                   16616: $warning - Message is displayed if no suitable server could be found.
                   16617: 
                   16618: =cut
                   16619: 
                   16620: sub check_release_required {
                   16621:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16622:     my ($switchserver,$warning);
                   16623:     if ($required ne '') {
                   16624:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16625:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16626:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16627:             my $otherserver;
                   16628:             if (($major eq '' && $minor eq '') ||
                   16629:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16630:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16631:                 my $switchlcrev =
                   16632:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16633:                                                            $userdomserver);
                   16634:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16635:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16636:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16637:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16638:                     if ($cdom ne $env{'user.domain'}) {
                   16639:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16640:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16641:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16642:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16643:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16644:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16645:                         my $canhost =
                   16646:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16647:                                                               $coursedomserver,
                   16648:                                                               $remoterev,
                   16649:                                                               $udomdefaults{'remotesessions'},
                   16650:                                                               $defdomdefaults{'hostedsessions'});
                   16651: 
                   16652:                         if ($canhost) {
                   16653:                             $otherserver = $coursedomserver;
                   16654:                         } else {
                   16655:                             $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.");
                   16656:                         }
                   16657:                     } else {
                   16658:                         $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).");
                   16659:                     }
                   16660:                 } else {
                   16661:                     $otherserver = $userdomserver;
                   16662:                 }
                   16663:             }
                   16664:             if ($otherserver ne '') {
                   16665:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16666:             }
                   16667:         }
                   16668:     }
                   16669:     return ($switchserver,$warning);
                   16670: }
                   16671: 
                   16672: =pod
                   16673: 
                   16674: =item * &check_release_result()
                   16675: 
                   16676: Inputs:
                   16677: 
                   16678: $switchwarning - Warning message if no suitable server found to host session.
                   16679: 
                   16680: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16681:                 and current role.
                   16682: 
                   16683: Returns: HTML to display with information about requirement to switch server.
                   16684:          Either displaying warning with link to Roles/Courses screen or
                   16685:          display link to switchserver.
                   16686: 
1.1075.2.69  raeburn  16687: =cut
                   16688: 
1.1075.2.88  raeburn  16689: sub check_release_result {
                   16690:     my ($switchwarning,$switchserver) = @_;
                   16691:     my $output = &start_page('Selected course unavailable on this server').
                   16692:                  '<p class="LC_warning">';
                   16693:     if ($switchwarning) {
                   16694:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16695:         if (&show_course()) {
                   16696:             $output .= &mt('Display courses');
                   16697:         } else {
                   16698:             $output .= &mt('Display roles');
                   16699:         }
                   16700:         $output .= '</a>';
                   16701:     } elsif ($switchserver) {
                   16702:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16703:                    '<br />'.
                   16704:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16705:                    &mt('Switch Server').
                   16706:                    '</a>';
                   16707:     }
                   16708:     $output .= '</p>'.&end_page();
                   16709:     return $output;
                   16710: }
                   16711: 
                   16712: =pod
                   16713: 
                   16714: =item * &needs_coursereinit()
                   16715: 
                   16716: Determine if course contents stored for user's session needs to be
                   16717: refreshed, because content has changed since "Big Hash" last tied.
                   16718: 
                   16719: Check for change is made if time last checked is more than 10 minutes ago
                   16720: (by default).
                   16721: 
                   16722: Inputs:
                   16723: 
                   16724: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16725: 
                   16726: $interval (optional) - Time which may elapse (in s) between last check for content
                   16727:                        change in current course. (default: 600 s).
                   16728: 
                   16729: Returns: an array; first element is:
                   16730: 
                   16731: =over 4
                   16732: 
                   16733: 'switch' - if content updates mean user's session
                   16734:            needs to be switched to a server running a newer LON-CAPA version
                   16735: 
                   16736: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16737:            on current server hosting user's session
                   16738: 
                   16739: ''       - if no action required.
                   16740: 
                   16741: =back
                   16742: 
                   16743: If first item element is 'switch':
                   16744: 
                   16745: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16746: 
                   16747: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16748:                               and current role.
                   16749: 
                   16750: otherwise: no other elements returned.
                   16751: 
                   16752: =back
                   16753: 
                   16754: =cut
                   16755: 
                   16756: sub needs_coursereinit {
                   16757:     my ($loncaparev,$interval) = @_;
                   16758:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16759:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16760:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16761:     my $now = time;
                   16762:     if ($interval eq '') {
                   16763:         $interval = 600;
                   16764:     }
                   16765:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16766:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16767:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16768:         if ($lastchange > $env{'request.course.tied'}) {
                   16769:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16770:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16771:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16772:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16773:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16774:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16775:                     my ($switchserver,$switchwarning) =
                   16776:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16777:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16778:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16779:                         return ('switch',$switchwarning,$switchserver);
                   16780:                     }
                   16781:                 }
                   16782:             }
                   16783:             return ('update');
                   16784:         }
                   16785:     }
                   16786:     return ();
                   16787: }
1.1075.2.69  raeburn  16788: 
1.1075.2.11  raeburn  16789: sub update_content_constraints {
                   16790:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16791:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16792:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16793:     my %checkresponsetypes;
                   16794:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16795:         my ($item,$name,$value) = split(/:/,$key);
                   16796:         if ($item eq 'resourcetag') {
                   16797:             if ($name eq 'responsetype') {
                   16798:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16799:             }
                   16800:         }
                   16801:     }
                   16802:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16803:     if (defined($navmap)) {
                   16804:         my %allresponses;
                   16805:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16806:             my %responses = $res->responseTypes();
                   16807:             foreach my $key (keys(%responses)) {
                   16808:                 next unless(exists($checkresponsetypes{$key}));
                   16809:                 $allresponses{$key} += $responses{$key};
                   16810:             }
                   16811:         }
                   16812:         foreach my $key (keys(%allresponses)) {
                   16813:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16814:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16815:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16816:             }
                   16817:         }
                   16818:         undef($navmap);
                   16819:     }
                   16820:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16821:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16822:     }
                   16823:     return;
                   16824: }
                   16825: 
1.1075.2.27  raeburn  16826: sub allmaps_incourse {
                   16827:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16828:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16829:         $cid = $env{'request.course.id'};
                   16830:         $cdom = $env{'course.'.$cid.'.domain'};
                   16831:         $cnum = $env{'course.'.$cid.'.num'};
                   16832:         $chome = $env{'course.'.$cid.'.home'};
                   16833:     }
                   16834:     my %allmaps = ();
                   16835:     my $lastchange =
                   16836:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16837:     if ($lastchange > $env{'request.course.tied'}) {
                   16838:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16839:         unless ($ferr) {
                   16840:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16841:         }
                   16842:     }
                   16843:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16844:     if (defined($navmap)) {
                   16845:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16846:             $allmaps{$res->src()} = 1;
                   16847:         }
                   16848:     }
                   16849:     return \%allmaps;
                   16850: }
                   16851: 
1.1075.2.11  raeburn  16852: sub parse_supplemental_title {
                   16853:     my ($title) = @_;
                   16854: 
                   16855:     my ($foldertitle,$renametitle);
                   16856:     if ($title =~ /&amp;&amp;&amp;/) {
                   16857:         $title = &HTML::Entites::decode($title);
                   16858:     }
                   16859:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16860:         $renametitle=$4;
                   16861:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16862:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16863:         my $name =  &plainname($uname,$udom);
                   16864:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16865:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16866:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16867:             $name.': <br />'.$foldertitle;
                   16868:     }
                   16869:     if (wantarray) {
                   16870:         return ($title,$foldertitle,$renametitle);
                   16871:     }
                   16872:     return $title;
                   16873: }
                   16874: 
1.1075.2.43  raeburn  16875: sub recurse_supplemental {
                   16876:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16877:     if ($suppmap) {
                   16878:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16879:         if ($fatal) {
                   16880:             $errors ++;
                   16881:         } else {
                   16882:             if ($#LONCAPA::map::resources > 0) {
                   16883:                 foreach my $res (@LONCAPA::map::resources) {
                   16884:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16885:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16886:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16887:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16888:                         } else {
                   16889:                             $numfiles ++;
                   16890:                         }
                   16891:                     }
                   16892:                 }
                   16893:             }
                   16894:         }
                   16895:     }
                   16896:     return ($numfiles,$errors);
                   16897: }
                   16898: 
1.1075.2.18  raeburn  16899: sub symb_to_docspath {
1.1075.2.119  raeburn  16900:     my ($symb,$navmapref) = @_;
                   16901:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16902:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16903:     if ($resurl=~/\.(sequence|page)$/) {
                   16904:         $mapurl=$resurl;
                   16905:     } elsif ($resurl eq 'adm/navmaps') {
                   16906:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16907:     }
                   16908:     my $mapresobj;
1.1075.2.119  raeburn  16909:     unless (ref($$navmapref)) {
                   16910:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16911:     }
                   16912:     if (ref($$navmapref)) {
                   16913:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16914:     }
                   16915:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16916:     my $type=$2;
                   16917:     my $path;
                   16918:     if (ref($mapresobj)) {
                   16919:         my $pcslist = $mapresobj->map_hierarchy();
                   16920:         if ($pcslist ne '') {
                   16921:             foreach my $pc (split(/,/,$pcslist)) {
                   16922:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16923:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16924:                 if (ref($res)) {
                   16925:                     my $thisurl = $res->src();
                   16926:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16927:                     my $thistitle = $res->title();
                   16928:                     $path .= '&'.
                   16929:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16930:                              &escape($thistitle).
1.1075.2.18  raeburn  16931:                              ':'.$res->randompick().
                   16932:                              ':'.$res->randomout().
                   16933:                              ':'.$res->encrypted().
                   16934:                              ':'.$res->randomorder().
                   16935:                              ':'.$res->is_page();
                   16936:                 }
                   16937:             }
                   16938:         }
                   16939:         $path =~ s/^\&//;
                   16940:         my $maptitle = $mapresobj->title();
                   16941:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16942:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16943:         }
                   16944:         $path .= (($path ne '')? '&' : '').
                   16945:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16946:                  &escape($maptitle).
1.1075.2.18  raeburn  16947:                  ':'.$mapresobj->randompick().
                   16948:                  ':'.$mapresobj->randomout().
                   16949:                  ':'.$mapresobj->encrypted().
                   16950:                  ':'.$mapresobj->randomorder().
                   16951:                  ':'.$mapresobj->is_page();
                   16952:     } else {
                   16953:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16954:         my $ispage = (($type eq 'page')? 1 : '');
                   16955:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16956:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16957:         }
                   16958:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16959:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16960:     }
                   16961:     unless ($mapurl eq 'default') {
                   16962:         $path = 'default&'.
1.1075.2.46  raeburn  16963:                 &escape('Main Content').
1.1075.2.18  raeburn  16964:                 ':::::&'.$path;
                   16965:     }
                   16966:     return $path;
                   16967: }
                   16968: 
1.1075.2.14  raeburn  16969: sub captcha_display {
1.1075.2.137  raeburn  16970:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  16971:     my ($output,$error);
1.1075.2.107  raeburn  16972:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  16973:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  16974:     if ($captcha eq 'original') {
                   16975:         $output = &create_captcha();
                   16976:         unless ($output) {
                   16977:             $error = 'captcha';
                   16978:         }
                   16979:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16980:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16981:         unless ($output) {
                   16982:             $error = 'recaptcha';
                   16983:         }
                   16984:     }
1.1075.2.107  raeburn  16985:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16986: }
                   16987: 
                   16988: sub captcha_response {
1.1075.2.137  raeburn  16989:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  16990:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  16991:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  16992:     if ($captcha eq 'original') {
                   16993:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16994:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16995:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16996:     } else {
                   16997:         $captcha_chk = 1;
                   16998:     }
                   16999:     return ($captcha_chk,$captcha_error);
                   17000: }
                   17001: 
                   17002: sub get_captcha_config {
1.1075.2.137  raeburn  17003:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  17004:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  17005:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17006:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17007:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17008:     if ($context eq 'usercreation') {
                   17009:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17010:         if (ref($domconfig{$context}) eq 'HASH') {
                   17011:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17012:             if (ref($hashtocheck) eq 'HASH') {
                   17013:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17014:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17015:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17016:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17017:                     }
                   17018:                     if ($privkey && $pubkey) {
                   17019:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  17020:                         $version = $hashtocheck->{'recaptchaversion'};
                   17021:                         if ($version ne '2') {
                   17022:                             $version = 1;
                   17023:                         }
1.1075.2.14  raeburn  17024:                     } else {
                   17025:                         $captcha = 'original';
                   17026:                     }
                   17027:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17028:                     $captcha = 'original';
                   17029:                 }
                   17030:             }
                   17031:         } else {
                   17032:             $captcha = 'captcha';
                   17033:         }
                   17034:     } elsif ($context eq 'login') {
                   17035:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17036:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17037:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17038:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17039:             if ($privkey && $pubkey) {
                   17040:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17041:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17042:                 if ($version ne '2') {
                   17043:                     $version = 1;
                   17044:                 }
1.1075.2.14  raeburn  17045:             } else {
                   17046:                 $captcha = 'original';
                   17047:             }
                   17048:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17049:             $captcha = 'original';
                   17050:         }
1.1075.2.137  raeburn  17051:     } elsif ($context eq 'passwords') {
                   17052:         if ($dom_in_effect) {
                   17053:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17054:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17055:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17056:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17057:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17058:                 }
                   17059:                 if ($privkey && $pubkey) {
                   17060:                     $captcha = 'recaptcha';
                   17061:                     $version = $passwdconf{'recaptchaversion'};
                   17062:                     if ($version ne '2') {
                   17063:                         $version = 1;
                   17064:                     }
                   17065:                 } else {
                   17066:                     $captcha = 'original';
                   17067:                 }
                   17068:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17069:                 $captcha = 'original';
                   17070:             }
                   17071:         }
1.1075.2.14  raeburn  17072:     }
1.1075.2.107  raeburn  17073:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17074: }
                   17075: 
                   17076: sub create_captcha {
                   17077:     my %captcha_params = &captcha_settings();
                   17078:     my ($output,$maxtries,$tries) = ('',10,0);
                   17079:     while ($tries < $maxtries) {
                   17080:         $tries ++;
                   17081:         my $captcha = Authen::Captcha->new (
                   17082:                                            output_folder => $captcha_params{'output_dir'},
                   17083:                                            data_folder   => $captcha_params{'db_dir'},
                   17084:                                           );
                   17085:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17086: 
                   17087:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17088:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17089:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17090:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17091:                       '<br />'.
                   17092:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17093:             last;
                   17094:         }
                   17095:     }
                   17096:     return $output;
                   17097: }
                   17098: 
                   17099: sub captcha_settings {
                   17100:     my %captcha_params = (
                   17101:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17102:                            www_output_dir => "/captchaspool",
                   17103:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17104:                            numchars       => '5',
                   17105:                          );
                   17106:     return %captcha_params;
                   17107: }
                   17108: 
                   17109: sub check_captcha {
                   17110:     my ($captcha_chk,$captcha_error);
                   17111:     my $code = $env{'form.code'};
                   17112:     my $md5sum = $env{'form.crypt'};
                   17113:     my %captcha_params = &captcha_settings();
                   17114:     my $captcha = Authen::Captcha->new(
                   17115:                       output_folder => $captcha_params{'output_dir'},
                   17116:                       data_folder   => $captcha_params{'db_dir'},
                   17117:                   );
1.1075.2.26  raeburn  17118:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17119:     my %captcha_hash = (
                   17120:                         0       => 'Code not checked (file error)',
                   17121:                        -1      => 'Failed: code expired',
                   17122:                        -2      => 'Failed: invalid code (not in database)',
                   17123:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17124:     );
                   17125:     if ($captcha_chk != 1) {
                   17126:         $captcha_error = $captcha_hash{$captcha_chk}
                   17127:     }
                   17128:     return ($captcha_chk,$captcha_error);
                   17129: }
                   17130: 
                   17131: sub create_recaptcha {
1.1075.2.107  raeburn  17132:     my ($pubkey,$version) = @_;
                   17133:     if ($version >= 2) {
                   17134:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17135:     } else {
                   17136:         my $use_ssl;
                   17137:         if ($ENV{'SERVER_PORT'} == 443) {
                   17138:             $use_ssl = 1;
                   17139:         }
                   17140:         my $captcha = Captcha::reCAPTCHA->new;
                   17141:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17142:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17143:                &mt('If the text is hard to read, [_1] will replace them.',
                   17144:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17145:                '<br /><br />';
                   17146:      }
1.1075.2.14  raeburn  17147: }
                   17148: 
                   17149: sub check_recaptcha {
1.1075.2.107  raeburn  17150:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17151:     my $captcha_chk;
1.1075.2.107  raeburn  17152:     if ($version >= 2) {
                   17153:         my $ua = LWP::UserAgent->new;
                   17154:         $ua->timeout(10);
                   17155:         my %info = (
                   17156:                      secret   => $privkey,
                   17157:                      response => $env{'form.g-recaptcha-response'},
                   17158:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17159:                    );
                   17160:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17161:         if ($response->is_success)  {
                   17162:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17163:             if (ref($data) eq 'HASH') {
                   17164:                 if ($data->{'success'}) {
                   17165:                     $captcha_chk = 1;
                   17166:                 }
                   17167:             }
                   17168:         }
                   17169:     } else {
                   17170:         my $captcha = Captcha::reCAPTCHA->new;
                   17171:         my $captcha_result =
                   17172:             $captcha->check_answer(
                   17173:                                     $privkey,
                   17174:                                     $ENV{'REMOTE_ADDR'},
                   17175:                                     $env{'form.recaptcha_challenge_field'},
                   17176:                                     $env{'form.recaptcha_response_field'},
                   17177:                                   );
                   17178:         if ($captcha_result->{is_valid}) {
                   17179:             $captcha_chk = 1;
                   17180:         }
1.1075.2.14  raeburn  17181:     }
                   17182:     return $captcha_chk;
                   17183: }
                   17184: 
1.1075.2.64  raeburn  17185: sub emailusername_info {
1.1075.2.103  raeburn  17186:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17187:     my %titles = &Apache::lonlocal::texthash (
                   17188:                      lastname      => 'Last Name',
                   17189:                      firstname     => 'First Name',
                   17190:                      institution   => 'School/college/university',
                   17191:                      location      => "School's city, state/province, country",
                   17192:                      web           => "School's web address",
                   17193:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17194:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17195:                  );
                   17196:     return (\@fields,\%titles);
                   17197: }
                   17198: 
1.1075.2.56  raeburn  17199: sub cleanup_html {
                   17200:     my ($incoming) = @_;
                   17201:     my $outgoing;
                   17202:     if ($incoming ne '') {
                   17203:         $outgoing = $incoming;
                   17204:         $outgoing =~ s/;/&#059;/g;
                   17205:         $outgoing =~ s/\#/&#035;/g;
                   17206:         $outgoing =~ s/\&/&#038;/g;
                   17207:         $outgoing =~ s/</&#060;/g;
                   17208:         $outgoing =~ s/>/&#062;/g;
                   17209:         $outgoing =~ s/\(/&#040/g;
                   17210:         $outgoing =~ s/\)/&#041;/g;
                   17211:         $outgoing =~ s/"/&#034;/g;
                   17212:         $outgoing =~ s/'/&#039;/g;
                   17213:         $outgoing =~ s/\$/&#036;/g;
                   17214:         $outgoing =~ s{/}{&#047;}g;
                   17215:         $outgoing =~ s/=/&#061;/g;
                   17216:         $outgoing =~ s/\\/&#092;/g
                   17217:     }
                   17218:     return $outgoing;
                   17219: }
                   17220: 
1.1075.2.74  raeburn  17221: # Checks for critical messages and returns a redirect url if one exists.
                   17222: # $interval indicates how often to check for messages.
                   17223: sub critical_redirect {
                   17224:     my ($interval) = @_;
                   17225:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17226:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17227:                                         $env{'user.name'});
                   17228:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17229:         my $redirecturl;
                   17230:         if ($what[0]) {
                   17231:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17232:                 $redirecturl='/adm/email?critical=display';
                   17233:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17234:                 return (1, $url);
                   17235:             }
                   17236:         }
                   17237:     }
                   17238:     return ();
                   17239: }
                   17240: 
1.1075.2.64  raeburn  17241: # Use:
                   17242: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17243: #
                   17244: ##################################################
                   17245: #          password associated functions         #
                   17246: ##################################################
                   17247: sub des_keys {
                   17248:     # Make a new key for DES encryption.
                   17249:     # Each key has two parts which are returned separately.
                   17250:     # Please note:  Each key must be passed through the &hex function
                   17251:     # before it is output to the web browser.  The hex versions cannot
                   17252:     # be used to decrypt.
                   17253:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17254:                 '8','9','a','b','c','d','e','f');
                   17255:     my $lkey='';
                   17256:     for (0..7) {
                   17257:         $lkey.=$hexstr[rand(15)];
                   17258:     }
                   17259:     my $ukey='';
                   17260:     for (0..7) {
                   17261:         $ukey.=$hexstr[rand(15)];
                   17262:     }
                   17263:     return ($lkey,$ukey);
                   17264: }
                   17265: 
                   17266: sub des_decrypt {
                   17267:     my ($key,$cyphertext) = @_;
                   17268:     my $keybin=pack("H16",$key);
                   17269:     my $cypher;
                   17270:     if ($Crypt::DES::VERSION>=2.03) {
                   17271:         $cypher=new Crypt::DES $keybin;
                   17272:     } else {
                   17273:         $cypher=new DES $keybin;
                   17274:     }
1.1075.2.106  raeburn  17275:     my $plaintext='';
                   17276:     my $cypherlength = length($cyphertext);
                   17277:     my $numchunks = int($cypherlength/32);
                   17278:     for (my $j=0; $j<$numchunks; $j++) {
                   17279:         my $start = $j*32;
                   17280:         my $cypherblock = substr($cyphertext,$start,32);
                   17281:         my $chunk =
                   17282:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17283:         $chunk .=
                   17284:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17285:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17286:         $plaintext .= $chunk;
                   17287:     }
1.1075.2.64  raeburn  17288:     return $plaintext;
                   17289: }
                   17290: 
1.1075.2.135  raeburn  17291: sub is_nonframeable {
                   17292:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17293:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17294:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17295: 
                   17296:     $remprotocol = lc($remprotocol);
                   17297:     $remhost = lc($remhost);
                   17298:     my $remport = 80;
                   17299:     if ($remprotocol eq 'https') {
                   17300:         $remport = 443;
                   17301:     }
                   17302:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17303:     if ($cached) {
                   17304:         unless ($nocache) {
                   17305:             if ($result) {
                   17306:                 return 1;
                   17307:             } else {
                   17308:                 return 0;
                   17309:             }
                   17310:         }
                   17311:     }
                   17312:     my $uselink;
                   17313:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  17314:     my $ua = LWP::UserAgent->new;
                   17315:     $ua->timeout(5);
                   17316:     my $response=$ua->request($request);
1.1075.2.135  raeburn  17317:     if ($response->is_success()) {
                   17318:         my $secpolicy = lc($response->header('content-security-policy'));
                   17319:         my $xframeop = lc($response->header('x-frame-options'));
                   17320:         $secpolicy =~ s/^\s+|\s+$//g;
                   17321:         $xframeop =~ s/^\s+|\s+$//g;
                   17322:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   17323:             my $remotehost = $remprotocol.'://'.$remhost;
                   17324:             my ($origin,$protocol,$port);
                   17325:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   17326:                 $port = $ENV{'SERVER_PORT'};
                   17327:             } else {
                   17328:                 $port = 80;
                   17329:             }
                   17330:             if ($absolute eq '') {
                   17331:                 $protocol = 'http:';
                   17332:                 if ($port == 443) {
                   17333:                     $protocol = 'https:';
                   17334:                 }
                   17335:                 $origin = $protocol.'//'.lc($hostname);
                   17336:             } else {
                   17337:                 $origin = lc($absolute);
                   17338:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   17339:             }
                   17340:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   17341:                 my $framepolicy = $1;
                   17342:                 $framepolicy =~ s/^\s+|\s+$//g;
                   17343:                 my @policies = split(/\s+/,$framepolicy);
                   17344:                 if (@policies) {
                   17345:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   17346:                         $uselink = 1;
                   17347:                     } else {
                   17348:                         $uselink = 1;
                   17349:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   17350:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   17351:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   17352:                             undef($uselink);
                   17353:                         }
                   17354:                         if ($uselink) {
                   17355:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   17356:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   17357:                                     undef($uselink);
                   17358:                                 }
                   17359:                             }
                   17360:                         }
                   17361:                         if ($uselink) {
                   17362:                             my @possok;
                   17363:                             if ($ip ne '') {
                   17364:                                 push(@possok,$ip);
                   17365:                             }
                   17366:                             my $hoststr = '';
                   17367:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   17368:                                 if ($hoststr eq '') {
                   17369:                                     $hoststr = $part;
                   17370:                                 } else {
                   17371:                                     $hoststr = "$part.$hoststr";
                   17372:                                 }
                   17373:                                 if ($hoststr eq $hostname) {
                   17374:                                     push(@possok,$hostname);
                   17375:                                 } else {
                   17376:                                     push(@possok,"*.$hoststr");
                   17377:                                 }
                   17378:                             }
                   17379:                             if (@possok) {
                   17380:                                 foreach my $poss (@possok) {
                   17381:                                     last if (!$uselink);
                   17382:                                     foreach my $policy (@policies) {
                   17383:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   17384:                                             undef($uselink);
                   17385:                                             last;
                   17386:                                         }
                   17387:                                     }
                   17388:                                 }
                   17389:                             }
                   17390:                         }
                   17391:                     }
                   17392:                 }
                   17393:             } elsif ($xframeop ne '') {
                   17394:                 $uselink = 1;
                   17395:                 my @policies = split(/\s*,\s*/,$xframeop);
                   17396:                 if (@policies) {
                   17397:                     unless (grep(/^deny$/,@policies)) {
                   17398:                         if ($origin ne '') {
                   17399:                             if (grep(/^sameorigin$/,@policies)) {
                   17400:                                 if ($remotehost eq $origin) {
                   17401:                                     undef($uselink);
                   17402:                                 }
                   17403:                             }
                   17404:                             if ($uselink) {
                   17405:                                 foreach my $policy (@policies) {
                   17406:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   17407:                                         my $allowfrom = $1;
                   17408:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   17409:                                             undef($uselink);
                   17410:                                             last;
                   17411:                                         }
                   17412:                                     }
                   17413:                                 }
                   17414:                             }
                   17415:                         }
                   17416:                     }
                   17417:                 }
                   17418:             }
                   17419:         }
                   17420:     }
                   17421:     if ($nocache) {
                   17422:         if ($cached) {
                   17423:             my $devalidate;
                   17424:             if ($uselink && !$result) {
                   17425:                 $devalidate = 1;
                   17426:             } elsif (!$uselink && $result) {
                   17427:                 $devalidate = 1;
                   17428:             }
                   17429:             if ($devalidate) {
                   17430:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   17431:             }
                   17432:         }
                   17433:     } else {
                   17434:         if ($uselink) {
                   17435:             $result = 1;
                   17436:         } else {
                   17437:             $result = 0;
                   17438:         }
                   17439:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   17440:     }
                   17441:     return $uselink;
                   17442: }
                   17443: 
1.112     bowersj2 17444: 1;
                   17445: __END__;
1.41      ng       17446: 

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