![]() ![]() | ![]() |
- For 2.11 Backport 1.1213, 1.1214, 1.1215.
1: # The LearningOnline Network with CAPA 2: # a pile of common routines 3: # 4: # $Id: loncommon.pm,v 1.1075.2.92 2015/04/07 15:13:35 raeburn Exp $ 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: # 28: 29: # Makes a table out of the previous attempts 30: # Inputs result_from_symbread, user, domain, course_id 31: # Reads in non-network-related .tab files 32: 33: # POD header: 34: 35: =pod 36: 37: =head1 NAME 38: 39: Apache::loncommon - pile of common routines 40: 41: =head1 SYNOPSIS 42: 43: Common routines for manipulating connections, student answers, 44: domains, common Javascript fragments, etc. 45: 46: =head1 OVERVIEW 47: 48: A collection of commonly used subroutines that don't have a natural 49: home anywhere else. This collection helps remove 50: redundancy from other modules and increase efficiency of memory usage. 51: 52: =cut 53: 54: # End of POD header 55: package Apache::loncommon; 56: 57: use strict; 58: use Apache::lonnet; 59: use GDBM_File; 60: use POSIX qw(strftime mktime); 61: use Apache::lonmenu(); 62: use Apache::lonenc(); 63: use Apache::lonlocal; 64: use Apache::lonnet(); 65: use HTML::Entities; 66: use Apache::lonhtmlcommon(); 67: use Apache::loncoursedata(); 68: use Apache::lontexconvert(); 69: use Apache::lonclonecourse(); 70: use Apache::lonuserutils(); 71: use Apache::lonuserstate(); 72: use Apache::courseclassifier(); 73: use LONCAPA qw(:DEFAULT :match); 74: use DateTime::TimeZone; 75: use DateTime::Locale::Catalog; 76: use Authen::Captcha; 77: use Captcha::reCAPTCHA; 78: use Crypt::DES; 79: use DynaLoader; # for Crypt::DES version 80: 81: # ---------------------------------------------- Designs 82: use vars qw(%defaultdesign); 83: 84: my $readit; 85: 86: 87: ## 88: ## Global Variables 89: ## 90: 91: 92: # ----------------------------------------------- SSI with retries: 93: # 94: 95: =pod 96: 97: =head1 Server Side include with retries: 98: 99: =over 4 100: 101: =item * &ssi_with_retries(resource,retries form) 102: 103: Performs an ssi with some number of retries. Retries continue either 104: until the result is ok or until the retry count supplied by the 105: caller is exhausted. 106: 107: Inputs: 108: 109: =over 4 110: 111: resource - Identifies the resource to insert. 112: 113: retries - Count of the number of retries allowed. 114: 115: form - Hash that identifies the rendering options. 116: 117: =back 118: 119: Returns: 120: 121: =over 4 122: 123: content - The content of the response. If retries were exhausted this is empty. 124: 125: response - The response from the last attempt (which may or may not have been successful. 126: 127: =back 128: 129: =back 130: 131: =cut 132: 133: sub ssi_with_retries { 134: my ($resource, $retries, %form) = @_; 135: 136: 137: my $ok = 0; # True if we got a good response. 138: my $content; 139: my $response; 140: 141: # Try to get the ssi done. within the retries count: 142: 143: do { 144: ($content, $response) = &Apache::lonnet::ssi($resource, %form); 145: $ok = $response->is_success; 146: if (!$ok) { 147: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message); 148: } 149: $retries--; 150: } while (!$ok && ($retries > 0)); 151: 152: if (!$ok) { 153: $content = ''; # On error return an empty content. 154: } 155: return ($content, $response); 156: 157: } 158: 159: 160: 161: # ----------------------------------------------- Filetypes/Languages/Copyright 162: my %language; 163: my %supported_language; 164: my %latex_language; # For choosing hyphenation in <transl..> 165: my %latex_language_bykey; # for choosing hyphenation from metadata 166: my %cprtag; 167: my %scprtag; 168: my %fe; my %fd; my %fm; 169: my %category_extensions; 170: 171: # ---------------------------------------------- Thesaurus variables 172: # 173: # %Keywords: 174: # A hash used by &keyword to determine if a word is considered a keyword. 175: # $thesaurus_db_file 176: # Scalar containing the full path to the thesaurus database. 177: 178: my %Keywords; 179: my $thesaurus_db_file; 180: 181: # 182: # Initialize values from language.tab, copyright.tab, filetypes.tab, 183: # thesaurus.tab, and filecategories.tab. 184: # 185: BEGIN { 186: # Variable initialization 187: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db"; 188: # 189: unless ($readit) { 190: # ------------------------------------------------------------------- languages 191: { 192: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}. 193: '/language.tab'; 194: if ( open(my $fh,"<$langtabfile") ) { 195: while (my $line = <$fh>) { 196: next if ($line=~/^\#/); 197: chomp($line); 198: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line)); 199: $language{$key}=$val.' - '.$enc; 200: if ($sup) { 201: $supported_language{$key}=$sup; 202: } 203: if ($latex) { 204: $latex_language_bykey{$key} = $latex; 205: $latex_language{$two} = $latex; 206: } 207: } 208: close($fh); 209: } 210: } 211: # ------------------------------------------------------------------ copyrights 212: { 213: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}. 214: '/copyright.tab'; 215: if ( open (my $fh,"<$copyrightfile") ) { 216: while (my $line = <$fh>) { 217: next if ($line=~/^\#/); 218: chomp($line); 219: my ($key,$val)=(split(/\s+/,$line,2)); 220: $cprtag{$key}=$val; 221: } 222: close($fh); 223: } 224: } 225: # ----------------------------------------------------------- source copyrights 226: { 227: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}. 228: '/source_copyright.tab'; 229: if ( open (my $fh,"<$sourcecopyrightfile") ) { 230: while (my $line = <$fh>) { 231: next if ($line =~ /^\#/); 232: chomp($line); 233: my ($key,$val)=(split(/\s+/,$line,2)); 234: $scprtag{$key}=$val; 235: } 236: close($fh); 237: } 238: } 239: 240: # -------------------------------------------------------------- default domain designs 241: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors'; 242: my $designfile = $designdir.'/default.tab'; 243: if ( open (my $fh,"<$designfile") ) { 244: while (my $line = <$fh>) { 245: next if ($line =~ /^\#/); 246: chomp($line); 247: my ($key,$val)=(split(/\=/,$line)); 248: if ($val) { $defaultdesign{$key}=$val; } 249: } 250: close($fh); 251: } 252: 253: # ------------------------------------------------------------- file categories 254: { 255: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}. 256: '/filecategories.tab'; 257: if ( open (my $fh,"<$categoryfile") ) { 258: while (my $line = <$fh>) { 259: next if ($line =~ /^\#/); 260: chomp($line); 261: my ($extension,$category)=(split(/\s+/,$line,2)); 262: push @{$category_extensions{lc($category)}},$extension; 263: } 264: close($fh); 265: } 266: 267: } 268: # ------------------------------------------------------------------ file types 269: { 270: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}. 271: '/filetypes.tab'; 272: if ( open (my $fh,"<$typesfile") ) { 273: while (my $line = <$fh>) { 274: next if ($line =~ /^\#/); 275: chomp($line); 276: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4); 277: if ($descr ne '') { 278: $fe{$ending}=lc($emb); 279: $fd{$ending}=$descr; 280: if ($mime ne 'unk') { $fm{$ending}=$mime; } 281: } 282: } 283: close($fh); 284: } 285: } 286: &Apache::lonnet::logthis( 287: "<span style='color:yellow;'>INFO: Read file types</span>"); 288: $readit=1; 289: } # end of unless($readit) 290: 291: } 292: 293: ############################################################### 294: ## HTML and Javascript Helper Functions ## 295: ############################################################### 296: 297: =pod 298: 299: =head1 HTML and Javascript Functions 300: 301: =over 4 302: 303: =item * &browser_and_searcher_javascript() 304: 305: X<browsing, javascript>X<searching, javascript>Returns a string 306: containing javascript with two functions, C<openbrowser> and 307: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt> 308: tags. 309: 310: =item * &openbrowser(formname,elementname,only,omit) [javascript] 311: 312: inputs: formname, elementname, only, omit 313: 314: formname and elementname indicate the name of the html form and name of 315: the element that the results of the browsing selection are to be placed in. 316: 317: Specifying 'only' will restrict the browser to displaying only files 318: with the given extension. Can be a comma separated list. 319: 320: Specifying 'omit' will restrict the browser to NOT displaying files 321: with the given extension. Can be a comma separated list. 322: 323: =item * &opensearcher(formname,elementname) [javascript] 324: 325: Inputs: formname, elementname 326: 327: formname and elementname specify the name of the html form and the name 328: of the element the selection from the search results will be placed in. 329: 330: =cut 331: 332: sub browser_and_searcher_javascript { 333: my ($mode)=@_; 334: if (!defined($mode)) { $mode='edit'; } 335: my $resurl=&escape_single(&lastresurl()); 336: return <<END; 337: // <!-- BEGIN LON-CAPA Internal 338: var editbrowser = null; 339: function openbrowser(formname,elementname,only,omit,titleelement) { 340: var url = '$resurl/?'; 341: if (editbrowser == null) { 342: url += 'launch=1&'; 343: } 344: url += 'catalogmode=interactive&'; 345: url += 'mode=$mode&'; 346: url += 'inhibitmenu=yes&'; 347: url += 'form=' + formname + '&'; 348: if (only != null) { 349: url += 'only=' + only + '&'; 350: } else { 351: url += 'only=&'; 352: } 353: if (omit != null) { 354: url += 'omit=' + omit + '&'; 355: } else { 356: url += 'omit=&'; 357: } 358: if (titleelement != null) { 359: url += 'titleelement=' + titleelement + '&'; 360: } else { 361: url += 'titleelement=&'; 362: } 363: url += 'element=' + elementname + ''; 364: var title = 'Browser'; 365: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1'; 366: options += ',width=700,height=600'; 367: editbrowser = open(url,title,options,'1'); 368: editbrowser.focus(); 369: } 370: var editsearcher; 371: function opensearcher(formname,elementname,titleelement) { 372: var url = '/adm/searchcat?'; 373: if (editsearcher == null) { 374: url += 'launch=1&'; 375: } 376: url += 'catalogmode=interactive&'; 377: url += 'mode=$mode&'; 378: url += 'form=' + formname + '&'; 379: if (titleelement != null) { 380: url += 'titleelement=' + titleelement + '&'; 381: } else { 382: url += 'titleelement=&'; 383: } 384: url += 'element=' + elementname + ''; 385: var title = 'Search'; 386: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1'; 387: options += ',width=700,height=600'; 388: editsearcher = open(url,title,options,'1'); 389: editsearcher.focus(); 390: } 391: // END LON-CAPA Internal --> 392: END 393: } 394: 395: sub lastresurl { 396: if ($env{'environment.lastresurl'}) { 397: return $env{'environment.lastresurl'} 398: } else { 399: return '/res'; 400: } 401: } 402: 403: sub storeresurl { 404: my $resurl=&Apache::lonnet::clutter(shift); 405: unless ($resurl=~/^\/res/) { return 0; } 406: $resurl=~s/\/$//; 407: &Apache::lonnet::put('environment',{'lastresurl' => $resurl}); 408: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl}); 409: return 1; 410: } 411: 412: sub studentbrowser_javascript { 413: unless ( 414: (($env{'request.course.id'}) && 415: (&Apache::lonnet::allowed('srm',$env{'request.course.id'}) 416: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}. 417: '/'.$env{'request.course.sec'}) 418: )) 419: || ($env{'request.role'}=~/^(au|dc|su)/) 420: ) { return ''; } 421: return (<<'ENDSTDBRW'); 422: <script type="text/javascript" language="Javascript"> 423: // <![CDATA[ 424: var stdeditbrowser; 425: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) { 426: var url = '/adm/pickstudent?'; 427: var filter; 428: if (!ignorefilter) { 429: eval('filter=document.'+formname+'.'+uname+'.value;'); 430: } 431: if (filter != null) { 432: if (filter != '') { 433: url += 'filter='+filter+'&'; 434: } 435: } 436: url += 'form=' + formname + '&unameelement='+uname+ 437: '&udomelement='+udom+ 438: '&clicker='+clicker; 439: if (roleflag) { url+="&roles=1"; } 440: if (courseadvonly) { url+="&courseadvonly=1"; } 441: var title = 'Student_Browser'; 442: var options = 'scrollbars=1,resizable=1,menubar=0'; 443: options += ',width=700,height=600'; 444: stdeditbrowser = open(url,title,options,'1'); 445: stdeditbrowser.focus(); 446: } 447: // ]]> 448: </script> 449: ENDSTDBRW 450: } 451: 452: sub resourcebrowser_javascript { 453: unless ($env{'request.course.id'}) { return ''; } 454: return (<<'ENDRESBRW'); 455: <script type="text/javascript" language="Javascript"> 456: // <![CDATA[ 457: var reseditbrowser; 458: function openresbrowser(formname,reslink) { 459: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink; 460: var title = 'Resource_Browser'; 461: var options = 'scrollbars=1,resizable=1,menubar=0'; 462: options += ',width=700,height=500'; 463: reseditbrowser = open(url,title,options,'1'); 464: reseditbrowser.focus(); 465: } 466: // ]]> 467: </script> 468: ENDRESBRW 469: } 470: 471: sub selectstudent_link { 472: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_; 473: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','". 474: &Apache::lonhtmlcommon::entity_encode($unameele)."','". 475: &Apache::lonhtmlcommon::entity_encode($udomele)."'"; 476: if ($env{'request.course.id'}) { 477: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'}) 478: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}. 479: '/'.$env{'request.course.sec'})) { 480: return ''; 481: } 482: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'"; 483: if ($courseadvonly) { 484: $callargs .= ",'',1,1"; 485: } 486: return '<span class="LC_nobreak">'. 487: '<a href="javascript:openstdbrowser('.$callargs.');">'. 488: &mt('Select User').'</a></span>'; 489: } 490: if ($env{'request.role'}=~/^(au|dc|su)/) { 491: $callargs .= ",'',1"; 492: return '<span class="LC_nobreak">'. 493: '<a href="javascript:openstdbrowser('.$callargs.');">'. 494: &mt('Select User').'</a></span>'; 495: } 496: return ''; 497: } 498: 499: sub selectresource_link { 500: my ($form,$reslink,$arg)=@_; 501: 502: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','". 503: &Apache::lonhtmlcommon::entity_encode($reslink)."'"; 504: unless ($env{'request.course.id'}) { return $arg; } 505: return '<span class="LC_nobreak">'. 506: '<a href="javascript:openresbrowser('.$callargs.');">'. 507: $arg.'</a></span>'; 508: } 509: 510: 511: 512: sub authorbrowser_javascript { 513: return <<"ENDAUTHORBRW"; 514: <script type="text/javascript" language="JavaScript"> 515: // <![CDATA[ 516: var stdeditbrowser; 517: 518: function openauthorbrowser(formname,udom) { 519: var url = '/adm/pickauthor?'; 520: url += 'form='+formname+'&roledom='+udom; 521: var title = 'Author_Browser'; 522: var options = 'scrollbars=1,resizable=1,menubar=0'; 523: options += ',width=700,height=600'; 524: stdeditbrowser = open(url,title,options,'1'); 525: stdeditbrowser.focus(); 526: } 527: 528: // ]]> 529: </script> 530: ENDAUTHORBRW 531: } 532: 533: sub coursebrowser_javascript { 534: my ($domainfilter,$sec_element,$formname,$role_element,$crstype, 535: $credits_element) = @_; 536: my $wintitle = 'Course_Browser'; 537: if ($crstype eq 'Community') { 538: $wintitle = 'Community_Browser'; 539: } 540: my $id_functions = &javascript_index_functions(); 541: my $output = ' 542: <script type="text/javascript" language="JavaScript"> 543: // <![CDATA[ 544: var stdeditbrowser;'."\n"; 545: 546: $output .= <<"ENDSTDBRW"; 547: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) { 548: var url = '/adm/pickcourse?'; 549: var formid = getFormIdByName(formname); 550: var domainfilter = getDomainFromSelectbox(formname,udom); 551: if (domainfilter != null) { 552: if (domainfilter != '') { 553: url += 'domainfilter='+domainfilter+'&'; 554: } 555: } 556: url += 'form=' + formname + '&cnumelement='+uname+ 557: '&cdomelement='+udom+ 558: '&cnameelement='+desc; 559: if (extra_element !=null && extra_element != '') { 560: if (formname == 'rolechoice' || formname == 'studentform') { 561: url += '&roleelement='+extra_element; 562: if (domainfilter == null || domainfilter == '') { 563: url += '&domainfilter='+extra_element; 564: } 565: } 566: else { 567: if (formname == 'portform') { 568: url += '&setroles='+extra_element; 569: } else { 570: if (formname == 'rules') { 571: url += '&fixeddom='+extra_element; 572: } 573: } 574: } 575: } 576: if (type != null && type != '') { 577: url += '&type='+type; 578: } 579: if (type_elem != null && type_elem != '') { 580: url += '&typeelement='+type_elem; 581: } 582: if (formname == 'ccrs') { 583: var ownername = document.forms[formid].ccuname.value; 584: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value; 585: url += '&cloner='+ownername+':'+ownerdom; 586: } 587: if (multflag !=null && multflag != '') { 588: url += '&multiple='+multflag; 589: } 590: var title = '$wintitle'; 591: var options = 'scrollbars=1,resizable=1,menubar=0'; 592: options += ',width=700,height=600'; 593: stdeditbrowser = open(url,title,options,'1'); 594: stdeditbrowser.focus(); 595: } 596: $id_functions 597: ENDSTDBRW 598: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) { 599: $output .= &setsec_javascript($sec_element,$formname,$role_element, 600: $credits_element); 601: } 602: $output .= ' 603: // ]]> 604: </script>'; 605: return $output; 606: } 607: 608: sub javascript_index_functions { 609: return <<"ENDJS"; 610: 611: function getFormIdByName(formname) { 612: for (var i=0;i<document.forms.length;i++) { 613: if (document.forms[i].name == formname) { 614: return i; 615: } 616: } 617: return -1; 618: } 619: 620: function getIndexByName(formid,item) { 621: for (var i=0;i<document.forms[formid].elements.length;i++) { 622: if (document.forms[formid].elements[i].name == item) { 623: return i; 624: } 625: } 626: return -1; 627: } 628: 629: function getDomainFromSelectbox(formname,udom) { 630: var userdom; 631: var formid = getFormIdByName(formname); 632: if (formid > -1) { 633: var domid = getIndexByName(formid,udom); 634: if (domid > -1) { 635: if (document.forms[formid].elements[domid].type == 'select-one') { 636: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value; 637: } 638: if (document.forms[formid].elements[domid].type == 'hidden') { 639: userdom=document.forms[formid].elements[domid].value; 640: } 641: } 642: } 643: return userdom; 644: } 645: 646: ENDJS 647: 648: } 649: 650: sub javascript_array_indexof { 651: return <<ENDJS; 652: <script type="text/javascript" language="JavaScript"> 653: // <![CDATA[ 654: 655: if (!Array.prototype.indexOf) { 656: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { 657: "use strict"; 658: if (this === void 0 || this === null) { 659: throw new TypeError(); 660: } 661: var t = Object(this); 662: var len = t.length >>> 0; 663: if (len === 0) { 664: return -1; 665: } 666: var n = 0; 667: if (arguments.length > 0) { 668: n = Number(arguments[1]); 669: if (n !== n) { // shortcut for verifying if it's NaN 670: n = 0; 671: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) { 672: n = (n > 0 || -1) * Math.floor(Math.abs(n)); 673: } 674: } 675: if (n >= len) { 676: return -1; 677: } 678: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); 679: for (; k < len; k++) { 680: if (k in t && t[k] === searchElement) { 681: return k; 682: } 683: } 684: return -1; 685: } 686: } 687: 688: // ]]> 689: </script> 690: 691: ENDJS 692: 693: } 694: 695: sub userbrowser_javascript { 696: my $id_functions = &javascript_index_functions(); 697: return <<"ENDUSERBRW"; 698: 699: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) { 700: var url = '/adm/pickuser?'; 701: var userdom = getDomainFromSelectbox(formname,udom); 702: if (userdom != null) { 703: if (userdom != '') { 704: url += 'srchdom='+userdom+'&'; 705: } 706: } 707: url += 'form=' + formname + '&unameelement='+uname+ 708: '&udomelement='+udom+ 709: '&ulastelement='+ulast+ 710: '&ufirstelement='+ufirst+ 711: '&uemailelement='+uemail+ 712: '&hideudomelement='+hideudom+ 713: '&coursedom='+crsdom; 714: if ((caller != null) && (caller != undefined)) { 715: url += '&caller='+caller; 716: } 717: var title = 'User_Browser'; 718: var options = 'scrollbars=1,resizable=1,menubar=0'; 719: options += ',width=700,height=600'; 720: var stdeditbrowser = open(url,title,options,'1'); 721: stdeditbrowser.focus(); 722: } 723: 724: function fix_domain (formname,udom,origdom,uname) { 725: var formid = getFormIdByName(formname); 726: if (formid > -1) { 727: var unameid = getIndexByName(formid,uname); 728: var domid = getIndexByName(formid,udom); 729: var hidedomid = getIndexByName(formid,origdom); 730: if (hidedomid > -1) { 731: var fixeddom = document.forms[formid].elements[hidedomid].value; 732: var unameval = document.forms[formid].elements[unameid].value; 733: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) { 734: if (domid > -1) { 735: var slct = document.forms[formid].elements[domid]; 736: if (slct.type == 'select-one') { 737: var i; 738: for (i=0;i<slct.length;i++) { 739: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; } 740: } 741: } 742: if (slct.type == 'hidden') { 743: slct.value = fixeddom; 744: } 745: } 746: } 747: } 748: } 749: return; 750: } 751: 752: $id_functions 753: ENDUSERBRW 754: } 755: 756: sub setsec_javascript { 757: my ($sec_element,$formname,$role_element,$credits_element) = @_; 758: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr, 759: $communityrolestr); 760: if ($role_element ne '') { 761: my @allroles = ('st','ta','ep','in','ad'); 762: foreach my $crstype ('Course','Community') { 763: if ($crstype eq 'Community') { 764: foreach my $role (@allroles) { 765: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype)); 766: } 767: push(@communityrolenames,&Apache::lonnet::plaintext('co')); 768: } else { 769: foreach my $role (@allroles) { 770: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype)); 771: } 772: push(@courserolenames,&Apache::lonnet::plaintext('cc')); 773: } 774: } 775: $rolestr = '"'.join('","',@allroles).'"'; 776: $courserolestr = '"'.join('","',@courserolenames).'"'; 777: $communityrolestr = '"'.join('","',@communityrolenames).'"'; 778: } 779: my $setsections = qq| 780: function setSect(sectionlist) { 781: var sectionsArray = new Array(); 782: if ((sectionlist != '') && (typeof sectionlist != "undefined")) { 783: sectionsArray = sectionlist.split(","); 784: } 785: var numSections = sectionsArray.length; 786: document.$formname.$sec_element.length = 0; 787: if (numSections == 0) { 788: document.$formname.$sec_element.multiple=false; 789: document.$formname.$sec_element.size=1; 790: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false) 791: } else { 792: if (numSections == 1) { 793: document.$formname.$sec_element.multiple=false; 794: document.$formname.$sec_element.size=1; 795: document.$formname.$sec_element.options[0] = new Option('Select','',true,true); 796: document.$formname.$sec_element.options[1] = new Option('No section','',false,false) 797: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false); 798: } else { 799: for (var i=0; i<numSections; i++) { 800: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false) 801: } 802: document.$formname.$sec_element.multiple=true 803: if (numSections < 3) { 804: document.$formname.$sec_element.size=numSections; 805: } else { 806: document.$formname.$sec_element.size=3; 807: } 808: document.$formname.$sec_element.options[0].selected = false 809: } 810: } 811: } 812: 813: function setRole(crstype) { 814: |; 815: if ($role_element eq '') { 816: $setsections .= ' return; 817: } 818: '; 819: } else { 820: $setsections .= qq| 821: var elementLength = document.$formname.$role_element.length; 822: var allroles = Array($rolestr); 823: var courserolenames = Array($courserolestr); 824: var communityrolenames = Array($communityrolestr); 825: if (elementLength != undefined) { 826: if (document.$formname.$role_element.options[5].value == 'cc') { 827: if (crstype == 'Course') { 828: return; 829: } else { 830: allroles[5] = 'co'; 831: for (var i=0; i<6; i++) { 832: document.$formname.$role_element.options[i].value = allroles[i]; 833: document.$formname.$role_element.options[i].text = communityrolenames[i]; 834: } 835: } 836: } else { 837: if (crstype == 'Community') { 838: return; 839: } else { 840: allroles[5] = 'cc'; 841: for (var i=0; i<6; i++) { 842: document.$formname.$role_element.options[i].value = allroles[i]; 843: document.$formname.$role_element.options[i].text = courserolenames[i]; 844: } 845: } 846: } 847: } 848: return; 849: } 850: |; 851: } 852: if ($credits_element) { 853: $setsections .= qq| 854: function setCredits(defaultcredits) { 855: document.$formname.$credits_element.value = defaultcredits; 856: return; 857: } 858: |; 859: } 860: return $setsections; 861: } 862: 863: sub selectcourse_link { 864: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype, 865: $typeelement) = @_; 866: my $type = $selecttype; 867: my $linktext = &mt('Select Course'); 868: if ($selecttype eq 'Community') { 869: $linktext = &mt('Select Community'); 870: } elsif ($selecttype eq 'Course/Community') { 871: $linktext = &mt('Select Course/Community'); 872: $type = ''; 873: } elsif ($selecttype eq 'Select') { 874: $linktext = &mt('Select'); 875: $type = ''; 876: } 877: return '<span class="LC_nobreak">' 878: ."<a href='" 879: .'javascript:opencrsbrowser("'.$form.'","'.$unameele 880: .'","'.$udomele.'","'.$desc.'","'.$extra_element 881: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");' 882: ."'>".$linktext.'</a>' 883: .'</span>'; 884: } 885: 886: sub selectauthor_link { 887: my ($form,$udom)=@_; 888: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'. 889: &mt('Select Author').'</a>'; 890: } 891: 892: sub selectuser_link { 893: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem, 894: $coursedom,$linktext,$caller) = @_; 895: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',". 896: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'". 897: ');">'.$linktext.'</a>'; 898: } 899: 900: sub check_uncheck_jscript { 901: my $jscript = <<"ENDSCRT"; 902: function checkAll(field) { 903: if (field.length > 0) { 904: for (i = 0; i < field.length; i++) { 905: if (!field[i].disabled) { 906: field[i].checked = true; 907: } 908: } 909: } else { 910: if (!field.disabled) { 911: field.checked = true; 912: } 913: } 914: } 915: 916: function uncheckAll(field) { 917: if (field.length > 0) { 918: for (i = 0; i < field.length; i++) { 919: field[i].checked = false ; 920: } 921: } else { 922: field.checked = false ; 923: } 924: } 925: ENDSCRT 926: return $jscript; 927: } 928: 929: sub select_timezone { 930: my ($name,$selected,$onchange,$includeempty)=@_; 931: my $output='<select name="'.$name.'" '.$onchange.'>'."\n"; 932: if ($includeempty) { 933: $output .= '<option value=""'; 934: if (($selected eq '') || ($selected eq 'local')) { 935: $output .= ' selected="selected" '; 936: } 937: $output .= '> </option>'; 938: } 939: my @timezones = DateTime::TimeZone->all_names; 940: foreach my $tzone (@timezones) { 941: $output.= '<option value="'.$tzone.'"'; 942: if ($tzone eq $selected) { 943: $output.=' selected="selected"'; 944: } 945: $output.=">$tzone</option>\n"; 946: } 947: $output.="</select>"; 948: return $output; 949: } 950: 951: sub select_datelocale { 952: my ($name,$selected,$onchange,$includeempty)=@_; 953: my $output='<select name="'.$name.'" '.$onchange.'>'."\n"; 954: if ($includeempty) { 955: $output .= '<option value=""'; 956: if ($selected eq '') { 957: $output .= ' selected="selected" '; 958: } 959: $output .= '> </option>'; 960: } 961: my (@possibles,%locale_names); 962: my @locales = DateTime::Locale::Catalog::Locales; 963: foreach my $locale (@locales) { 964: if (ref($locale) eq 'HASH') { 965: my $id = $locale->{'id'}; 966: if ($id ne '') { 967: my $en_terr = $locale->{'en_territory'}; 968: my $native_terr = $locale->{'native_territory'}; 969: my @languages = &Apache::lonlocal::preferred_languages(); 970: if (grep(/^en$/,@languages) || !@languages) { 971: if ($en_terr ne '') { 972: $locale_names{$id} = '('.$en_terr.')'; 973: } elsif ($native_terr ne '') { 974: $locale_names{$id} = $native_terr; 975: } 976: } else { 977: if ($native_terr ne '') { 978: $locale_names{$id} = $native_terr.' '; 979: } elsif ($en_terr ne '') { 980: $locale_names{$id} = '('.$en_terr.')'; 981: } 982: } 983: push (@possibles,$id); 984: } 985: } 986: } 987: foreach my $item (sort(@possibles)) { 988: $output.= '<option value="'.$item.'"'; 989: if ($item eq $selected) { 990: $output.=' selected="selected"'; 991: } 992: $output.=">$item"; 993: if ($locale_names{$item} ne '') { 994: $output.=" $locale_names{$item}</option>\n"; 995: } 996: $output.="</option>\n"; 997: } 998: $output.="</select>"; 999: return $output; 1000: } 1001: 1002: sub select_language { 1003: my ($name,$selected,$includeempty) = @_; 1004: my %langchoices; 1005: if ($includeempty) { 1006: %langchoices = ('' => 'No language preference'); 1007: } 1008: foreach my $id (&languageids()) { 1009: my $code = &supportedlanguagecode($id); 1010: if ($code) { 1011: $langchoices{$code} = &plainlanguagedescription($id); 1012: } 1013: } 1014: %langchoices = &Apache::lonlocal::texthash(%langchoices); 1015: return &select_form($selected,$name,\%langchoices); 1016: } 1017: 1018: =pod 1019: 1020: =item * &linked_select_forms(...) 1021: 1022: linked_select_forms returns a string containing a <script></script> block 1023: and html for two <select> menus. The select menus will be linked in that 1024: changing the value of the first menu will result in new values being placed 1025: in the second menu. The values in the select menu will appear in alphabetical 1026: order unless a defined order is provided. 1027: 1028: linked_select_forms takes the following ordered inputs: 1029: 1030: =over 4 1031: 1032: =item * $formname, the name of the <form> tag 1033: 1034: =item * $middletext, the text which appears between the <select> tags 1035: 1036: =item * $firstdefault, the default value for the first menu 1037: 1038: =item * $firstselectname, the name of the first <select> tag 1039: 1040: =item * $secondselectname, the name of the second <select> tag 1041: 1042: =item * $hashref, a reference to a hash containing the data for the menus. 1043: 1044: =item * $menuorder, the order of values in the first menu 1045: 1046: =item * $onchangefirst, additional javascript call to execute for an onchange 1047: event for the first <select> tag 1048: 1049: =item * $onchangesecond, additional javascript call to execute for an onchange 1050: event for the second <select> tag 1051: 1052: =back 1053: 1054: Below is an example of such a hash. Only the 'text', 'default', and 1055: 'select2' keys must appear as stated. keys(%menu) are the possible 1056: values for the first select menu. The text that coincides with the 1057: first menu value is given in $menu{$choice1}->{'text'}. The values 1058: and text for the second menu are given in the hash pointed to by 1059: $menu{$choice1}->{'select2'}. 1060: 1061: my %menu = ( A1 => { text =>"Choice A1" , 1062: default => "B3", 1063: select2 => { 1064: B1 => "Choice B1", 1065: B2 => "Choice B2", 1066: B3 => "Choice B3", 1067: B4 => "Choice B4" 1068: }, 1069: order => ['B4','B3','B1','B2'], 1070: }, 1071: A2 => { text =>"Choice A2" , 1072: default => "C2", 1073: select2 => { 1074: C1 => "Choice C1", 1075: C2 => "Choice C2", 1076: C3 => "Choice C3" 1077: }, 1078: order => ['C2','C1','C3'], 1079: }, 1080: A3 => { text =>"Choice A3" , 1081: default => "D6", 1082: select2 => { 1083: D1 => "Choice D1", 1084: D2 => "Choice D2", 1085: D3 => "Choice D3", 1086: D4 => "Choice D4", 1087: D5 => "Choice D5", 1088: D6 => "Choice D6", 1089: D7 => "Choice D7" 1090: }, 1091: order => ['D4','D3','D2','D1','D7','D6','D5'], 1092: } 1093: ); 1094: 1095: =cut 1096: 1097: sub linked_select_forms { 1098: my ($formname, 1099: $middletext, 1100: $firstdefault, 1101: $firstselectname, 1102: $secondselectname, 1103: $hashref, 1104: $menuorder, 1105: $onchangefirst, 1106: $onchangesecond 1107: ) = @_; 1108: my $second = "document.$formname.$secondselectname"; 1109: my $first = "document.$formname.$firstselectname"; 1110: # output the javascript to do the changing 1111: my $result = ''; 1112: $result.='<script type="text/javascript" language="JavaScript">'."\n"; 1113: $result.="// <![CDATA[\n"; 1114: $result.="var select2data = new Object();\n"; 1115: $" = '","'; 1116: my $debug = ''; 1117: foreach my $s1 (sort(keys(%$hashref))) { 1118: $result.="select2data.d_$s1 = new Object();\n"; 1119: $result.="select2data.d_$s1.def = new String('". 1120: $hashref->{$s1}->{'default'}."');\n"; 1121: $result.="select2data.d_$s1.values = new Array("; 1122: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } )); 1123: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') { 1124: @s2values = @{$hashref->{$s1}->{'order'}}; 1125: } 1126: $result.="\"@s2values\");\n"; 1127: $result.="select2data.d_$s1.texts = new Array("; 1128: my @s2texts; 1129: foreach my $value (@s2values) { 1130: push @s2texts, $hashref->{$s1}->{'select2'}->{$value}; 1131: } 1132: $result.="\"@s2texts\");\n"; 1133: } 1134: $"=' '; 1135: $result.= <<"END"; 1136: 1137: function select1_changed() { 1138: // Determine new choice 1139: var newvalue = "d_" + $first.value; 1140: // update select2 1141: var values = select2data[newvalue].values; 1142: var texts = select2data[newvalue].texts; 1143: var select2def = select2data[newvalue].def; 1144: var i; 1145: // out with the old 1146: for (i = 0; i < $second.options.length; i++) { 1147: $second.options[i] = null; 1148: } 1149: // in with the nuclear 1150: for (i=0;i<values.length; i++) { 1151: $second.options[i] = new Option(values[i]); 1152: $second.options[i].value = values[i]; 1153: $second.options[i].text = texts[i]; 1154: if (values[i] == select2def) { 1155: $second.options[i].selected = true; 1156: } 1157: } 1158: } 1159: // ]]> 1160: </script> 1161: END 1162: # output the initial values for the selection lists 1163: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n"; 1164: my @order = sort(keys(%{$hashref})); 1165: if (ref($menuorder) eq 'ARRAY') { 1166: @order = @{$menuorder}; 1167: } 1168: foreach my $value (@order) { 1169: $result.=" <option value=\"$value\" "; 1170: $result.=" selected=\"selected\" " if ($value eq $firstdefault); 1171: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n"; 1172: } 1173: $result .= "</select>\n"; 1174: my %select2 = %{$hashref->{$firstdefault}->{'select2'}}; 1175: $result .= $middletext; 1176: $result .= "<select size=\"1\" name=\"$secondselectname\""; 1177: if ($onchangesecond) { 1178: $result .= ' onchange="'.$onchangesecond.'"'; 1179: } 1180: $result .= ">\n"; 1181: my $seconddefault = $hashref->{$firstdefault}->{'default'}; 1182: 1183: my @secondorder = sort(keys(%select2)); 1184: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') { 1185: @secondorder = @{$hashref->{$firstdefault}->{'order'}}; 1186: } 1187: foreach my $value (@secondorder) { 1188: $result.=" <option value=\"$value\" "; 1189: $result.=" selected=\"selected\" " if ($value eq $seconddefault); 1190: $result.=">".&mt($select2{$value})."</option>\n"; 1191: } 1192: $result .= "</select>\n"; 1193: # return $debug; 1194: return $result; 1195: } # end of sub linked_select_forms { 1196: 1197: =pod 1198: 1199: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid) 1200: 1201: Returns a string corresponding to an HTML link to the given help 1202: $topic, where $topic corresponds to the name of a .tex file in 1203: /home/httpd/html/adm/help/tex, with underscores replaced by 1204: spaces. 1205: 1206: $text will optionally be linked to the same topic, allowing you to 1207: link text in addition to the graphic. If you do not want to link 1208: text, but wish to specify one of the later parameters, pass an 1209: empty string. 1210: 1211: $stayOnPage is a value that will be interpreted as a boolean. If true, 1212: the link will not open a new window. If false, the link will open 1213: a new window using Javascript. (Default is false.) 1214: 1215: $width and $height are optional numerical parameters that will 1216: override the width and height of the popped up window, which may 1217: be useful for certain help topics with big pictures included. 1218: 1219: $imgid is the id of the img tag used for the help icon. This may be 1220: used in a javascript call to switch the image src. See 1221: lonhtmlcommon::htmlareaselectactive() for an example. 1222: 1223: =cut 1224: 1225: sub help_open_topic { 1226: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_; 1227: $text = "" if (not defined $text); 1228: $stayOnPage = 0 if (not defined $stayOnPage); 1229: $width = 500 if (not defined $width); 1230: $height = 400 if (not defined $height); 1231: my $filename = $topic; 1232: $filename =~ s/ /_/g; 1233: 1234: my $template = ""; 1235: my $link; 1236: 1237: $topic=~s/\W/\_/g; 1238: 1239: if (!$stayOnPage) { 1240: if ($env{'browser.mobile'}) { 1241: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');"; 1242: } else { 1243: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; 1244: } 1245: } elsif ($stayOnPage eq 'popup') { 1246: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; 1247: } else { 1248: $link = "/adm/help/${filename}.hlp"; 1249: } 1250: 1251: # Add the text 1252: if ($text ne "") { 1253: $template.='<span class="LC_help_open_topic">' 1254: .'<a target="_top" href="'.$link.'">' 1255: .$text.'</a>'; 1256: } 1257: 1258: # (Always) Add the graphic 1259: my $title = &mt('Online Help'); 1260: my $helpicon=&lonhttpdurl("/adm/help/help.png"); 1261: if ($imgid ne '') { 1262: $imgid = ' id="'.$imgid.'"'; 1263: } 1264: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">' 1265: .'<img src="'.$helpicon.'" border="0"' 1266: .' alt="'.&mt('Help: [_1]',$topic).'"' 1267: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 1268: .' /></a>'; 1269: if ($text ne "") { 1270: $template.='</span>'; 1271: } 1272: return $template; 1273: 1274: } 1275: 1276: # This is a quicky function for Latex cheatsheet editing, since it 1277: # appears in at least four places 1278: sub helpLatexCheatsheet { 1279: my ($topic,$text,$not_author,$stayOnPage) = @_; 1280: my $out; 1281: my $addOther = ''; 1282: if ($topic) { 1283: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> '; 1284: } 1285: $out = '<span>' # Start cheatsheet 1286: .$addOther 1287: .'<span>' 1288: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600) 1289: .'</span> <span>' 1290: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600) 1291: .'</span>'; 1292: unless ($not_author) { 1293: $out .= ' <span>' 1294: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600) 1295: .'</span> <span>' 1296: .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600) 1297: .'</span>'; 1298: } 1299: $out .= '</span>'; # End cheatsheet 1300: return $out; 1301: } 1302: 1303: sub general_help { 1304: my $helptopic='Student_Intro'; 1305: if ($env{'request.role'}=~/^(ca|au)/) { 1306: $helptopic='Authoring_Intro'; 1307: } elsif ($env{'request.role'}=~/^(cc|co)/) { 1308: $helptopic='Course_Coordination_Intro'; 1309: } elsif ($env{'request.role'}=~/^dc/) { 1310: $helptopic='Domain_Coordination_Intro'; 1311: } 1312: return $helptopic; 1313: } 1314: 1315: sub update_help_link { 1316: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_; 1317: my $origurl = $ENV{'REQUEST_URI'}; 1318: $origurl=~s|^/~|/priv/|; 1319: my $timestamp = time; 1320: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) { 1321: $$datum = &escape($$datum); 1322: } 1323: 1324: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage"; 1325: my $output .= <<"ENDOUTPUT"; 1326: <script type="text/javascript"> 1327: // <![CDATA[ 1328: banner_link = '$banner_link'; 1329: // ]]> 1330: </script> 1331: ENDOUTPUT 1332: return $output; 1333: } 1334: 1335: # now just updates the help link and generates a blue icon 1336: sub help_open_menu { 1337: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 1338: = @_; 1339: $stayOnPage = 1; 1340: my $output; 1341: if ($component_help) { 1342: if (!$text) { 1343: $output=&help_open_topic($component_help,undef,$stayOnPage, 1344: $width,$height); 1345: } else { 1346: my $help_text; 1347: $help_text=&unescape($topic); 1348: $output='<table><tr><td>'. 1349: &help_open_topic($component_help,$help_text,$stayOnPage, 1350: $width,$height).'</td></tr></table>'; 1351: } 1352: } 1353: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage); 1354: return $output.$banner_link; 1355: } 1356: 1357: sub top_nav_help { 1358: my ($text) = @_; 1359: $text = &mt($text); 1360: my $stay_on_page; 1361: unless ($env{'environment.remote'} eq 'on') { 1362: $stay_on_page = 1; 1363: } 1364: my ($link,$banner_link); 1365: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) { 1366: $link = ($stay_on_page) ? "javascript:helpMenu('display')" 1367: : "javascript:helpMenu('open')"; 1368: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page); 1369: } 1370: my $title = &mt('Get help'); 1371: if ($link) { 1372: return <<"END"; 1373: $banner_link 1374: <a href="$link" title="$title">$text</a> 1375: END 1376: } else { 1377: return ' '.$text.' '; 1378: } 1379: } 1380: 1381: sub help_menu_js { 1382: my ($httphost) = @_; 1383: my $stayOnPage = 1; 1384: my $width = 620; 1385: my $height = 600; 1386: my $helptopic=&general_help(); 1387: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp'; 1388: my $nothing=&Apache::lonhtmlcommon::javascript_nothing(); 1389: my $start_page = 1390: &Apache::loncommon::start_page('Help Menu', undef, 1391: {'frameset' => 1, 1392: 'js_ready' => 1, 1393: 'use_absolute' => $httphost, 1394: 'add_entries' => { 1395: 'border' => '0', 1396: 'rows' => "110,*",},}); 1397: my $end_page = 1398: &Apache::loncommon::end_page({'frameset' => 1, 1399: 'js_ready' => 1,}); 1400: 1401: my $template .= <<"ENDTEMPLATE"; 1402: <script type="text/javascript"> 1403: // <![CDATA[ 1404: // <!-- BEGIN LON-CAPA Internal 1405: var banner_link = ''; 1406: function helpMenu(target) { 1407: var caller = this; 1408: if (target == 'open') { 1409: var newWindow = null; 1410: try { 1411: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" ) 1412: } 1413: catch(error) { 1414: writeHelp(caller); 1415: return; 1416: } 1417: if (newWindow) { 1418: caller = newWindow; 1419: } 1420: } 1421: writeHelp(caller); 1422: return; 1423: } 1424: function writeHelp(caller) { 1425: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n'); 1426: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page'); 1427: caller.document.close(); 1428: caller.focus(); 1429: } 1430: // END LON-CAPA Internal --> 1431: // ]]> 1432: </script> 1433: ENDTEMPLATE 1434: return $template; 1435: } 1436: 1437: sub help_open_bug { 1438: my ($topic, $text, $stayOnPage, $width, $height) = @_; 1439: unless ($env{'user.adv'}) { return ''; } 1440: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; } 1441: $text = "" if (not defined $text); 1442: $stayOnPage=1; 1443: $width = 600 if (not defined $width); 1444: $height = 600 if (not defined $height); 1445: 1446: $topic=~s/\W+/\+/g; 1447: my $link=''; 1448: my $template=''; 1449: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='. 1450: &escape($ENV{'REQUEST_URI'}).'&component='.$topic; 1451: if (!$stayOnPage) 1452: { 1453: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; 1454: } 1455: else 1456: { 1457: $link = $url; 1458: } 1459: # Add the text 1460: if ($text ne "") 1461: { 1462: $template .= 1463: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>". 1464: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>"; 1465: } 1466: 1467: # Add the graphic 1468: my $title = &mt('Report a Bug'); 1469: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif"); 1470: $template .= <<"ENDTEMPLATE"; 1471: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a> 1472: ENDTEMPLATE 1473: if ($text ne '') { $template.='</td></tr></table>' }; 1474: return $template; 1475: 1476: } 1477: 1478: sub help_open_faq { 1479: my ($topic, $text, $stayOnPage, $width, $height) = @_; 1480: unless ($env{'user.adv'}) { return ''; } 1481: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; } 1482: $text = "" if (not defined $text); 1483: $stayOnPage=1; 1484: $width = 350 if (not defined $width); 1485: $height = 400 if (not defined $height); 1486: 1487: $topic=~s/\W+/\+/g; 1488: my $link=''; 1489: my $template=''; 1490: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html'; 1491: if (!$stayOnPage) 1492: { 1493: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; 1494: } 1495: else 1496: { 1497: $link = $url; 1498: } 1499: 1500: # Add the text 1501: if ($text ne "") 1502: { 1503: $template .= 1504: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>". 1505: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>"; 1506: } 1507: 1508: # Add the graphic 1509: my $title = &mt('View the FAQ'); 1510: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif"); 1511: $template .= <<"ENDTEMPLATE"; 1512: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a> 1513: ENDTEMPLATE 1514: if ($text ne '') { $template.='</td></tr></table>' }; 1515: return $template; 1516: 1517: } 1518: 1519: ############################################################### 1520: ############################################################### 1521: 1522: =pod 1523: 1524: =item * &change_content_javascript(): 1525: 1526: This and the next function allow you to create small sections of an 1527: otherwise static HTML page that you can update on the fly with 1528: Javascript, even in Netscape 4. 1529: 1530: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag) 1531: must be written to the HTML page once. It will prove the Javascript 1532: function "change(name, content)". Calling the change function with the 1533: name of the section 1534: you want to update, matching the name passed to C<changable_area>, and 1535: the new content you want to put in there, will put the content into 1536: that area. 1537: 1538: B<Note>: Netscape 4 only reserves enough space for the changable area 1539: to contain room for the original contents. You need to "make space" 1540: for whatever changes you wish to make, and be B<sure> to check your 1541: code in Netscape 4. This feature in Netscape 4 is B<not> powerful; 1542: it's adequate for updating a one-line status display, but little more. 1543: This script will set the space to 100% width, so you only need to 1544: worry about height in Netscape 4. 1545: 1546: Modern browsers are much less limiting, and if you can commit to the 1547: user not using Netscape 4, this feature may be used freely with 1548: pretty much any HTML. 1549: 1550: =cut 1551: 1552: sub change_content_javascript { 1553: # If we're on Netscape 4, we need to use Layer-based code 1554: if ($env{'browser.type'} eq 'netscape' && 1555: $env{'browser.version'} =~ /^4\./) { 1556: return (<<NETSCAPE4); 1557: function change(name, content) { 1558: doc = document.layers[name+"___escape"].layers[0].document; 1559: doc.open(); 1560: doc.write(content); 1561: doc.close(); 1562: } 1563: NETSCAPE4 1564: } else { 1565: # Otherwise, we need to use semi-standards-compliant code 1566: # (technically, "innerHTML" isn't standard but the equivalent 1567: # is really scary, and every useful browser supports it 1568: return (<<DOMBASED); 1569: function change(name, content) { 1570: element = document.getElementById(name); 1571: element.innerHTML = content; 1572: } 1573: DOMBASED 1574: } 1575: } 1576: 1577: =pod 1578: 1579: =item * &changable_area($name,$origContent): 1580: 1581: This provides a "changable area" that can be modified on the fly via 1582: the Javascript code provided in C<change_content_javascript>. $name is 1583: the name you will use to reference the area later; do not repeat the 1584: same name on a given HTML page more then once. $origContent is what 1585: the area will originally contain, which can be left blank. 1586: 1587: =cut 1588: 1589: sub changable_area { 1590: my ($name, $origContent) = @_; 1591: 1592: if ($env{'browser.type'} eq 'netscape' && 1593: $env{'browser.version'} =~ /^4\./) { 1594: # If this is netscape 4, we need to use the Layer tag 1595: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>"; 1596: } else { 1597: return "<span id='$name'>$origContent</span>"; 1598: } 1599: } 1600: 1601: =pod 1602: 1603: =item * &viewport_geometry_js 1604: 1605: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser. 1606: 1607: =cut 1608: 1609: 1610: sub viewport_geometry_js { 1611: return <<"GEOMETRY"; 1612: var Geometry = {}; 1613: function init_geometry() { 1614: if (Geometry.init) { return }; 1615: Geometry.init=1; 1616: if (window.innerHeight) { 1617: Geometry.getViewportHeight = function() { return window.innerHeight; }; 1618: Geometry.getViewportWidth = function() { return window.innerWidth; }; 1619: Geometry.getHorizontalScroll = function() { return window.pageXOffset; }; 1620: Geometry.getVerticalScroll = function() { return window.pageYOffset; }; 1621: } 1622: else if (document.documentElement && document.documentElement.clientHeight) { 1623: Geometry.getViewportHeight = 1624: function() { return document.documentElement.clientHeight; }; 1625: Geometry.getViewportWidth = 1626: function() { return document.documentElement.clientWidth; }; 1627: 1628: Geometry.getHorizontalScroll = 1629: function() { return document.documentElement.scrollLeft; }; 1630: Geometry.getVerticalScroll = 1631: function() { return document.documentElement.scrollTop; }; 1632: } 1633: else if (document.body.clientHeight) { 1634: Geometry.getViewportHeight = 1635: function() { return document.body.clientHeight; }; 1636: Geometry.getViewportWidth = 1637: function() { return document.body.clientWidth; }; 1638: Geometry.getHorizontalScroll = 1639: function() { return document.body.scrollLeft; }; 1640: Geometry.getVerticalScroll = 1641: function() { return document.body.scrollTop; }; 1642: } 1643: } 1644: 1645: GEOMETRY 1646: } 1647: 1648: =pod 1649: 1650: =item * &viewport_size_js() 1651: 1652: 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. 1653: 1654: =cut 1655: 1656: sub viewport_size_js { 1657: my $geometry = &viewport_geometry_js(); 1658: return <<"DIMS"; 1659: 1660: $geometry 1661: 1662: function getViewportDims(width,height) { 1663: init_geometry(); 1664: width.value = Geometry.getViewportWidth(); 1665: height.value = Geometry.getViewportHeight(); 1666: return; 1667: } 1668: 1669: DIMS 1670: } 1671: 1672: =pod 1673: 1674: =item * &resize_textarea_js() 1675: 1676: emits the needed javascript to resize a textarea to be as big as possible 1677: 1678: creates a function resize_textrea that takes two IDs first should be 1679: the id of the element to resize, second should be the id of a div that 1680: surrounds everything that comes after the textarea, this routine needs 1681: to be attached to the <body> for the onload and onresize events. 1682: 1683: =back 1684: 1685: =cut 1686: 1687: sub resize_textarea_js { 1688: my $geometry = &viewport_geometry_js(); 1689: return <<"RESIZE"; 1690: <script type="text/javascript"> 1691: // <![CDATA[ 1692: $geometry 1693: 1694: function getX(element) { 1695: var x = 0; 1696: while (element) { 1697: x += element.offsetLeft; 1698: element = element.offsetParent; 1699: } 1700: return x; 1701: } 1702: function getY(element) { 1703: var y = 0; 1704: while (element) { 1705: y += element.offsetTop; 1706: element = element.offsetParent; 1707: } 1708: return y; 1709: } 1710: 1711: 1712: function resize_textarea(textarea_id,bottom_id) { 1713: init_geometry(); 1714: var textarea = document.getElementById(textarea_id); 1715: //alert(textarea); 1716: 1717: var textarea_top = getY(textarea); 1718: var textarea_height = textarea.offsetHeight; 1719: var bottom = document.getElementById(bottom_id); 1720: var bottom_top = getY(bottom); 1721: var bottom_height = bottom.offsetHeight; 1722: var window_height = Geometry.getViewportHeight(); 1723: var fudge = 23; 1724: var new_height = window_height-fudge-textarea_top-bottom_height; 1725: if (new_height < 300) { 1726: new_height = 300; 1727: } 1728: textarea.style.height=new_height+'px'; 1729: } 1730: // ]]> 1731: </script> 1732: RESIZE 1733: 1734: } 1735: 1736: =pod 1737: 1738: =head1 Excel and CSV file utility routines 1739: 1740: =cut 1741: 1742: ############################################################### 1743: ############################################################### 1744: 1745: =pod 1746: 1747: =over 4 1748: 1749: =item * &csv_translate($text) 1750: 1751: Translate $text to allow it to be output as a 'comma separated values' 1752: format. 1753: 1754: =cut 1755: 1756: ############################################################### 1757: ############################################################### 1758: sub csv_translate { 1759: my $text = shift; 1760: $text =~ s/\"/\"\"/g; 1761: $text =~ s/\n/ /g; 1762: return $text; 1763: } 1764: 1765: ############################################################### 1766: ############################################################### 1767: 1768: =pod 1769: 1770: =item * &define_excel_formats() 1771: 1772: Define some commonly used Excel cell formats. 1773: 1774: Currently supported formats: 1775: 1776: =over 4 1777: 1778: =item header 1779: 1780: =item bold 1781: 1782: =item h1 1783: 1784: =item h2 1785: 1786: =item h3 1787: 1788: =item h4 1789: 1790: =item i 1791: 1792: =item date 1793: 1794: =back 1795: 1796: Inputs: $workbook 1797: 1798: Returns: $format, a hash reference. 1799: 1800: 1801: =cut 1802: 1803: ############################################################### 1804: ############################################################### 1805: sub define_excel_formats { 1806: my ($workbook) = @_; 1807: my $format; 1808: $format->{'header'} = $workbook->add_format(bold => 1, 1809: bottom => 1, 1810: align => 'center'); 1811: $format->{'bold'} = $workbook->add_format(bold=>1); 1812: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18); 1813: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16); 1814: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14); 1815: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12); 1816: $format->{'i'} = $workbook->add_format(italic=>1); 1817: $format->{'date'} = $workbook->add_format(num_format=> 1818: 'mm/dd/yyyy hh:mm:ss'); 1819: return $format; 1820: } 1821: 1822: ############################################################### 1823: ############################################################### 1824: 1825: =pod 1826: 1827: =item * &create_workbook() 1828: 1829: Create an Excel worksheet. If it fails, output message on the 1830: request object and return undefs. 1831: 1832: Inputs: Apache request object 1833: 1834: Returns (undef) on failure, 1835: Excel worksheet object, scalar with filename, and formats 1836: from &Apache::loncommon::define_excel_formats on success 1837: 1838: =cut 1839: 1840: ############################################################### 1841: ############################################################### 1842: sub create_workbook { 1843: my ($r) = @_; 1844: # 1845: # Create the excel spreadsheet 1846: my $filename = '/prtspool/'. 1847: $env{'user.name'}.'_'.$env{'user.domain'}.'_'. 1848: time.'_'.rand(1000000000).'.xls'; 1849: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename); 1850: if (! defined($workbook)) { 1851: $r->log_error("Error creating excel spreadsheet $filename: $!"); 1852: $r->print( 1853: '<p class="LC_error">' 1854: .&mt('Problems occurred in creating the new Excel file.') 1855: .' '.&mt('This error has been logged.') 1856: .' '.&mt('Please alert your LON-CAPA administrator.') 1857: .'</p>' 1858: ); 1859: return (undef); 1860: } 1861: # 1862: $workbook->set_tempdir(LONCAPA::tempdir()); 1863: # 1864: my $format = &Apache::loncommon::define_excel_formats($workbook); 1865: return ($workbook,$filename,$format); 1866: } 1867: 1868: ############################################################### 1869: ############################################################### 1870: 1871: =pod 1872: 1873: =item * &create_text_file() 1874: 1875: Create a file to write to and eventually make available to the user. 1876: If file creation fails, outputs an error message on the request object and 1877: return undefs. 1878: 1879: Inputs: Apache request object, and file suffix 1880: 1881: Returns (undef) on failure, 1882: Filehandle and filename on success. 1883: 1884: =cut 1885: 1886: ############################################################### 1887: ############################################################### 1888: sub create_text_file { 1889: my ($r,$suffix) = @_; 1890: if (! defined($suffix)) { $suffix = 'txt'; }; 1891: my $fh; 1892: my $filename = '/prtspool/'. 1893: $env{'user.name'}.'_'.$env{'user.domain'}.'_'. 1894: time.'_'.rand(1000000000).'.'.$suffix; 1895: $fh = Apache::File->new('>/home/httpd'.$filename); 1896: if (! defined($fh)) { 1897: $r->log_error("Couldn't open $filename for output $!"); 1898: $r->print( 1899: '<p class="LC_error">' 1900: .&mt('Problems occurred in creating the output file.') 1901: .' '.&mt('This error has been logged.') 1902: .' '.&mt('Please alert your LON-CAPA administrator.') 1903: .'</p>' 1904: ); 1905: } 1906: return ($fh,$filename) 1907: } 1908: 1909: 1910: =pod 1911: 1912: =back 1913: 1914: =cut 1915: 1916: ############################################################### 1917: ## Home server <option> list generating code ## 1918: ############################################################### 1919: 1920: # ------------------------------------------ 1921: 1922: sub domain_select { 1923: my ($name,$value,$multiple)=@_; 1924: my %domains=map { 1925: $_ => $_.' '. &Apache::lonnet::domain($_,'description') 1926: } &Apache::lonnet::all_domains(); 1927: if ($multiple) { 1928: $domains{''}=&mt('Any domain'); 1929: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))]; 1930: return &multiple_select_form($name,$value,4,\%domains); 1931: } else { 1932: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))]; 1933: return &select_form($name,$value,\%domains); 1934: } 1935: } 1936: 1937: #------------------------------------------- 1938: 1939: =pod 1940: 1941: =head1 Routines for form select boxes 1942: 1943: =over 4 1944: 1945: =item * &multiple_select_form($name,$value,$size,$hash,$order) 1946: 1947: Returns a string containing a <select> element int multiple mode 1948: 1949: 1950: Args: 1951: $name - name of the <select> element 1952: $value - scalar or array ref of values that should already be selected 1953: $size - number of rows long the select element is 1954: $hash - the elements should be 'option' => 'shown text' 1955: (shown text should already have been &mt()) 1956: $order - (optional) array ref of the order to show the elements in 1957: 1958: =cut 1959: 1960: #------------------------------------------- 1961: sub multiple_select_form { 1962: my ($name,$value,$size,$hash,$order)=@_; 1963: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value); 1964: my $output=''; 1965: if (! defined($size)) { 1966: $size = 4; 1967: if (scalar(keys(%$hash))<4) { 1968: $size = scalar(keys(%$hash)); 1969: } 1970: } 1971: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">'; 1972: my @order; 1973: if (ref($order) eq 'ARRAY') { 1974: @order = @{$order}; 1975: } else { 1976: @order = sort(keys(%$hash)); 1977: } 1978: if (exists($$hash{'select_form_order'})) { 1979: @order = @{$$hash{'select_form_order'}}; 1980: } 1981: 1982: foreach my $key (@order) { 1983: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" '; 1984: $output.='selected="selected" ' if ($selected{$key}); 1985: $output.='>'.$hash->{$key}."</option>\n"; 1986: } 1987: $output.="</select>\n"; 1988: return $output; 1989: } 1990: 1991: #------------------------------------------- 1992: 1993: =pod 1994: 1995: =item * &select_form($defdom,$name,$hashref,$onchange) 1996: 1997: Returns a string containing a <select name='$name' size='1'> form to 1998: allow a user to select options from a ref to a hash containing: 1999: option_name => displayed text. An optional $onchange can include 2000: a javascript onchange item, e.g., onchange="this.form.submit();" 2001: 2002: See lonrights.pm for an example invocation and use. 2003: 2004: =cut 2005: 2006: #------------------------------------------- 2007: sub select_form { 2008: my ($def,$name,$hashref,$onchange) = @_; 2009: return unless (ref($hashref) eq 'HASH'); 2010: if ($onchange) { 2011: $onchange = ' onchange="'.$onchange.'"'; 2012: } 2013: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n"; 2014: my @keys; 2015: if (exists($hashref->{'select_form_order'})) { 2016: @keys=@{$hashref->{'select_form_order'}}; 2017: } else { 2018: @keys=sort(keys(%{$hashref})); 2019: } 2020: foreach my $key (@keys) { 2021: $selectform.= 2022: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '. 2023: ($key eq $def ? 'selected="selected" ' : ''). 2024: ">".$hashref->{$key}."</option>\n"; 2025: } 2026: $selectform.="</select>"; 2027: return $selectform; 2028: } 2029: 2030: # For display filters 2031: 2032: sub display_filter { 2033: my ($context) = @_; 2034: if (!$env{'form.show'}) { $env{'form.show'}=10; } 2035: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; } 2036: my $phraseinput = 'hidden'; 2037: my $includeinput = 'hidden'; 2038: my ($checked,$includetypestext); 2039: if ($env{'form.displayfilter'} eq 'containing') { 2040: $phraseinput = 'text'; 2041: if ($context eq 'parmslog') { 2042: $includeinput = 'checkbox'; 2043: if ($env{'form.includetypes'}) { 2044: $checked = ' checked="checked"'; 2045: } 2046: $includetypestext = &mt('Include parameter types'); 2047: } 2048: } else { 2049: $includetypestext = ' '; 2050: } 2051: my ($additional,$secondid,$thirdid); 2052: if ($context eq 'parmslog') { 2053: $additional = 2054: '<label><input type="'.$includeinput.'" name="includetypes"'. 2055: $checked.' name="includetypes" value="1" id="includetypes" />'. 2056: ' <span id="includetypestext">'.$includetypestext.'</span>'. 2057: '</label>'; 2058: $secondid = 'includetypes'; 2059: $thirdid = 'includetypestext'; 2060: } 2061: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context', 2062: '$secondid','$thirdid')"; 2063: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]', 2064: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef, 2065: (&mt('all'),10,20,50,100,1000,10000))). 2066: '</label></span> <span class="LC_nobreak">'. 2067: &mt('Filter: [_1]', 2068: &select_form($env{'form.displayfilter'}, 2069: 'displayfilter', 2070: {'currentfolder' => 'Current folder/page', 2071: 'containing' => 'Containing phrase', 2072: 'none' => 'None'},$onchange)).' '. 2073: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'. 2074: &HTML::Entities::encode($env{'form.containingphrase'}). 2075: '" />'.$additional; 2076: } 2077: 2078: sub display_filter_js { 2079: my $includetext = &mt('Include parameter types'); 2080: return <<"ENDJS"; 2081: 2082: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) { 2083: var firstType = 'hidden'; 2084: if (setter.options[setter.selectedIndex].value == 'containing') { 2085: firstType = 'text'; 2086: } 2087: firstObject = document.getElementById(firstid); 2088: if (typeof(firstObject) == 'object') { 2089: if (firstObject.type != firstType) { 2090: changeInputType(firstObject,firstType); 2091: } 2092: } 2093: if (context == 'parmslog') { 2094: var secondType = 'hidden'; 2095: if (firstType == 'text') { 2096: secondType = 'checkbox'; 2097: } 2098: secondObject = document.getElementById(secondid); 2099: if (typeof(secondObject) == 'object') { 2100: if (secondObject.type != secondType) { 2101: changeInputType(secondObject,secondType); 2102: } 2103: } 2104: var textItem = document.getElementById(thirdid); 2105: var currtext = textItem.innerHTML; 2106: var newtext; 2107: if (firstType == 'text') { 2108: newtext = '$includetext'; 2109: } else { 2110: newtext = ' '; 2111: } 2112: if (currtext != newtext) { 2113: textItem.innerHTML = newtext; 2114: } 2115: } 2116: return; 2117: } 2118: 2119: function changeInputType(oldObject,newType) { 2120: var newObject = document.createElement('input'); 2121: newObject.type = newType; 2122: if (oldObject.size) { 2123: newObject.size = oldObject.size; 2124: } 2125: if (oldObject.value) { 2126: newObject.value = oldObject.value; 2127: } 2128: if (oldObject.name) { 2129: newObject.name = oldObject.name; 2130: } 2131: if (oldObject.id) { 2132: newObject.id = oldObject.id; 2133: } 2134: oldObject.parentNode.replaceChild(newObject,oldObject); 2135: return; 2136: } 2137: 2138: ENDJS 2139: } 2140: 2141: sub gradeleveldescription { 2142: my $gradelevel=shift; 2143: my %gradelevels=(0 => 'Not specified', 2144: 1 => 'Grade 1', 2145: 2 => 'Grade 2', 2146: 3 => 'Grade 3', 2147: 4 => 'Grade 4', 2148: 5 => 'Grade 5', 2149: 6 => 'Grade 6', 2150: 7 => 'Grade 7', 2151: 8 => 'Grade 8', 2152: 9 => 'Grade 9', 2153: 10 => 'Grade 10', 2154: 11 => 'Grade 11', 2155: 12 => 'Grade 12', 2156: 13 => 'Grade 13', 2157: 14 => '100 Level', 2158: 15 => '200 Level', 2159: 16 => '300 Level', 2160: 17 => '400 Level', 2161: 18 => 'Graduate Level'); 2162: return &mt($gradelevels{$gradelevel}); 2163: } 2164: 2165: sub select_level_form { 2166: my ($deflevel,$name)=@_; 2167: unless ($deflevel) { $deflevel=0; } 2168: my $selectform = "<select name=\"$name\" size=\"1\">\n"; 2169: for (my $i=0; $i<=18; $i++) { 2170: $selectform.="<option value=\"$i\" ". 2171: ($i==$deflevel ? 'selected="selected" ' : ''). 2172: ">".&gradeleveldescription($i)."</option>\n"; 2173: } 2174: $selectform.="</select>"; 2175: return $selectform; 2176: } 2177: 2178: #------------------------------------------- 2179: 2180: =pod 2181: 2182: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) 2183: 2184: Returns a string containing a <select name='$name' size='1'> form to 2185: allow a user to select the domain to preform an operation in. 2186: See loncreateuser.pm for an example invocation and use. 2187: 2188: If the $includeempty flag is set, it also includes an empty choice ("no domain 2189: selected"); 2190: 2191: If the $showdomdesc flag is set, the domain name is followed by the domain description. 2192: 2193: 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. 2194: 2195: The optional $incdoms is a reference to an array of domains which will be the only available options. 2196: 2197: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 2198: 2199: =cut 2200: 2201: #------------------------------------------- 2202: sub select_dom_form { 2203: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_; 2204: if ($onchange) { 2205: $onchange = ' onchange="'.$onchange.'"'; 2206: } 2207: my (@domains,%exclude); 2208: if (ref($incdoms) eq 'ARRAY') { 2209: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms}); 2210: } else { 2211: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains()); 2212: } 2213: if ($includeempty) { @domains=('',@domains); } 2214: if (ref($excdoms) eq 'ARRAY') { 2215: map { $exclude{$_} = 1; } @{$excdoms}; 2216: } 2217: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n"; 2218: foreach my $dom (@domains) { 2219: next if ($exclude{$dom}); 2220: $selectdomain.="<option value=\"$dom\" ". 2221: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom; 2222: if ($showdomdesc) { 2223: if ($dom ne '') { 2224: my $domdesc = &Apache::lonnet::domain($dom,'description'); 2225: if ($domdesc ne '') { 2226: $selectdomain .= ' ('.$domdesc.')'; 2227: } 2228: } 2229: } 2230: $selectdomain .= "</option>\n"; 2231: } 2232: $selectdomain.="</select>"; 2233: return $selectdomain; 2234: } 2235: 2236: #------------------------------------------- 2237: 2238: =pod 2239: 2240: =item * &home_server_form_item($domain,$name,$defaultflag) 2241: 2242: input: 4 arguments (two required, two optional) - 2243: $domain - domain of new user 2244: $name - name of form element 2245: $default - Value of 'default' causes a default item to be first 2246: option, and selected by default. 2247: $hide - Value of 'hide' causes hiding of the name of the server, 2248: if 1 server found, or default, if 0 found. 2249: output: returns 2 items: 2250: (a) form element which contains either: 2251: (i) <select name="$name"> 2252: <option value="$hostid1">$hostid $servers{$hostid}</option> 2253: <option value="$hostid2">$hostid $servers{$hostid}</option> 2254: </select> 2255: form item if there are multiple library servers in $domain, or 2256: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 2257: if there is only one library server in $domain. 2258: 2259: (b) number of library servers found. 2260: 2261: See loncreateuser.pm for example of use. 2262: 2263: =cut 2264: 2265: #------------------------------------------- 2266: sub home_server_form_item { 2267: my ($domain,$name,$default,$hide) = @_; 2268: my %servers = &Apache::lonnet::get_servers($domain,'library'); 2269: my $result; 2270: my $numlib = keys(%servers); 2271: if ($numlib > 1) { 2272: $result .= '<select name="'.$name.'" />'."\n"; 2273: if ($default) { 2274: $result .= '<option value="default" selected="selected">'.&mt('default'). 2275: '</option>'."\n"; 2276: } 2277: foreach my $hostid (sort(keys(%servers))) { 2278: $result.= '<option value="'.$hostid.'">'. 2279: $hostid.' '.$servers{$hostid}."</option>\n"; 2280: } 2281: $result .= '</select>'."\n"; 2282: } elsif ($numlib == 1) { 2283: my $hostid; 2284: foreach my $item (keys(%servers)) { 2285: $hostid = $item; 2286: } 2287: $result .= '<input type="hidden" name="'.$name.'" value="'. 2288: $hostid.'" />'; 2289: if (!$hide) { 2290: $result .= $hostid.' '.$servers{$hostid}; 2291: } 2292: $result .= "\n"; 2293: } elsif ($default) { 2294: $result .= '<input type="hidden" name="'.$name. 2295: '" value="default" />'; 2296: if (!$hide) { 2297: $result .= &mt('default'); 2298: } 2299: $result .= "\n"; 2300: } 2301: return ($result,$numlib); 2302: } 2303: 2304: =pod 2305: 2306: =back 2307: 2308: =cut 2309: 2310: ############################################################### 2311: ## Decoding User Agent ## 2312: ############################################################### 2313: 2314: =pod 2315: 2316: =head1 Decoding the User Agent 2317: 2318: =over 4 2319: 2320: =item * &decode_user_agent() 2321: 2322: Inputs: $r 2323: 2324: Outputs: 2325: 2326: =over 4 2327: 2328: =item * $httpbrowser 2329: 2330: =item * $clientbrowser 2331: 2332: =item * $clientversion 2333: 2334: =item * $clientmathml 2335: 2336: =item * $clientunicode 2337: 2338: =item * $clientos 2339: 2340: =item * $clientmobile 2341: 2342: =item * $clientinfo 2343: 2344: =item * $clientosversion 2345: 2346: =back 2347: 2348: =back 2349: 2350: =cut 2351: 2352: ############################################################### 2353: ############################################################### 2354: sub decode_user_agent { 2355: my ($r)=@_; 2356: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"}); 2357: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"}); 2358: my $httpbrowser=$ENV{"HTTP_USER_AGENT"}; 2359: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); } 2360: my $clientbrowser='unknown'; 2361: my $clientversion='0'; 2362: my $clientmathml=''; 2363: my $clientunicode='0'; 2364: my $clientmobile=0; 2365: my $clientosversion=''; 2366: for (my $i=0;$i<=$#browsertype;$i++) { 2367: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]); 2368: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) { 2369: $clientbrowser=$bname; 2370: $httpbrowser=~/$vreg/i; 2371: $clientversion=$1; 2372: $clientmathml=($clientversion>=$minv); 2373: $clientunicode=($clientversion>=$univ); 2374: } 2375: } 2376: my $clientos='unknown'; 2377: my $clientinfo; 2378: if (($httpbrowser=~/linux/i) || 2379: ($httpbrowser=~/unix/i) || 2380: ($httpbrowser=~/ux/i) || 2381: ($httpbrowser=~/solaris/i)) { $clientos='unix'; } 2382: if (($httpbrowser=~/vax/i) || 2383: ($httpbrowser=~/vms/i)) { $clientos='vms'; } 2384: if ($httpbrowser=~/next/i) { $clientos='next'; } 2385: if (($httpbrowser=~/mac/i) || 2386: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; } 2387: if ($httpbrowser=~/win/i) { 2388: $clientos='win'; 2389: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) { 2390: $clientosversion = $1; 2391: } 2392: } 2393: if ($httpbrowser=~/embed/i) { $clientos='pda'; } 2394: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) { 2395: $clientmobile=lc($1); 2396: } 2397: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) { 2398: $clientinfo = 'firefox-'.$1; 2399: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) { 2400: $clientinfo = 'chromeframe-'.$1; 2401: } 2402: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml, 2403: $clientunicode,$clientos,$clientmobile,$clientinfo, 2404: $clientosversion); 2405: } 2406: 2407: ############################################################### 2408: ## Authentication changing form generation subroutines ## 2409: ############################################################### 2410: ## 2411: ## All of the authform_xxxxxxx subroutines take their inputs in a 2412: ## hash, and have reasonable default values. 2413: ## 2414: ## formname = the name given in the <form> tag. 2415: #------------------------------------------- 2416: 2417: =pod 2418: 2419: =head1 Authentication Routines 2420: 2421: =over 4 2422: 2423: =item * &authform_xxxxxx() 2424: 2425: The authform_xxxxxx subroutines provide javascript and html forms which 2426: handle some of the conveniences required for authentication forms. 2427: This is not an optimal method, but it works. 2428: 2429: =over 4 2430: 2431: =item * authform_header 2432: 2433: =item * authform_authorwarning 2434: 2435: =item * authform_nochange 2436: 2437: =item * authform_kerberos 2438: 2439: =item * authform_internal 2440: 2441: =item * authform_filesystem 2442: 2443: =back 2444: 2445: See loncreateuser.pm for invocation and use examples. 2446: 2447: =cut 2448: 2449: #------------------------------------------- 2450: sub authform_header{ 2451: my %in = ( 2452: formname => 'cu', 2453: kerb_def_dom => '', 2454: @_, 2455: ); 2456: $in{'formname'} = 'document.' . $in{'formname'}; 2457: my $result=''; 2458: 2459: #---------------------------------------------- Code for upper case translation 2460: my $Javascript_toUpperCase; 2461: unless ($in{kerb_def_dom}) { 2462: $Javascript_toUpperCase =<<"END"; 2463: switch (choice) { 2464: case 'krb': currentform.elements[choicearg].value = 2465: currentform.elements[choicearg].value.toUpperCase(); 2466: break; 2467: default: 2468: } 2469: END 2470: } else { 2471: $Javascript_toUpperCase = ""; 2472: } 2473: 2474: my $radioval = "'nochange'"; 2475: if (defined($in{'curr_authtype'})) { 2476: if ($in{'curr_authtype'} ne '') { 2477: $radioval = "'".$in{'curr_authtype'}."arg'"; 2478: } 2479: } 2480: my $argfield = 'null'; 2481: if (defined($in{'mode'})) { 2482: if ($in{'mode'} eq 'modifycourse') { 2483: if (defined($in{'curr_autharg'})) { 2484: if ($in{'curr_autharg'} ne '') { 2485: $argfield = "'$in{'curr_autharg'}'"; 2486: } 2487: } 2488: } 2489: } 2490: 2491: $result.=<<"END"; 2492: var current = new Object(); 2493: current.radiovalue = $radioval; 2494: current.argfield = $argfield; 2495: 2496: function changed_radio(choice,currentform) { 2497: var choicearg = choice + 'arg'; 2498: // If a radio button in changed, we need to change the argfield 2499: if (current.radiovalue != choice) { 2500: current.radiovalue = choice; 2501: if (current.argfield != null) { 2502: currentform.elements[current.argfield].value = ''; 2503: } 2504: if (choice == 'nochange') { 2505: current.argfield = null; 2506: } else { 2507: current.argfield = choicearg; 2508: switch(choice) { 2509: case 'krb': 2510: currentform.elements[current.argfield].value = 2511: "$in{'kerb_def_dom'}"; 2512: break; 2513: default: 2514: break; 2515: } 2516: } 2517: } 2518: return; 2519: } 2520: 2521: function changed_text(choice,currentform) { 2522: var choicearg = choice + 'arg'; 2523: if (currentform.elements[choicearg].value !='') { 2524: $Javascript_toUpperCase 2525: // clear old field 2526: if ((current.argfield != choicearg) && (current.argfield != null)) { 2527: currentform.elements[current.argfield].value = ''; 2528: } 2529: current.argfield = choicearg; 2530: } 2531: set_auth_radio_buttons(choice,currentform); 2532: return; 2533: } 2534: 2535: function set_auth_radio_buttons(newvalue,currentform) { 2536: var numauthchoices = currentform.login.length; 2537: if (typeof numauthchoices == "undefined") { 2538: return; 2539: } 2540: var i=0; 2541: while (i < numauthchoices) { 2542: if (currentform.login[i].value == newvalue) { break; } 2543: i++; 2544: } 2545: if (i == numauthchoices) { 2546: return; 2547: } 2548: current.radiovalue = newvalue; 2549: currentform.login[i].checked = true; 2550: return; 2551: } 2552: END 2553: return $result; 2554: } 2555: 2556: sub authform_authorwarning { 2557: my $result=''; 2558: $result='<i>'. 2559: &mt('As a general rule, only authors or co-authors should be '. 2560: 'filesystem authenticated '. 2561: '(which allows access to the server filesystem).')."</i>\n"; 2562: return $result; 2563: } 2564: 2565: sub authform_nochange { 2566: my %in = ( 2567: formname => 'document.cu', 2568: kerb_def_dom => 'MSU.EDU', 2569: @_, 2570: ); 2571: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2572: my $result; 2573: if (!$authnum) { 2574: $result = &mt('Under your current role you are not permitted to change login settings for this user'); 2575: } else { 2576: $result = '<label>'.&mt('[_1] Do not change login data', 2577: '<input type="radio" name="login" value="nochange" '. 2578: 'checked="checked" onclick="'. 2579: "javascript:changed_radio('nochange',$in{'formname'});".'" />'). 2580: '</label>'; 2581: } 2582: return $result; 2583: } 2584: 2585: sub authform_kerberos { 2586: my %in = ( 2587: formname => 'document.cu', 2588: kerb_def_dom => 'MSU.EDU', 2589: kerb_def_auth => 'krb4', 2590: @_, 2591: ); 2592: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype, 2593: $autharg,$jscall); 2594: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2595: if ($in{'kerb_def_auth'} eq 'krb5') { 2596: $check5 = ' checked="checked"'; 2597: } else { 2598: $check4 = ' checked="checked"'; 2599: } 2600: $krbarg = $in{'kerb_def_dom'}; 2601: if (defined($in{'curr_authtype'})) { 2602: if ($in{'curr_authtype'} eq 'krb') { 2603: $krbcheck = ' checked="checked"'; 2604: if (defined($in{'mode'})) { 2605: if ($in{'mode'} eq 'modifyuser') { 2606: $krbcheck = ''; 2607: } 2608: } 2609: if (defined($in{'curr_kerb_ver'})) { 2610: if ($in{'curr_krb_ver'} eq '5') { 2611: $check5 = ' checked="checked"'; 2612: $check4 = ''; 2613: } else { 2614: $check4 = ' checked="checked"'; 2615: $check5 = ''; 2616: } 2617: } 2618: if (defined($in{'curr_autharg'})) { 2619: $krbarg = $in{'curr_autharg'}; 2620: } 2621: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) { 2622: if (defined($in{'curr_autharg'})) { 2623: $result = 2624: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].', 2625: $in{'curr_autharg'},$krbver); 2626: } else { 2627: $result = 2628: &mt('Currently Kerberos authenticated, Version [_1].',$krbver); 2629: } 2630: return $result; 2631: } 2632: } 2633: } else { 2634: if ($authnum == 1) { 2635: $authtype = '<input type="hidden" name="login" value="krb" />'; 2636: } 2637: } 2638: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) { 2639: return; 2640: } elsif ($authtype eq '') { 2641: if (defined($in{'mode'})) { 2642: if ($in{'mode'} eq 'modifycourse') { 2643: if ($authnum == 1) { 2644: $authtype = '<input type="radio" name="login" value="krb" />'; 2645: } 2646: } 2647: } 2648: } 2649: $jscall = "javascript:changed_radio('krb',$in{'formname'});"; 2650: if ($authtype eq '') { 2651: $authtype = '<input type="radio" name="login" value="krb" '. 2652: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'. 2653: $krbcheck.' />'; 2654: } 2655: if (($can_assign{'krb4'} && $can_assign{'krb5'}) || 2656: ($can_assign{'krb4'} && !$can_assign{'krb5'} && 2657: $in{'curr_authtype'} eq 'krb5') || 2658: (!$can_assign{'krb4'} && $can_assign{'krb5'} && 2659: $in{'curr_authtype'} eq 'krb4')) { 2660: $result .= &mt 2661: ('[_1] Kerberos authenticated with domain [_2] '. 2662: '[_3] Version 4 [_4] Version 5 [_5]', 2663: '<label>'.$authtype, 2664: '</label><input type="text" size="10" name="krbarg" '. 2665: 'value="'.$krbarg.'" '. 2666: 'onchange="'.$jscall.'" />', 2667: '<label><input type="radio" name="krbver" value="4" '.$check4.' />', 2668: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />', 2669: '</label>'); 2670: } elsif ($can_assign{'krb4'}) { 2671: $result .= &mt 2672: ('[_1] Kerberos authenticated with domain [_2] '. 2673: '[_3] Version 4 [_4]', 2674: '<label>'.$authtype, 2675: '</label><input type="text" size="10" name="krbarg" '. 2676: 'value="'.$krbarg.'" '. 2677: 'onchange="'.$jscall.'" />', 2678: '<label><input type="hidden" name="krbver" value="4" />', 2679: '</label>'); 2680: } elsif ($can_assign{'krb5'}) { 2681: $result .= &mt 2682: ('[_1] Kerberos authenticated with domain [_2] '. 2683: '[_3] Version 5 [_4]', 2684: '<label>'.$authtype, 2685: '</label><input type="text" size="10" name="krbarg" '. 2686: 'value="'.$krbarg.'" '. 2687: 'onchange="'.$jscall.'" />', 2688: '<label><input type="hidden" name="krbver" value="5" />', 2689: '</label>'); 2690: } 2691: return $result; 2692: } 2693: 2694: sub authform_internal { 2695: my %in = ( 2696: formname => 'document.cu', 2697: kerb_def_dom => 'MSU.EDU', 2698: @_, 2699: ); 2700: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall); 2701: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2702: if (defined($in{'curr_authtype'})) { 2703: if ($in{'curr_authtype'} eq 'int') { 2704: if ($can_assign{'int'}) { 2705: $intcheck = 'checked="checked" '; 2706: if (defined($in{'mode'})) { 2707: if ($in{'mode'} eq 'modifyuser') { 2708: $intcheck = ''; 2709: } 2710: } 2711: if (defined($in{'curr_autharg'})) { 2712: $intarg = $in{'curr_autharg'}; 2713: } 2714: } else { 2715: $result = &mt('Currently internally authenticated.'); 2716: return $result; 2717: } 2718: } 2719: } else { 2720: if ($authnum == 1) { 2721: $authtype = '<input type="hidden" name="login" value="int" />'; 2722: } 2723: } 2724: if (!$can_assign{'int'}) { 2725: return; 2726: } elsif ($authtype eq '') { 2727: if (defined($in{'mode'})) { 2728: if ($in{'mode'} eq 'modifycourse') { 2729: if ($authnum == 1) { 2730: $authtype = '<input type="radio" name="login" value="int" />'; 2731: } 2732: } 2733: } 2734: } 2735: $jscall = "javascript:changed_radio('int',$in{'formname'});"; 2736: if ($authtype eq '') { 2737: $authtype = '<input type="radio" name="login" value="int" '.$intcheck. 2738: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />'; 2739: } 2740: $autharg = '<input type="password" size="10" name="intarg" value="'. 2741: $intarg.'" onchange="'.$jscall.'" />'; 2742: $result = &mt 2743: ('[_1] Internally authenticated (with initial password [_2])', 2744: '<label>'.$authtype,'</label>'.$autharg); 2745: $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>'; 2746: return $result; 2747: } 2748: 2749: sub authform_local { 2750: my %in = ( 2751: formname => 'document.cu', 2752: kerb_def_dom => 'MSU.EDU', 2753: @_, 2754: ); 2755: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall); 2756: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2757: if (defined($in{'curr_authtype'})) { 2758: if ($in{'curr_authtype'} eq 'loc') { 2759: if ($can_assign{'loc'}) { 2760: $loccheck = 'checked="checked" '; 2761: if (defined($in{'mode'})) { 2762: if ($in{'mode'} eq 'modifyuser') { 2763: $loccheck = ''; 2764: } 2765: } 2766: if (defined($in{'curr_autharg'})) { 2767: $locarg = $in{'curr_autharg'}; 2768: } 2769: } else { 2770: $result = &mt('Currently using local (institutional) authentication.'); 2771: return $result; 2772: } 2773: } 2774: } else { 2775: if ($authnum == 1) { 2776: $authtype = '<input type="hidden" name="login" value="loc" />'; 2777: } 2778: } 2779: if (!$can_assign{'loc'}) { 2780: return; 2781: } elsif ($authtype eq '') { 2782: if (defined($in{'mode'})) { 2783: if ($in{'mode'} eq 'modifycourse') { 2784: if ($authnum == 1) { 2785: $authtype = '<input type="radio" name="login" value="loc" />'; 2786: } 2787: } 2788: } 2789: } 2790: $jscall = "javascript:changed_radio('loc',$in{'formname'});"; 2791: if ($authtype eq '') { 2792: $authtype = '<input type="radio" name="login" value="loc" '. 2793: $loccheck.' onchange="'.$jscall.'" onclick="'. 2794: $jscall.'" />'; 2795: } 2796: $autharg = '<input type="text" size="10" name="locarg" value="'. 2797: $locarg.'" onchange="'.$jscall.'" />'; 2798: $result = &mt('[_1] Local Authentication with argument [_2]', 2799: '<label>'.$authtype,'</label>'.$autharg); 2800: return $result; 2801: } 2802: 2803: sub authform_filesystem { 2804: my %in = ( 2805: formname => 'document.cu', 2806: kerb_def_dom => 'MSU.EDU', 2807: @_, 2808: ); 2809: my ($fsyscheck,$result,$authtype,$autharg,$jscall); 2810: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2811: if (defined($in{'curr_authtype'})) { 2812: if ($in{'curr_authtype'} eq 'fsys') { 2813: if ($can_assign{'fsys'}) { 2814: $fsyscheck = 'checked="checked" '; 2815: if (defined($in{'mode'})) { 2816: if ($in{'mode'} eq 'modifyuser') { 2817: $fsyscheck = ''; 2818: } 2819: } 2820: } else { 2821: $result = &mt('Currently Filesystem Authenticated.'); 2822: return $result; 2823: } 2824: } 2825: } else { 2826: if ($authnum == 1) { 2827: $authtype = '<input type="hidden" name="login" value="fsys" />'; 2828: } 2829: } 2830: if (!$can_assign{'fsys'}) { 2831: return; 2832: } elsif ($authtype eq '') { 2833: if (defined($in{'mode'})) { 2834: if ($in{'mode'} eq 'modifycourse') { 2835: if ($authnum == 1) { 2836: $authtype = '<input type="radio" name="login" value="fsys" />'; 2837: } 2838: } 2839: } 2840: } 2841: $jscall = "javascript:changed_radio('fsys',$in{'formname'});"; 2842: if ($authtype eq '') { 2843: $authtype = '<input type="radio" name="login" value="fsys" '. 2844: $fsyscheck.' onchange="'.$jscall.'" onclick="'. 2845: $jscall.'" />'; 2846: } 2847: $autharg = '<input type="text" size="10" name="fsysarg" value=""'. 2848: ' onchange="'.$jscall.'" />'; 2849: $result = &mt 2850: ('[_1] Filesystem Authenticated (with initial password [_2])', 2851: '<label><input type="radio" name="login" value="fsys" '. 2852: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />', 2853: '</label><input type="password" size="10" name="fsysarg" value="" '. 2854: 'onchange="'.$jscall.'" />'); 2855: return $result; 2856: } 2857: 2858: sub get_assignable_auth { 2859: my ($dom) = @_; 2860: if ($dom eq '') { 2861: $dom = $env{'request.role.domain'}; 2862: } 2863: my %can_assign = ( 2864: krb4 => 1, 2865: krb5 => 1, 2866: int => 1, 2867: loc => 1, 2868: ); 2869: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom); 2870: if (ref($domconfig{'usercreation'}) eq 'HASH') { 2871: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') { 2872: my $authhash = $domconfig{'usercreation'}{'authtypes'}; 2873: my $context; 2874: if ($env{'request.role'} =~ /^au/) { 2875: $context = 'author'; 2876: } elsif ($env{'request.role'} =~ /^dc/) { 2877: $context = 'domain'; 2878: } elsif ($env{'request.course.id'}) { 2879: $context = 'course'; 2880: } 2881: if ($context) { 2882: if (ref($authhash->{$context}) eq 'HASH') { 2883: %can_assign = %{$authhash->{$context}}; 2884: } 2885: } 2886: } 2887: } 2888: my $authnum = 0; 2889: foreach my $key (keys(%can_assign)) { 2890: if ($can_assign{$key}) { 2891: $authnum ++; 2892: } 2893: } 2894: if ($can_assign{'krb4'} && $can_assign{'krb5'}) { 2895: $authnum --; 2896: } 2897: return ($authnum,%can_assign); 2898: } 2899: 2900: ############################################################### 2901: ## Get Kerberos Defaults for Domain ## 2902: ############################################################### 2903: ## 2904: ## Returns default kerberos version and an associated argument 2905: ## as listed in file domain.tab. If not listed, provides 2906: ## appropriate default domain and kerberos version. 2907: ## 2908: #------------------------------------------- 2909: 2910: =pod 2911: 2912: =item * &get_kerberos_defaults() 2913: 2914: get_kerberos_defaults($target_domain) returns the default kerberos 2915: version and domain. If not found, it defaults to version 4 and the 2916: domain of the server. 2917: 2918: =over 4 2919: 2920: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain); 2921: 2922: =back 2923: 2924: =back 2925: 2926: =cut 2927: 2928: #------------------------------------------- 2929: sub get_kerberos_defaults { 2930: my $domain=shift; 2931: my ($krbdef,$krbdefdom); 2932: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain); 2933: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) { 2934: $krbdef = $domdefaults{'auth_def'}; 2935: $krbdefdom = $domdefaults{'auth_arg_def'}; 2936: } else { 2937: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/; 2938: my $krbdefdom=$1; 2939: $krbdefdom=~tr/a-z/A-Z/; 2940: $krbdef = "krb4"; 2941: } 2942: return ($krbdef,$krbdefdom); 2943: } 2944: 2945: 2946: ############################################################### 2947: ## Thesaurus Functions ## 2948: ############################################################### 2949: 2950: =pod 2951: 2952: =head1 Thesaurus Functions 2953: 2954: =over 4 2955: 2956: =item * &initialize_keywords() 2957: 2958: Initializes the package variable %Keywords if it is empty. Uses the 2959: package variable $thesaurus_db_file. 2960: 2961: =cut 2962: 2963: ################################################### 2964: 2965: sub initialize_keywords { 2966: return 1 if (scalar keys(%Keywords)); 2967: # If we are here, %Keywords is empty, so fill it up 2968: # Make sure the file we need exists... 2969: if (! -e $thesaurus_db_file) { 2970: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file". 2971: " failed because it does not exist"); 2972: return 0; 2973: } 2974: # Set up the hash as a database 2975: my %thesaurus_db; 2976: if (! tie(%thesaurus_db,'GDBM_File', 2977: $thesaurus_db_file,&GDBM_READER(),0640)){ 2978: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ". 2979: $thesaurus_db_file); 2980: return 0; 2981: } 2982: # Get the average number of appearances of a word. 2983: my $avecount = $thesaurus_db{'average.count'}; 2984: # Put keywords (those that appear > average) into %Keywords 2985: while (my ($word,$data)=each (%thesaurus_db)) { 2986: my ($count,undef) = split /:/,$data; 2987: $Keywords{$word}++ if ($count > $avecount); 2988: } 2989: untie %thesaurus_db; 2990: # Remove special values from %Keywords. 2991: foreach my $value ('total.count','average.count') { 2992: delete($Keywords{$value}) if (exists($Keywords{$value})); 2993: } 2994: return 1; 2995: } 2996: 2997: ################################################### 2998: 2999: =pod 3000: 3001: =item * &keyword($word) 3002: 3003: Returns true if $word is a keyword. A keyword is a word that appears more 3004: than the average number of times in the thesaurus database. Calls 3005: &initialize_keywords 3006: 3007: =cut 3008: 3009: ################################################### 3010: 3011: sub keyword { 3012: return if (!&initialize_keywords()); 3013: my $word=lc(shift()); 3014: $word=~s/\W//g; 3015: return exists($Keywords{$word}); 3016: } 3017: 3018: ############################################################### 3019: 3020: =pod 3021: 3022: =item * &get_related_words() 3023: 3024: Look up a word in the thesaurus. Takes a scalar argument and returns 3025: an array of words. If the keyword is not in the thesaurus, an empty array 3026: will be returned. The order of the words returned is determined by the 3027: database which holds them. 3028: 3029: Uses global $thesaurus_db_file. 3030: 3031: 3032: =cut 3033: 3034: ############################################################### 3035: sub get_related_words { 3036: my $keyword = shift; 3037: my %thesaurus_db; 3038: if (! -e $thesaurus_db_file) { 3039: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ". 3040: "failed because the file does not exist"); 3041: return (); 3042: } 3043: if (! tie(%thesaurus_db,'GDBM_File', 3044: $thesaurus_db_file,&GDBM_READER(),0640)){ 3045: return (); 3046: } 3047: my @Words=(); 3048: my $count=0; 3049: if (exists($thesaurus_db{$keyword})) { 3050: # The first element is the number of times 3051: # the word appears. We do not need it now. 3052: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword})); 3053: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]); 3054: my $threshold=$mostfrequentcount/10; 3055: foreach my $possibleword (@RelatedWords) { 3056: my ($word,$wordcount)=split(/\,/,$possibleword); 3057: if ($wordcount>$threshold) { 3058: push(@Words,$word); 3059: $count++; 3060: if ($count>10) { last; } 3061: } 3062: } 3063: } 3064: untie %thesaurus_db; 3065: return @Words; 3066: } 3067: 3068: =pod 3069: 3070: =back 3071: 3072: =cut 3073: 3074: # -------------------------------------------------------------- Plaintext name 3075: =pod 3076: 3077: =head1 User Name Functions 3078: 3079: =over 4 3080: 3081: =item * &plainname($uname,$udom,$first) 3082: 3083: Takes a users logon name and returns it as a string in 3084: "first middle last generation" form 3085: if $first is set to 'lastname' then it returns it as 3086: 'lastname generation, firstname middlename' if their is a lastname 3087: 3088: =cut 3089: 3090: 3091: ############################################################### 3092: sub plainname { 3093: my ($uname,$udom,$first)=@_; 3094: return if (!defined($uname) || !defined($udom)); 3095: my %names=&getnames($uname,$udom); 3096: my $name=&Apache::lonnet::format_name($names{'firstname'}, 3097: $names{'middlename'}, 3098: $names{'lastname'}, 3099: $names{'generation'},$first); 3100: $name=~s/^\s+//; 3101: $name=~s/\s+$//; 3102: $name=~s/\s+/ /g; 3103: if ($name !~ /\S/) { $name=$uname.':'.$udom; } 3104: return $name; 3105: } 3106: 3107: # -------------------------------------------------------------------- Nickname 3108: =pod 3109: 3110: =item * &nickname($uname,$udom) 3111: 3112: Gets a users name and returns it as a string as 3113: 3114: ""nickname"" 3115: 3116: if the user has a nickname or 3117: 3118: "first middle last generation" 3119: 3120: if the user does not 3121: 3122: =cut 3123: 3124: sub nickname { 3125: my ($uname,$udom)=@_; 3126: return if (!defined($uname) || !defined($udom)); 3127: my %names=&getnames($uname,$udom); 3128: my $name=$names{'nickname'}; 3129: if ($name) { 3130: $name='"'.$name.'"'; 3131: } else { 3132: $name=$names{'firstname'}.' '.$names{'middlename'}.' '. 3133: $names{'lastname'}.' '.$names{'generation'}; 3134: $name=~s/\s+$//; 3135: $name=~s/\s+/ /g; 3136: } 3137: return $name; 3138: } 3139: 3140: sub getnames { 3141: my ($uname,$udom)=@_; 3142: return if (!defined($uname) || !defined($udom)); 3143: if ($udom eq 'public' && $uname eq 'public') { 3144: return ('lastname' => &mt('Public')); 3145: } 3146: my $id=$uname.':'.$udom; 3147: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id); 3148: if ($cached) { 3149: return %{$names}; 3150: } else { 3151: my %loadnames=&Apache::lonnet::get('environment', 3152: ['firstname','middlename','lastname','generation','nickname'], 3153: $udom,$uname); 3154: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames); 3155: return %loadnames; 3156: } 3157: } 3158: 3159: # -------------------------------------------------------------------- getemails 3160: 3161: =pod 3162: 3163: =item * &getemails($uname,$udom) 3164: 3165: Gets a user's email information and returns it as a hash with keys: 3166: notification, critnotification, permanentemail 3167: 3168: For notification and critnotification, values are comma-separated lists 3169: of e-mail addresses; for permanentemail, value is a single e-mail address. 3170: 3171: 3172: =cut 3173: 3174: 3175: sub getemails { 3176: my ($uname,$udom)=@_; 3177: if ($udom eq 'public' && $uname eq 'public') { 3178: return; 3179: } 3180: if (!$udom) { $udom=$env{'user.domain'}; } 3181: if (!$uname) { $uname=$env{'user.name'}; } 3182: my $id=$uname.':'.$udom; 3183: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id); 3184: if ($cached) { 3185: return %{$names}; 3186: } else { 3187: my %loadnames=&Apache::lonnet::get('environment', 3188: ['notification','critnotification', 3189: 'permanentemail'], 3190: $udom,$uname); 3191: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames); 3192: return %loadnames; 3193: } 3194: } 3195: 3196: sub flush_email_cache { 3197: my ($uname,$udom)=@_; 3198: if (!$udom) { $udom =$env{'user.domain'}; } 3199: if (!$uname) { $uname=$env{'user.name'}; } 3200: return if ($udom eq 'public' && $uname eq 'public'); 3201: my $id=$uname.':'.$udom; 3202: &Apache::lonnet::devalidate_cache_new('emailscache',$id); 3203: } 3204: 3205: # -------------------------------------------------------------------- getlangs 3206: 3207: =pod 3208: 3209: =item * &getlangs($uname,$udom) 3210: 3211: Gets a user's language preference and returns it as a hash with key: 3212: language. 3213: 3214: =cut 3215: 3216: 3217: sub getlangs { 3218: my ($uname,$udom) = @_; 3219: if (!$udom) { $udom =$env{'user.domain'}; } 3220: if (!$uname) { $uname=$env{'user.name'}; } 3221: my $id=$uname.':'.$udom; 3222: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id); 3223: if ($cached) { 3224: return %{$langs}; 3225: } else { 3226: my %loadlangs=&Apache::lonnet::get('environment',['languages'], 3227: $udom,$uname); 3228: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs); 3229: return %loadlangs; 3230: } 3231: } 3232: 3233: sub flush_langs_cache { 3234: my ($uname,$udom)=@_; 3235: if (!$udom) { $udom =$env{'user.domain'}; } 3236: if (!$uname) { $uname=$env{'user.name'}; } 3237: return if ($udom eq 'public' && $uname eq 'public'); 3238: my $id=$uname.':'.$udom; 3239: &Apache::lonnet::devalidate_cache_new('userlangs',$id); 3240: } 3241: 3242: # ------------------------------------------------------------------ Screenname 3243: 3244: =pod 3245: 3246: =item * &screenname($uname,$udom) 3247: 3248: Gets a users screenname and returns it as a string 3249: 3250: =cut 3251: 3252: sub screenname { 3253: my ($uname,$udom)=@_; 3254: if ($uname eq $env{'user.name'} && 3255: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};} 3256: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname); 3257: return $names{'screenname'}; 3258: } 3259: 3260: 3261: # ------------------------------------------------------------- Confirm Wrapper 3262: =pod 3263: 3264: =item * &confirmwrapper($message) 3265: 3266: Wrap messages about completion of operation in box 3267: 3268: =cut 3269: 3270: sub confirmwrapper { 3271: my ($message)=@_; 3272: if ($message) { 3273: return "\n".'<div class="LC_confirm_box">'."\n" 3274: .$message."\n" 3275: .'</div>'."\n"; 3276: } else { 3277: return $message; 3278: } 3279: } 3280: 3281: # ------------------------------------------------------------- Message Wrapper 3282: 3283: sub messagewrapper { 3284: my ($link,$username,$domain,$subject,$text)=@_; 3285: return 3286: '<a href="/adm/email?compose=individual&'. 3287: 'recname='.$username.'&recdom='.$domain. 3288: '&subject='.&escape($subject).'&text='.&escape($text).'" '. 3289: 'title="'.&mt('Send message').'">'.$link.'</a>'; 3290: } 3291: 3292: # --------------------------------------------------------------- Notes Wrapper 3293: 3294: sub noteswrapper { 3295: my ($link,$un,$do)=@_; 3296: return 3297: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>"; 3298: } 3299: 3300: # ------------------------------------------------------------- Aboutme Wrapper 3301: 3302: sub aboutmewrapper { 3303: my ($link,$username,$domain,$target,$class)=@_; 3304: if (!defined($username) && !defined($domain)) { 3305: return; 3306: } 3307: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'. 3308: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>'; 3309: } 3310: 3311: # ------------------------------------------------------------ Syllabus Wrapper 3312: 3313: sub syllabuswrapper { 3314: my ($linktext,$coursedir,$domain)=@_; 3315: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>}; 3316: } 3317: 3318: # ----------------------------------------------------------------------------- 3319: 3320: sub track_student_link { 3321: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_; 3322: my $link ="/adm/trackstudent?"; 3323: my $title = 'View recent activity'; 3324: if (defined($sname) && $sname !~ /^\s*$/ && 3325: defined($sdom) && $sdom !~ /^\s*$/) { 3326: $link .= "selected_student=$sname:$sdom"; 3327: $title .= ' of this student'; 3328: } 3329: if (defined($target) && $target !~ /^\s*$/) { 3330: $target = qq{target="$target"}; 3331: } else { 3332: $target = ''; 3333: } 3334: if ($start) { $link.='&start='.$start; } 3335: if ($only_body) { $link .= '&only_body=1'; } 3336: $title = &mt($title); 3337: $linktext = &mt($linktext); 3338: return qq{<a href="$link" title="$title" $target>$linktext</a>}. 3339: &help_open_topic('View_recent_activity'); 3340: } 3341: 3342: sub slot_reservations_link { 3343: my ($linktext,$sname,$sdom,$target) = @_; 3344: my $link ="/adm/slotrequest?command=showresv&origin=aboutme"; 3345: my $title = 'View slot reservation history'; 3346: if (defined($sname) && $sname !~ /^\s*$/ && 3347: defined($sdom) && $sdom !~ /^\s*$/) { 3348: $link .= "&uname=$sname&udom=$sdom"; 3349: $title .= ' of this student'; 3350: } 3351: if (defined($target) && $target !~ /^\s*$/) { 3352: $target = qq{target="$target"}; 3353: } else { 3354: $target = ''; 3355: } 3356: $title = &mt($title); 3357: $linktext = &mt($linktext); 3358: return qq{<a href="$link" title="$title" $target>$linktext</a>}; 3359: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History'); 3360: 3361: } 3362: 3363: # ===================================================== Display a student photo 3364: 3365: 3366: sub student_image_tag { 3367: my ($domain,$user)=@_; 3368: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg'); 3369: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) { 3370: return '<img src="'.$imgsrc.'" align="right" />'; 3371: } else { 3372: return ''; 3373: } 3374: } 3375: 3376: =pod 3377: 3378: =back 3379: 3380: =head1 Access .tab File Data 3381: 3382: =over 4 3383: 3384: =item * &languageids() 3385: 3386: returns list of all language ids 3387: 3388: =cut 3389: 3390: sub languageids { 3391: return sort(keys(%language)); 3392: } 3393: 3394: =pod 3395: 3396: =item * &languagedescription() 3397: 3398: returns description of a specified language id 3399: 3400: =cut 3401: 3402: sub languagedescription { 3403: my $code=shift; 3404: return ($supported_language{$code}?'* ':''). 3405: $language{$code}. 3406: ($supported_language{$code}?' ('.&mt('interface available').')':''); 3407: } 3408: 3409: =pod 3410: 3411: =item * &plainlanguagedescription 3412: 3413: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)') 3414: and the language character encoding (e.g. ISO) separated by a ' - ' string. 3415: 3416: =cut 3417: 3418: sub plainlanguagedescription { 3419: my $code=shift; 3420: return $language{$code}; 3421: } 3422: 3423: =pod 3424: 3425: =item * &supportedlanguagecode 3426: 3427: Returns the supported language code (e.g. sptutf maps to pt) given a language 3428: code. 3429: 3430: =cut 3431: 3432: sub supportedlanguagecode { 3433: my $code=shift; 3434: return $supported_language{$code}; 3435: } 3436: 3437: =pod 3438: 3439: =item * &latexlanguage() 3440: 3441: Given a language key code returns the correspondnig language to use 3442: to select the correct hyphenation on LaTeX printouts. This is undef if there 3443: is no supported hyphenation for the language code. 3444: 3445: =cut 3446: 3447: sub latexlanguage { 3448: my $code = shift; 3449: return $latex_language{$code}; 3450: } 3451: 3452: =pod 3453: 3454: =item * &latexhyphenation() 3455: 3456: Same as above but what's supplied is the language as it might be stored 3457: in the metadata. 3458: 3459: =cut 3460: 3461: sub latexhyphenation { 3462: my $key = shift; 3463: return $latex_language_bykey{$key}; 3464: } 3465: 3466: =pod 3467: 3468: =item * ©rightids() 3469: 3470: returns list of all copyrights 3471: 3472: =cut 3473: 3474: sub copyrightids { 3475: return sort(keys(%cprtag)); 3476: } 3477: 3478: =pod 3479: 3480: =item * ©rightdescription() 3481: 3482: returns description of a specified copyright id 3483: 3484: =cut 3485: 3486: sub copyrightdescription { 3487: return &mt($cprtag{shift(@_)}); 3488: } 3489: 3490: =pod 3491: 3492: =item * &source_copyrightids() 3493: 3494: returns list of all source copyrights 3495: 3496: =cut 3497: 3498: sub source_copyrightids { 3499: return sort(keys(%scprtag)); 3500: } 3501: 3502: =pod 3503: 3504: =item * &source_copyrightdescription() 3505: 3506: returns description of a specified source copyright id 3507: 3508: =cut 3509: 3510: sub source_copyrightdescription { 3511: return &mt($scprtag{shift(@_)}); 3512: } 3513: 3514: =pod 3515: 3516: =item * &filecategories() 3517: 3518: returns list of all file categories 3519: 3520: =cut 3521: 3522: sub filecategories { 3523: return sort(keys(%category_extensions)); 3524: } 3525: 3526: =pod 3527: 3528: =item * &filecategorytypes() 3529: 3530: returns list of file types belonging to a given file 3531: category 3532: 3533: =cut 3534: 3535: sub filecategorytypes { 3536: my ($cat) = @_; 3537: return @{$category_extensions{lc($cat)}}; 3538: } 3539: 3540: =pod 3541: 3542: =item * &fileembstyle() 3543: 3544: returns embedding style for a specified file type 3545: 3546: =cut 3547: 3548: sub fileembstyle { 3549: return $fe{lc(shift(@_))}; 3550: } 3551: 3552: sub filemimetype { 3553: return $fm{lc(shift(@_))}; 3554: } 3555: 3556: 3557: sub filecategoryselect { 3558: my ($name,$value)=@_; 3559: return &select_form($value,$name, 3560: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))}); 3561: } 3562: 3563: =pod 3564: 3565: =item * &filedescription() 3566: 3567: returns description for a specified file type 3568: 3569: =cut 3570: 3571: sub filedescription { 3572: my $file_description = $fd{lc(shift())}; 3573: $file_description =~ s:([\[\]]):~$1:g; 3574: return &mt($file_description); 3575: } 3576: 3577: =pod 3578: 3579: =item * &filedescriptionex() 3580: 3581: returns description for a specified file type with 3582: extra formatting 3583: 3584: =cut 3585: 3586: sub filedescriptionex { 3587: my $ex=shift; 3588: my $file_description = $fd{lc($ex)}; 3589: $file_description =~ s:([\[\]]):~$1:g; 3590: return '.'.$ex.' '.&mt($file_description); 3591: } 3592: 3593: # End of .tab access 3594: =pod 3595: 3596: =back 3597: 3598: =cut 3599: 3600: # ------------------------------------------------------------------ File Types 3601: sub fileextensions { 3602: return sort(keys(%fe)); 3603: } 3604: 3605: # ----------------------------------------------------------- Display Languages 3606: # returns a hash with all desired display languages 3607: # 3608: 3609: sub display_languages { 3610: my %languages=(); 3611: foreach my $lang (&Apache::lonlocal::preferred_languages()) { 3612: $languages{$lang}=1; 3613: } 3614: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']); 3615: if ($env{'form.displaylanguage'}) { 3616: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) { 3617: $languages{$lang}=1; 3618: } 3619: } 3620: return %languages; 3621: } 3622: 3623: sub languages { 3624: my ($possible_langs) = @_; 3625: my @preferred_langs = &Apache::lonlocal::preferred_languages(); 3626: if (!ref($possible_langs)) { 3627: if( wantarray ) { 3628: return @preferred_langs; 3629: } else { 3630: return $preferred_langs[0]; 3631: } 3632: } 3633: my %possibilities = map { $_ => 1 } (@$possible_langs); 3634: my @preferred_possibilities; 3635: foreach my $preferred_lang (@preferred_langs) { 3636: if (exists($possibilities{$preferred_lang})) { 3637: push(@preferred_possibilities, $preferred_lang); 3638: } 3639: } 3640: if( wantarray ) { 3641: return @preferred_possibilities; 3642: } 3643: return $preferred_possibilities[0]; 3644: } 3645: 3646: sub user_lang { 3647: my ($touname,$toudom,$fromcid) = @_; 3648: my @userlangs; 3649: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) { 3650: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/, 3651: $env{'course.'.$fromcid.'.languages'})); 3652: } else { 3653: my %langhash = &getlangs($touname,$toudom); 3654: if ($langhash{'languages'} ne '') { 3655: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'}); 3656: } else { 3657: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom); 3658: if ($domdefs{'lang_def'} ne '') { 3659: @userlangs = ($domdefs{'lang_def'}); 3660: } 3661: } 3662: } 3663: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs); 3664: my $user_lh = Apache::localize->get_handle(@languages); 3665: return $user_lh; 3666: } 3667: 3668: 3669: ############################################################### 3670: ## Student Answer Attempts ## 3671: ############################################################### 3672: 3673: =pod 3674: 3675: =head1 Alternate Problem Views 3676: 3677: =over 4 3678: 3679: =item * &get_previous_attempt($symb, $username, $domain, $course, 3680: $getattempt, $regexp, $gradesub, $usec, $identifier) 3681: 3682: Return string with previous attempt on problem. Arguments: 3683: 3684: =over 4 3685: 3686: =item * $symb: Problem, including path 3687: 3688: =item * $username: username of the desired student 3689: 3690: =item * $domain: domain of the desired student 3691: 3692: =item * $course: Course ID 3693: 3694: =item * $getattempt: Leave blank for all attempts, otherwise put 3695: something 3696: 3697: =item * $regexp: if string matches this regexp, the string will be 3698: sent to $gradesub 3699: 3700: =item * $gradesub: routine that processes the string if it matches $regexp 3701: 3702: =item * $usec: section of the desired student 3703: 3704: =item * $identifier: counter for student (multiple students one problem) or 3705: problem (one student; whole sequence). 3706: 3707: =back 3708: 3709: The output string is a table containing all desired attempts, if any. 3710: 3711: =cut 3712: 3713: sub get_previous_attempt { 3714: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_; 3715: my $prevattempts=''; 3716: no strict 'refs'; 3717: if ($symb) { 3718: my (%returnhash)= 3719: &Apache::lonnet::restore($symb,$course,$domain,$username); 3720: if ($returnhash{'version'}) { 3721: my %lasthash=(); 3722: my $version; 3723: for ($version=1;$version<=$returnhash{'version'};$version++) { 3724: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) { 3725: if ($key =~ /\.rawrndseed$/) { 3726: my ($id) = ($key =~ /^(.+)\.rawrndseed$/); 3727: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key}; 3728: } else { 3729: $lasthash{$key}=$returnhash{$version.':'.$key}; 3730: } 3731: } 3732: } 3733: $prevattempts=&start_data_table().&start_data_table_header_row(); 3734: $prevattempts.='<th>'.&mt('History').'</th>'; 3735: my (%typeparts,%lasthidden,%regraded,%hidestatus); 3736: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'}); 3737: foreach my $key (sort(keys(%lasthash))) { 3738: my ($ign,@parts) = split(/\./,$key); 3739: if ($#parts > 0) { 3740: my $data=$parts[-1]; 3741: next if ($data eq 'foilorder'); 3742: pop(@parts); 3743: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>'; 3744: if ($data eq 'type') { 3745: unless ($showsurv) { 3746: my $id = join(',',@parts); 3747: $typeparts{$ign.'.'.$id} = $lasthash{$key}; 3748: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) { 3749: $lasthidden{$ign.'.'.$id} = 1; 3750: } 3751: } 3752: if ($identifier ne '') { 3753: my $id = join(',',@parts); 3754: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb, 3755: $domain,$username,$usec,undef,$course) =~ /^no/) { 3756: $hidestatus{$ign.'.'.$id} = 1; 3757: } 3758: } 3759: } elsif ($data eq 'regrader') { 3760: if (($identifier ne '') && (@parts)) { 3761: my $id = join(',',@parts); 3762: $regraded{$ign.'.'.$id} = 1; 3763: } 3764: } 3765: } else { 3766: if ($#parts == 0) { 3767: $prevattempts.='<th>'.$parts[0].'</th>'; 3768: } else { 3769: $prevattempts.='<th>'.$ign.'</th>'; 3770: } 3771: } 3772: } 3773: $prevattempts.=&end_data_table_header_row(); 3774: if ($getattempt eq '') { 3775: my (%solved,%resets,%probstatus); 3776: if (($identifier ne '') && (keys(%regraded) > 0)) { 3777: for ($version=1;$version<=$returnhash{'version'};$version++) { 3778: foreach my $id (keys(%regraded)) { 3779: if (($returnhash{$version.':'.$id.'.regrader'}) && 3780: ($returnhash{$version.':'.$id.'.tries'} eq '') && 3781: ($returnhash{$version.':'.$id.'.award'} eq '')) { 3782: push(@{$resets{$id}},$version); 3783: } 3784: } 3785: } 3786: } 3787: for ($version=1;$version<=$returnhash{'version'};$version++) { 3788: my (@hidden,@unsolved); 3789: if (%typeparts) { 3790: foreach my $id (keys(%typeparts)) { 3791: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 3792: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) { 3793: push(@hidden,$id); 3794: } elsif ($identifier ne '') { 3795: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') || 3796: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') || 3797: ($hidestatus{$id})) { 3798: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}})); 3799: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') { 3800: push(@{$solved{$id}},$version); 3801: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') && 3802: (ref($solved{$id}) eq 'ARRAY')) { 3803: my $skip; 3804: if (ref($resets{$id}) eq 'ARRAY') { 3805: foreach my $reset (@{$resets{$id}}) { 3806: if ($reset > $solved{$id}[-1]) { 3807: $skip=1; 3808: last; 3809: } 3810: } 3811: } 3812: unless ($skip) { 3813: my ($ign,$partslist) = split(/\./,$id,2); 3814: push(@unsolved,$partslist); 3815: } 3816: } 3817: } 3818: } 3819: } 3820: } 3821: $prevattempts.=&start_data_table_row(). 3822: '<td>'.&mt('Transaction [_1]',$version); 3823: if (@unsolved) { 3824: $prevattempts .= '<span class="LC_nobreak"><label>'. 3825: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'. 3826: &mt('Hide').'</label></span>'; 3827: } 3828: $prevattempts .= '</td>'; 3829: if (@hidden) { 3830: foreach my $key (sort(keys(%lasthash))) { 3831: next if ($key =~ /\.foilorder$/); 3832: my $hide; 3833: foreach my $id (@hidden) { 3834: if ($key =~ /^\Q$id\E/) { 3835: $hide = 1; 3836: last; 3837: } 3838: } 3839: if ($hide) { 3840: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/); 3841: if (($data eq 'award') || ($data eq 'awarddetail')) { 3842: my $value = &format_previous_attempt_value($key, 3843: $returnhash{$version.':'.$key}); 3844: $prevattempts.='<td>'.$value.' </td>'; 3845: } else { 3846: $prevattempts.='<td> </td>'; 3847: } 3848: } else { 3849: if ($key =~ /\./) { 3850: my $value = $returnhash{$version.':'.$key}; 3851: if ($key =~ /\.rndseed$/) { 3852: my ($id) = ($key =~ /^(.+)\.rndseed$/); 3853: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) { 3854: $value = $returnhash{$version.':'.$id.'.rawrndseed'}; 3855: } 3856: } 3857: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value). 3858: ' </td>'; 3859: } else { 3860: $prevattempts.='<td> </td>'; 3861: } 3862: } 3863: } 3864: } else { 3865: foreach my $key (sort(keys(%lasthash))) { 3866: next if ($key =~ /\.foilorder$/); 3867: my $value = $returnhash{$version.':'.$key}; 3868: if ($key =~ /\.rndseed$/) { 3869: my ($id) = ($key =~ /^(.+)\.rndseed$/); 3870: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) { 3871: $value = $returnhash{$version.':'.$id.'.rawrndseed'}; 3872: } 3873: } 3874: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value). 3875: ' </td>'; 3876: } 3877: } 3878: $prevattempts.=&end_data_table_row(); 3879: } 3880: } 3881: my @currhidden = keys(%lasthidden); 3882: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>'; 3883: foreach my $key (sort(keys(%lasthash))) { 3884: next if ($key =~ /\.foilorder$/); 3885: if (%typeparts) { 3886: my $hidden; 3887: foreach my $id (@currhidden) { 3888: if ($key =~ /^\Q$id\E/) { 3889: $hidden = 1; 3890: last; 3891: } 3892: } 3893: if ($hidden) { 3894: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/); 3895: if (($data eq 'award') || ($data eq 'awarddetail')) { 3896: my $value = &format_previous_attempt_value($key,$lasthash{$key}); 3897: if ($key =~/$regexp$/ && (defined &$gradesub)) { 3898: $value = &$gradesub($value); 3899: } 3900: $prevattempts.='<td>'.$value.' </td>'; 3901: } else { 3902: $prevattempts.='<td> </td>'; 3903: } 3904: } else { 3905: my $value = &format_previous_attempt_value($key,$lasthash{$key}); 3906: if ($key =~/$regexp$/ && (defined &$gradesub)) { 3907: $value = &$gradesub($value); 3908: } 3909: $prevattempts.='<td>'.$value.' </td>'; 3910: } 3911: } else { 3912: my $value = &format_previous_attempt_value($key,$lasthash{$key}); 3913: if ($key =~/$regexp$/ && (defined &$gradesub)) { 3914: $value = &$gradesub($value); 3915: } 3916: $prevattempts.='<td>'.$value.' </td>'; 3917: } 3918: } 3919: $prevattempts.= &end_data_table_row().&end_data_table(); 3920: } else { 3921: $prevattempts= 3922: &start_data_table().&start_data_table_row(). 3923: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'. 3924: &end_data_table_row().&end_data_table(); 3925: } 3926: } else { 3927: $prevattempts= 3928: &start_data_table().&start_data_table_row(). 3929: '<td>'.&mt('No data.').'</td>'. 3930: &end_data_table_row().&end_data_table(); 3931: } 3932: } 3933: 3934: sub format_previous_attempt_value { 3935: my ($key,$value) = @_; 3936: if (($key =~ /timestamp/) || ($key=~/duedate/)) { 3937: $value = &Apache::lonlocal::locallocaltime($value); 3938: } elsif (ref($value) eq 'ARRAY') { 3939: $value = '('.join(', ', @{ $value }).')'; 3940: } elsif ($key =~ /answerstring$/) { 3941: my %answers = &Apache::lonnet::str2hash($value); 3942: my @anskeys = sort(keys(%answers)); 3943: if (@anskeys == 1) { 3944: my $answer = $answers{$anskeys[0]}; 3945: if ($answer =~ m{\0}) { 3946: $answer =~ s{\0}{,}g; 3947: } 3948: my $tag_internal_answer_name = 'INTERNAL'; 3949: if ($anskeys[0] eq $tag_internal_answer_name) { 3950: $value = $answer; 3951: } else { 3952: $value = $anskeys[0].'='.$answer; 3953: } 3954: } else { 3955: foreach my $ans (@anskeys) { 3956: my $answer = $answers{$ans}; 3957: if ($answer =~ m{\0}) { 3958: $answer =~ s{\0}{,}g; 3959: } 3960: $value .= $ans.'='.$answer.'<br />';; 3961: } 3962: } 3963: } else { 3964: $value = &unescape($value); 3965: } 3966: return $value; 3967: } 3968: 3969: 3970: sub relative_to_absolute { 3971: my ($url,$output)=@_; 3972: my $parser=HTML::TokeParser->new(\$output); 3973: my $token; 3974: my $thisdir=$url; 3975: my @rlinks=(); 3976: while ($token=$parser->get_token) { 3977: if ($token->[0] eq 'S') { 3978: if ($token->[1] eq 'a') { 3979: if ($token->[2]->{'href'}) { 3980: $rlinks[$#rlinks+1]=$token->[2]->{'href'}; 3981: } 3982: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) { 3983: $rlinks[$#rlinks+1]=$token->[2]->{'src'}; 3984: } elsif ($token->[1] eq 'base') { 3985: $thisdir=$token->[2]->{'href'}; 3986: } 3987: } 3988: } 3989: $thisdir=~s-/[^/]*$--; 3990: foreach my $link (@rlinks) { 3991: unless (($link=~/^https?\:\/\//i) || 3992: ($link=~/^\//) || 3993: ($link=~/^javascript:/i) || 3994: ($link=~/^mailto:/i) || 3995: ($link=~/^\#/)) { 3996: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link); 3997: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/; 3998: } 3999: } 4000: # -------------------------------------------------- Deal with Applet codebases 4001: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei; 4002: return $output; 4003: } 4004: 4005: =pod 4006: 4007: =item * &get_student_view() 4008: 4009: show a snapshot of what student was looking at 4010: 4011: =cut 4012: 4013: sub get_student_view { 4014: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_; 4015: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb); 4016: my (%form); 4017: my @elements=('symb','courseid','domain','username'); 4018: foreach my $element (@elements) { 4019: $form{'grade_'.$element}=eval '$'.$element #' 4020: } 4021: if (defined($moreenv)) { 4022: %form=(%form,%{$moreenv}); 4023: } 4024: if (defined($target)) { $form{'grade_target'} = $target; } 4025: $feedurl=&Apache::lonnet::clutter($feedurl); 4026: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form); 4027: $userview=~s/\<body[^\>]*\>//gi; 4028: $userview=~s/\<\/body\>//gi; 4029: $userview=~s/\<html\>//gi; 4030: $userview=~s/\<\/html\>//gi; 4031: $userview=~s/\<head\>//gi; 4032: $userview=~s/\<\/head\>//gi; 4033: $userview=~s/action\s*\=/would_be_action\=/gi; 4034: $userview=&relative_to_absolute($feedurl,$userview); 4035: if (wantarray) { 4036: return ($userview,$response); 4037: } else { 4038: return $userview; 4039: } 4040: } 4041: 4042: sub get_student_view_with_retries { 4043: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_; 4044: 4045: my $ok = 0; # True if we got a good response. 4046: my $content; 4047: my $response; 4048: 4049: # Try to get the student_view done. within the retries count: 4050: 4051: do { 4052: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv); 4053: $ok = $response->is_success; 4054: if (!$ok) { 4055: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message); 4056: } 4057: $retries--; 4058: } while (!$ok && ($retries > 0)); 4059: 4060: if (!$ok) { 4061: $content = ''; # On error return an empty content. 4062: } 4063: if (wantarray) { 4064: return ($content, $response); 4065: } else { 4066: return $content; 4067: } 4068: } 4069: 4070: =pod 4071: 4072: =item * &get_student_answers() 4073: 4074: show a snapshot of how student was answering problem 4075: 4076: =cut 4077: 4078: sub get_student_answers { 4079: my ($symb,$username,$domain,$courseid,%form) = @_; 4080: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb); 4081: my (%moreenv); 4082: my @elements=('symb','courseid','domain','username'); 4083: foreach my $element (@elements) { 4084: $moreenv{'grade_'.$element}=eval '$'.$element #' 4085: } 4086: $moreenv{'grade_target'}='answer'; 4087: %moreenv=(%form,%moreenv); 4088: $feedurl = &Apache::lonnet::clutter($feedurl); 4089: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv); 4090: return $userview; 4091: } 4092: 4093: =pod 4094: 4095: =item * &submlink() 4096: 4097: Inputs: $text $uname $udom $symb $target 4098: 4099: Returns: A link to grades.pm such as to see the SUBM view of a student 4100: 4101: =cut 4102: 4103: ############################################### 4104: sub submlink { 4105: my ($text,$uname,$udom,$symb,$target)=@_; 4106: if (!($uname && $udom)) { 4107: (my $cursymb, my $courseid,$udom,$uname)= 4108: &Apache::lonnet::whichuser($symb); 4109: if (!$symb) { $symb=$cursymb; } 4110: } 4111: if (!$symb) { $symb=&Apache::lonnet::symbread(); } 4112: $symb=&escape($symb); 4113: if ($target) { $target=" target=\"$target\""; } 4114: return 4115: '<a href="/adm/grades?command=submission'. 4116: '&symb='.$symb. 4117: '&student='.$uname. 4118: '&userdom='.$udom.'"'. 4119: $target.'>'.$text.'</a>'; 4120: } 4121: ############################################## 4122: 4123: =pod 4124: 4125: =item * &pgrdlink() 4126: 4127: Inputs: $text $uname $udom $symb $target 4128: 4129: Returns: A link to grades.pm such as to see the PGRD view of a student 4130: 4131: =cut 4132: 4133: ############################################### 4134: sub pgrdlink { 4135: my $link=&submlink(@_); 4136: $link=~s/(&command=submission)/$1&showgrading=yes/; 4137: return $link; 4138: } 4139: ############################################## 4140: 4141: =pod 4142: 4143: =item * &pprmlink() 4144: 4145: Inputs: $text $uname $udom $symb $target 4146: 4147: Returns: A link to parmset.pm such as to see the PPRM view of a 4148: student and a specific resource 4149: 4150: =cut 4151: 4152: ############################################### 4153: sub pprmlink { 4154: my ($text,$uname,$udom,$symb,$target)=@_; 4155: if (!($uname && $udom)) { 4156: (my $cursymb, my $courseid,$udom,$uname)= 4157: &Apache::lonnet::whichuser($symb); 4158: if (!$symb) { $symb=$cursymb; } 4159: } 4160: if (!$symb) { $symb=&Apache::lonnet::symbread(); } 4161: $symb=&escape($symb); 4162: if ($target) { $target="target=\"$target\""; } 4163: return '<a href="/adm/parmset?command=set&'. 4164: 'symb='.$symb.'&uname='.$uname. 4165: '&udom='.$udom.'" '.$target.'>'.$text.'</a>'; 4166: } 4167: ############################################## 4168: 4169: =pod 4170: 4171: =back 4172: 4173: =cut 4174: 4175: ############################################### 4176: 4177: 4178: sub timehash { 4179: my ($thistime) = @_; 4180: my $timezone = &Apache::lonlocal::gettimezone(); 4181: my $dt = DateTime->from_epoch(epoch => $thistime) 4182: ->set_time_zone($timezone); 4183: my $wday = $dt->day_of_week(); 4184: if ($wday == 7) { $wday = 0; } 4185: return ( 'second' => $dt->second(), 4186: 'minute' => $dt->minute(), 4187: 'hour' => $dt->hour(), 4188: 'day' => $dt->day_of_month(), 4189: 'month' => $dt->month(), 4190: 'year' => $dt->year(), 4191: 'weekday' => $wday, 4192: 'dayyear' => $dt->day_of_year(), 4193: 'dlsav' => $dt->is_dst() ); 4194: } 4195: 4196: sub utc_string { 4197: my ($date)=@_; 4198: return strftime("%Y%m%dT%H%M%SZ",gmtime($date)); 4199: } 4200: 4201: sub maketime { 4202: my %th=@_; 4203: my ($epoch_time,$timezone,$dt); 4204: $timezone = &Apache::lonlocal::gettimezone(); 4205: eval { 4206: $dt = DateTime->new( year => $th{'year'}, 4207: month => $th{'month'}, 4208: day => $th{'day'}, 4209: hour => $th{'hour'}, 4210: minute => $th{'minute'}, 4211: second => $th{'second'}, 4212: time_zone => $timezone, 4213: ); 4214: }; 4215: if (!$@) { 4216: $epoch_time = $dt->epoch; 4217: if ($epoch_time) { 4218: return $epoch_time; 4219: } 4220: } 4221: return POSIX::mktime( 4222: ($th{'seconds'},$th{'minutes'},$th{'hours'}, 4223: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1)); 4224: } 4225: 4226: ######################################### 4227: 4228: sub findallcourses { 4229: my ($roles,$uname,$udom) = @_; 4230: my %roles; 4231: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; } 4232: my %courses; 4233: my $now=time; 4234: if (!defined($uname)) { 4235: $uname = $env{'user.name'}; 4236: } 4237: if (!defined($udom)) { 4238: $udom = $env{'user.domain'}; 4239: } 4240: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) { 4241: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname); 4242: if (!%roles) { 4243: %roles = ( 4244: cc => 1, 4245: co => 1, 4246: in => 1, 4247: ep => 1, 4248: ta => 1, 4249: cr => 1, 4250: st => 1, 4251: ); 4252: } 4253: foreach my $entry (keys(%roleshash)) { 4254: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry}); 4255: if ($trole =~ /^cr/) { 4256: next if (!exists($roles{$trole}) && !exists($roles{'cr'})); 4257: } else { 4258: next if (!exists($roles{$trole})); 4259: } 4260: if ($tend) { 4261: next if ($tend < $now); 4262: } 4263: if ($tstart) { 4264: next if ($tstart > $now); 4265: } 4266: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role); 4267: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry); 4268: my $value = $trole.'/'.$cdom.'/'; 4269: if ($secpart eq '') { 4270: ($cnum,$role) = split(/_/,$cnumpart); 4271: $sec = 'none'; 4272: $value .= $cnum.'/'; 4273: } else { 4274: $cnum = $cnumpart; 4275: ($sec,$role) = split(/_/,$secpart); 4276: $value .= $cnum.'/'.$sec; 4277: } 4278: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') { 4279: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) { 4280: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value); 4281: } 4282: } else { 4283: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value); 4284: } 4285: } 4286: } else { 4287: foreach my $key (keys(%env)) { 4288: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} || 4289: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) { 4290: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4); 4291: next if ($role eq 'ca' || $role eq 'aa'); 4292: next if (%roles && !exists($roles{$role})); 4293: my ($starttime,$endtime)=split(/\./,$env{$key}); 4294: my $active=1; 4295: if ($starttime) { 4296: if ($now<$starttime) { $active=0; } 4297: } 4298: if ($endtime) { 4299: if ($now>$endtime) { $active=0; } 4300: } 4301: if ($active) { 4302: my $value = $role.'/'.$cdom.'/'.$cnum.'/'; 4303: if ($sec eq '') { 4304: $sec = 'none'; 4305: } else { 4306: $value .= $sec; 4307: } 4308: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') { 4309: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) { 4310: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value); 4311: } 4312: } else { 4313: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value); 4314: } 4315: } 4316: } 4317: } 4318: } 4319: return %courses; 4320: } 4321: 4322: ############################################### 4323: 4324: sub blockcheck { 4325: my ($setters,$activity,$uname,$udom,$url,$is_course) = @_; 4326: 4327: if (defined($udom) && defined($uname)) { 4328: # If uname and udom are for a course, check for blocks in the course. 4329: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) { 4330: my ($startblock,$endblock,$triggerblock) = 4331: &get_blocks($setters,$activity,$udom,$uname,$url); 4332: return ($startblock,$endblock,$triggerblock); 4333: } 4334: } else { 4335: $udom = $env{'user.domain'}; 4336: $uname = $env{'user.name'}; 4337: } 4338: 4339: my $startblock = 0; 4340: my $endblock = 0; 4341: my $triggerblock = ''; 4342: my %live_courses = &findallcourses(undef,$uname,$udom); 4343: 4344: # If uname is for a user, and activity is course-specific, i.e., 4345: # boards, chat or groups, check for blocking in current course only. 4346: 4347: if (($activity eq 'boards' || $activity eq 'chat' || 4348: $activity eq 'groups' || $activity eq 'printout') && 4349: ($env{'request.course.id'})) { 4350: foreach my $key (keys(%live_courses)) { 4351: if ($key ne $env{'request.course.id'}) { 4352: delete($live_courses{$key}); 4353: } 4354: } 4355: } 4356: 4357: my $otheruser = 0; 4358: my %own_courses; 4359: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) { 4360: # Resource belongs to user other than current user. 4361: $otheruser = 1; 4362: # Gather courses for current user 4363: %own_courses = 4364: &findallcourses(undef,$env{'user.name'},$env{'user.domain'}); 4365: } 4366: 4367: # Gather active course roles - course coordinator, instructor, 4368: # exam proctor, ta, student, or custom role. 4369: 4370: foreach my $course (keys(%live_courses)) { 4371: my ($cdom,$cnum); 4372: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) { 4373: $cdom = $env{'course.'.$course.'.domain'}; 4374: $cnum = $env{'course.'.$course.'.num'}; 4375: } else { 4376: ($cdom,$cnum) = split(/_/,$course); 4377: } 4378: my $no_ownblock = 0; 4379: my $no_userblock = 0; 4380: if ($otheruser && $activity ne 'com') { 4381: # Check if current user has 'evb' priv for this 4382: if (defined($own_courses{$course})) { 4383: foreach my $sec (keys(%{$own_courses{$course}})) { 4384: my $checkrole = 'cm./'.$cdom.'/'.$cnum; 4385: if ($sec ne 'none') { 4386: $checkrole .= '/'.$sec; 4387: } 4388: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) { 4389: $no_ownblock = 1; 4390: last; 4391: } 4392: } 4393: } 4394: # if they have 'evb' priv and are currently not playing student 4395: next if (($no_ownblock) && 4396: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})); 4397: } 4398: foreach my $sec (keys(%{$live_courses{$course}})) { 4399: my $checkrole = 'cm./'.$cdom.'/'.$cnum; 4400: if ($sec ne 'none') { 4401: $checkrole .= '/'.$sec; 4402: } 4403: if ($otheruser) { 4404: # Resource belongs to user other than current user. 4405: # Assemble privs for that user, and check for 'evb' priv. 4406: my (%allroles,%userroles); 4407: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') { 4408: foreach my $entry (@{$live_courses{$course}{$sec}}) { 4409: my ($trole,$tdom,$tnum,$tsec); 4410: if ($entry =~ /^cr/) { 4411: ($trole,$tdom,$tnum,$tsec) = 4412: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|); 4413: } else { 4414: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry); 4415: } 4416: my ($spec,$area,$trest); 4417: $area = '/'.$tdom.'/'.$tnum; 4418: $trest = $tnum; 4419: if ($tsec ne '') { 4420: $area .= '/'.$tsec; 4421: $trest .= '/'.$tsec; 4422: } 4423: $spec = $trole.'.'.$area; 4424: if ($trole =~ /^cr/) { 4425: &Apache::lonnet::custom_roleprivs(\%allroles,$trole, 4426: $tdom,$spec,$trest,$area); 4427: } else { 4428: &Apache::lonnet::standard_roleprivs(\%allroles,$trole, 4429: $tdom,$spec,$trest,$area); 4430: } 4431: } 4432: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles); 4433: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) { 4434: if ($1) { 4435: $no_userblock = 1; 4436: last; 4437: } 4438: } 4439: } 4440: } else { 4441: # Resource belongs to current user 4442: # Check for 'evb' priv via lonnet::allowed(). 4443: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) { 4444: $no_ownblock = 1; 4445: last; 4446: } 4447: } 4448: } 4449: # if they have the evb priv and are currently not playing student 4450: next if (($no_ownblock) && 4451: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E})); 4452: next if ($no_userblock); 4453: 4454: # Retrieve blocking times and identity of locker for course 4455: # of specified user, unless user has 'evb' privilege. 4456: 4457: my ($start,$end,$trigger) = 4458: &get_blocks($setters,$activity,$cdom,$cnum,$url); 4459: if (($start != 0) && 4460: (($startblock == 0) || ($startblock > $start))) { 4461: $startblock = $start; 4462: if ($trigger ne '') { 4463: $triggerblock = $trigger; 4464: } 4465: } 4466: if (($end != 0) && 4467: (($endblock == 0) || ($endblock < $end))) { 4468: $endblock = $end; 4469: if ($trigger ne '') { 4470: $triggerblock = $trigger; 4471: } 4472: } 4473: } 4474: return ($startblock,$endblock,$triggerblock); 4475: } 4476: 4477: sub get_blocks { 4478: my ($setters,$activity,$cdom,$cnum,$url) = @_; 4479: my $startblock = 0; 4480: my $endblock = 0; 4481: my $triggerblock = ''; 4482: my $course = $cdom.'_'.$cnum; 4483: $setters->{$course} = {}; 4484: $setters->{$course}{'staff'} = []; 4485: $setters->{$course}{'times'} = []; 4486: $setters->{$course}{'triggers'} = []; 4487: my (@blockers,%triggered); 4488: my $now = time; 4489: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum); 4490: if ($activity eq 'docs') { 4491: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks); 4492: foreach my $block (@blockers) { 4493: if ($block =~ /^firstaccess____(.+)$/) { 4494: my $item = $1; 4495: my $type = 'map'; 4496: my $timersymb = $item; 4497: if ($item eq 'course') { 4498: $type = 'course'; 4499: } elsif ($item =~ /___\d+___/) { 4500: $type = 'resource'; 4501: } else { 4502: $timersymb = &Apache::lonnet::symbread($item); 4503: } 4504: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb}; 4505: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 4506: $triggered{$block} = { 4507: start => $start, 4508: end => $end, 4509: type => $type, 4510: }; 4511: } 4512: } 4513: } else { 4514: foreach my $block (keys(%commblocks)) { 4515: if ($block =~ m/^(\d+)____(\d+)$/) { 4516: my ($start,$end) = ($1,$2); 4517: if ($start <= time && $end >= time) { 4518: if (ref($commblocks{$block}) eq 'HASH') { 4519: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') { 4520: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') { 4521: unless(grep(/^\Q$block\E$/,@blockers)) { 4522: push(@blockers,$block); 4523: } 4524: } 4525: } 4526: } 4527: } 4528: } elsif ($block =~ /^firstaccess____(.+)$/) { 4529: my $item = $1; 4530: my $timersymb = $item; 4531: my $type = 'map'; 4532: if ($item eq 'course') { 4533: $type = 'course'; 4534: } elsif ($item =~ /___\d+___/) { 4535: $type = 'resource'; 4536: } else { 4537: $timersymb = &Apache::lonnet::symbread($item); 4538: } 4539: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb}; 4540: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 4541: if ($start && $end) { 4542: if (($start <= time) && ($end >= time)) { 4543: unless (grep(/^\Q$block\E$/,@blockers)) { 4544: push(@blockers,$block); 4545: $triggered{$block} = { 4546: start => $start, 4547: end => $end, 4548: type => $type, 4549: }; 4550: } 4551: } 4552: } 4553: } 4554: } 4555: } 4556: foreach my $blocker (@blockers) { 4557: my ($staff_name,$staff_dom,$title,$blocks) = 4558: &parse_block_record($commblocks{$blocker}); 4559: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]); 4560: my ($start,$end,$triggertype); 4561: if ($blocker =~ m/^(\d+)____(\d+)$/) { 4562: ($start,$end) = ($1,$2); 4563: } elsif (ref($triggered{$blocker}) eq 'HASH') { 4564: $start = $triggered{$blocker}{'start'}; 4565: $end = $triggered{$blocker}{'end'}; 4566: $triggertype = $triggered{$blocker}{'type'}; 4567: } 4568: if ($start) { 4569: push(@{$$setters{$course}{'times'}}, [$start,$end]); 4570: if ($triggertype) { 4571: push(@{$$setters{$course}{'triggers'}},$triggertype); 4572: } else { 4573: push(@{$$setters{$course}{'triggers'}},0); 4574: } 4575: if ( ($startblock == 0) || ($startblock > $start) ) { 4576: $startblock = $start; 4577: if ($triggertype) { 4578: $triggerblock = $blocker; 4579: } 4580: } 4581: if ( ($endblock == 0) || ($endblock < $end) ) { 4582: $endblock = $end; 4583: if ($triggertype) { 4584: $triggerblock = $blocker; 4585: } 4586: } 4587: } 4588: } 4589: return ($startblock,$endblock,$triggerblock); 4590: } 4591: 4592: sub parse_block_record { 4593: my ($record) = @_; 4594: my ($setuname,$setudom,$title,$blocks); 4595: if (ref($record) eq 'HASH') { 4596: ($setuname,$setudom) = split(/:/,$record->{'setter'}); 4597: $title = &unescape($record->{'event'}); 4598: $blocks = $record->{'blocks'}; 4599: } else { 4600: my @data = split(/:/,$record,3); 4601: if (scalar(@data) eq 2) { 4602: $title = $data[1]; 4603: ($setuname,$setudom) = split(/@/,$data[0]); 4604: } else { 4605: ($setuname,$setudom,$title) = @data; 4606: } 4607: $blocks = { 'com' => 'on' }; 4608: } 4609: return ($setuname,$setudom,$title,$blocks); 4610: } 4611: 4612: sub blocking_status { 4613: my ($activity,$uname,$udom,$url,$is_course) = @_; 4614: my %setters; 4615: 4616: # check for active blocking 4617: my ($startblock,$endblock,$triggerblock) = 4618: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course); 4619: my $blocked = 0; 4620: if ($startblock && $endblock) { 4621: $blocked = 1; 4622: } 4623: 4624: # caller just wants to know whether a block is active 4625: if (!wantarray) { return $blocked; } 4626: 4627: # build a link to a popup window containing the details 4628: my $querystring = "?activity=$activity"; 4629: # $uname and $udom decide whose portfolio the user is trying to look at 4630: if ($activity eq 'port') { 4631: $querystring .= "&udom=$udom" if $udom; 4632: $querystring .= "&uname=$uname" if $uname; 4633: } elsif ($activity eq 'docs') { 4634: $querystring .= '&url='.&HTML::Entities::encode($url,'&"'); 4635: } 4636: 4637: my $output .= <<'END_MYBLOCK'; 4638: function openWindow(url, wdwName, w, h, toolbar,scrollbar) { 4639: var options = "width=" + w + ",height=" + h + ","; 4640: options += "resizable=yes,scrollbars="+scrollbar+",status=no,"; 4641: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no"; 4642: var newWin = window.open(url, wdwName, options); 4643: newWin.focus(); 4644: } 4645: END_MYBLOCK 4646: 4647: $output = Apache::lonhtmlcommon::scripttag($output); 4648: 4649: my $popupUrl = "/adm/blockingstatus/$querystring"; 4650: my $text = &mt('Communication Blocked'); 4651: if ($activity eq 'docs') { 4652: $text = &mt('Content Access Blocked'); 4653: } elsif ($activity eq 'printout') { 4654: $text = &mt('Printing Blocked'); 4655: } 4656: $output .= <<"END_BLOCK"; 4657: <div class='LC_comblock'> 4658: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 4659: title='$text'> 4660: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a> 4661: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 4662: title='$text'>$text</a> 4663: </div> 4664: 4665: END_BLOCK 4666: 4667: return ($blocked, $output); 4668: } 4669: 4670: ############################################### 4671: 4672: sub check_ip_acc { 4673: my ($acc)=@_; 4674: &Apache::lonxml::debug("acc is $acc"); 4675: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) { 4676: return 1; 4677: } 4678: my $allowed=0; 4679: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'}; 4680: 4681: my $name; 4682: foreach my $pattern (split(',',$acc)) { 4683: $pattern =~ s/^\s*//; 4684: $pattern =~ s/\s*$//; 4685: if ($pattern =~ /\*$/) { 4686: #35.8.* 4687: $pattern=~s/\*//; 4688: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; } 4689: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) { 4690: #35.8.3.[34-56] 4691: my $low=$2; 4692: my $high=$3; 4693: $pattern=$1; 4694: if ($ip =~ /^\Q$pattern\E/) { 4695: my $last=(split(/\./,$ip))[3]; 4696: if ($last <=$high && $last >=$low) { $allowed=1; } 4697: } 4698: } elsif ($pattern =~ /^\*/) { 4699: #*.msu.edu 4700: $pattern=~s/\*//; 4701: if (!defined($name)) { 4702: use Socket; 4703: my $netaddr=inet_aton($ip); 4704: ($name)=gethostbyaddr($netaddr,AF_INET); 4705: } 4706: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; } 4707: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) { 4708: #127.0.0.1 4709: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; } 4710: } else { 4711: #some.name.com 4712: if (!defined($name)) { 4713: use Socket; 4714: my $netaddr=inet_aton($ip); 4715: ($name)=gethostbyaddr($netaddr,AF_INET); 4716: } 4717: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; } 4718: } 4719: if ($allowed) { last; } 4720: } 4721: return $allowed; 4722: } 4723: 4724: ############################################### 4725: 4726: =pod 4727: 4728: =head1 Domain Template Functions 4729: 4730: =over 4 4731: 4732: =item * &determinedomain() 4733: 4734: Inputs: $domain (usually will be undef) 4735: 4736: Returns: Determines which domain should be used for designs 4737: 4738: =cut 4739: 4740: ############################################### 4741: sub determinedomain { 4742: my $domain=shift; 4743: if (! $domain) { 4744: # Determine domain if we have not been given one 4745: $domain = &Apache::lonnet::default_login_domain(); 4746: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; } 4747: if ($env{'request.role.domain'}) { 4748: $domain=$env{'request.role.domain'}; 4749: } 4750: } 4751: return $domain; 4752: } 4753: ############################################### 4754: 4755: sub devalidate_domconfig_cache { 4756: my ($udom)=@_; 4757: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom); 4758: } 4759: 4760: # ---------------------- Get domain configuration for a domain 4761: sub get_domainconf { 4762: my ($udom) = @_; 4763: my $cachetime=1800; 4764: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom); 4765: if (defined($cached)) { return %{$result}; } 4766: 4767: my %domconfig = &Apache::lonnet::get_dom('configuration', 4768: ['login','rolecolors','autoenroll'],$udom); 4769: my (%designhash,%legacy); 4770: if (keys(%domconfig) > 0) { 4771: if (ref($domconfig{'login'}) eq 'HASH') { 4772: if (keys(%{$domconfig{'login'}})) { 4773: foreach my $key (keys(%{$domconfig{'login'}})) { 4774: if (ref($domconfig{'login'}{$key}) eq 'HASH') { 4775: if (($key eq 'loginvia') || ($key eq 'headtag')) { 4776: if (ref($domconfig{'login'}{$key}) eq 'HASH') { 4777: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) { 4778: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') { 4779: if ($key eq 'loginvia') { 4780: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) { 4781: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'}; 4782: $designhash{$udom.'.login.loginvia'} = $server; 4783: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') { 4784: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'}; 4785: } else { 4786: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'}; 4787: } 4788: } 4789: } elsif ($key eq 'headtag') { 4790: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) { 4791: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'}; 4792: } 4793: } 4794: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) { 4795: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'}; 4796: } 4797: } 4798: } 4799: } 4800: } else { 4801: foreach my $img (keys(%{$domconfig{'login'}{$key}})) { 4802: $designhash{$udom.'.login.'.$key.'_'.$img} = 4803: $domconfig{'login'}{$key}{$img}; 4804: } 4805: } 4806: } else { 4807: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key}; 4808: } 4809: } 4810: } else { 4811: $legacy{'login'} = 1; 4812: } 4813: } else { 4814: $legacy{'login'} = 1; 4815: } 4816: if (ref($domconfig{'rolecolors'}) eq 'HASH') { 4817: if (keys(%{$domconfig{'rolecolors'}})) { 4818: foreach my $role (keys(%{$domconfig{'rolecolors'}})) { 4819: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') { 4820: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) { 4821: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item}; 4822: } 4823: } 4824: } 4825: } else { 4826: $legacy{'rolecolors'} = 1; 4827: } 4828: } else { 4829: $legacy{'rolecolors'} = 1; 4830: } 4831: if (ref($domconfig{'autoenroll'}) eq 'HASH') { 4832: if ($domconfig{'autoenroll'}{'co-owners'}) { 4833: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'}; 4834: } 4835: } 4836: if (keys(%legacy) > 0) { 4837: my %legacyhash = &get_legacy_domconf($udom); 4838: foreach my $item (keys(%legacyhash)) { 4839: if ($item =~ /^\Q$udom\E\.login/) { 4840: if ($legacy{'login'}) { 4841: $designhash{$item} = $legacyhash{$item}; 4842: } 4843: } else { 4844: if ($legacy{'rolecolors'}) { 4845: $designhash{$item} = $legacyhash{$item}; 4846: } 4847: } 4848: } 4849: } 4850: } else { 4851: %designhash = &get_legacy_domconf($udom); 4852: } 4853: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash, 4854: $cachetime); 4855: return %designhash; 4856: } 4857: 4858: sub get_legacy_domconf { 4859: my ($udom) = @_; 4860: my %legacyhash; 4861: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors'; 4862: my $designfile = $designdir.'/'.$udom.'.tab'; 4863: if (-e $designfile) { 4864: if ( open (my $fh,"<$designfile") ) { 4865: while (my $line = <$fh>) { 4866: next if ($line =~ /^\#/); 4867: chomp($line); 4868: my ($key,$val)=(split(/\=/,$line)); 4869: if ($val) { $legacyhash{$udom.'.'.$key}=$val; } 4870: } 4871: close($fh); 4872: } 4873: } 4874: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') { 4875: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif"; 4876: } 4877: return %legacyhash; 4878: } 4879: 4880: =pod 4881: 4882: =item * &domainlogo() 4883: 4884: Inputs: $domain (usually will be undef) 4885: 4886: Returns: A link to a domain logo, if the domain logo exists. 4887: If the domain logo does not exist, a description of the domain. 4888: 4889: =cut 4890: 4891: ############################################### 4892: sub domainlogo { 4893: my $domain = &determinedomain(shift); 4894: my %designhash = &get_domainconf($domain); 4895: # See if there is a logo 4896: if ($designhash{$domain.'.login.domlogo'} ne '') { 4897: my $imgsrc = $designhash{$domain.'.login.domlogo'}; 4898: if ($imgsrc =~ m{^/(adm|res)/}) { 4899: if ($imgsrc =~ m{^/res/}) { 4900: my $local_name = &Apache::lonnet::filelocation('',$imgsrc); 4901: &Apache::lonnet::repcopy($local_name); 4902: } 4903: $imgsrc = &lonhttpdurl($imgsrc); 4904: } 4905: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />'; 4906: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) { 4907: return &Apache::lonnet::domain($domain,'description'); 4908: } else { 4909: return ''; 4910: } 4911: } 4912: ############################################## 4913: 4914: =pod 4915: 4916: =item * &designparm() 4917: 4918: Inputs: $which parameter; $domain (usually will be undef) 4919: 4920: Returns: value of designparamter $which 4921: 4922: =cut 4923: 4924: 4925: ############################################## 4926: sub designparm { 4927: my ($which,$domain)=@_; 4928: if (exists($env{'environment.color.'.$which})) { 4929: return $env{'environment.color.'.$which}; 4930: } 4931: $domain=&determinedomain($domain); 4932: my %domdesign; 4933: unless ($domain eq 'public') { 4934: %domdesign = &get_domainconf($domain); 4935: } 4936: my $output; 4937: if ($domdesign{$domain.'.'.$which} ne '') { 4938: $output = $domdesign{$domain.'.'.$which}; 4939: } else { 4940: $output = $defaultdesign{$which}; 4941: } 4942: if (($which =~ /^(student|coordinator|author|admin)\.img$/) || 4943: ($which =~ /login\.(img|logo|domlogo|login)/)) { 4944: if ($output =~ m{^/(adm|res)/}) { 4945: if ($output =~ m{^/res/}) { 4946: my $local_name = &Apache::lonnet::filelocation('',$output); 4947: &Apache::lonnet::repcopy($local_name); 4948: } 4949: $output = &lonhttpdurl($output); 4950: } 4951: } 4952: return $output; 4953: } 4954: 4955: ############################################## 4956: =pod 4957: 4958: =item * &authorspace() 4959: 4960: Inputs: $url (usually will be undef). 4961: 4962: Returns: Path to Authoring Space containing the resource or 4963: directory being viewed (or for which action is being taken). 4964: If $url is provided, and begins /priv/<domain>/<uname> 4965: the path will be that portion of the $context argument. 4966: Otherwise the path will be for the author space of the current 4967: user when the current role is author, or for that of the 4968: co-author/assistant co-author space when the current role 4969: is co-author or assistant co-author. 4970: 4971: =cut 4972: 4973: sub authorspace { 4974: my ($url) = @_; 4975: if ($url ne '') { 4976: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) { 4977: return $1; 4978: } 4979: } 4980: my $caname = ''; 4981: my $cadom = ''; 4982: if ($env{'request.role'} =~ /^(?:ca|aa)/) { 4983: ($cadom,$caname) = 4984: ($env{'request.role'}=~/($match_domain)\/($match_username)$/); 4985: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) { 4986: $caname = $env{'user.name'}; 4987: $cadom = $env{'user.domain'}; 4988: } 4989: if (($caname ne '') && ($cadom ne '')) { 4990: return "/priv/$cadom/$caname/"; 4991: } 4992: return; 4993: } 4994: 4995: ############################################## 4996: =pod 4997: 4998: =item * &head_subbox() 4999: 5000: Inputs: $content (contains HTML code with page functions, etc.) 5001: 5002: Returns: HTML div with $content 5003: To be included in page header 5004: 5005: =cut 5006: 5007: sub head_subbox { 5008: my ($content)=@_; 5009: my $output = 5010: '<div class="LC_head_subbox">' 5011: .$content 5012: .'</div>' 5013: } 5014: 5015: ############################################## 5016: =pod 5017: 5018: =item * &CSTR_pageheader() 5019: 5020: Input: (optional) filename from which breadcrumb trail is built. 5021: In most cases no input as needed, as $env{'request.filename'} 5022: is appropriate for use in building the breadcrumb trail. 5023: 5024: Returns: HTML div with CSTR path and recent box 5025: To be included on Authoring Space pages 5026: 5027: =cut 5028: 5029: sub CSTR_pageheader { 5030: my ($trailfile) = @_; 5031: if ($trailfile eq '') { 5032: $trailfile = $env{'request.filename'}; 5033: } 5034: 5035: # this is for resources; directories have customtitle, and crumbs 5036: # and select recent are created in lonpubdir.pm 5037: 5038: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'}; 5039: my ($udom,$uname,$thisdisfn)= 5040: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$}); 5041: my $formaction = "/priv/$udom/$uname/$thisdisfn"; 5042: $formaction =~ s{/+}{/}g; 5043: 5044: my $parentpath = ''; 5045: my $lastitem = ''; 5046: if ($thisdisfn =~ m-(.+/)([^/]*)$-) { 5047: $parentpath = $1; 5048: $lastitem = $2; 5049: } else { 5050: $lastitem = $thisdisfn; 5051: } 5052: 5053: my $output = 5054: '<div>' 5055: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it? 5056: .'<b>'.&mt('Authoring Space:').'</b> ' 5057: .'<form name="dirs" method="post" action="'.$formaction 5058: .'" target="_top">' #FIXME lonpubdir: target="_parent" 5059: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef); 5060: 5061: if ($lastitem) { 5062: $output .= 5063: '<span class="LC_filename">' 5064: .$lastitem 5065: .'</span>'; 5066: } 5067: $output .= 5068: '<br />' 5069: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />" 5070: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()') 5071: .'</form>' 5072: .&Apache::lonmenu::constspaceform() 5073: .'</div>'; 5074: 5075: return $output; 5076: } 5077: 5078: ############################################### 5079: ############################################### 5080: 5081: =pod 5082: 5083: =back 5084: 5085: =head1 HTML Helpers 5086: 5087: =over 4 5088: 5089: =item * &bodytag() 5090: 5091: Returns a uniform header for LON-CAPA web pages. 5092: 5093: Inputs: 5094: 5095: =over 4 5096: 5097: =item * $title, A title to be displayed on the page. 5098: 5099: =item * $function, the current role (can be undef). 5100: 5101: =item * $addentries, extra parameters for the <body> tag. 5102: 5103: =item * $bodyonly, if defined, only return the <body> tag. 5104: 5105: =item * $domain, if defined, force a given domain. 5106: 5107: =item * $forcereg, if page should register as content page (relevant for 5108: text interface only) 5109: 5110: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the 5111: navigational links 5112: 5113: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value 5114: 5115: =item * $no_inline_link, if true and in remote mode, don't show the 5116: 'Switch To Inline Menu' link 5117: 5118: =item * $args, optional argument valid values are 5119: no_auto_mt_title -> prevents &mt()ing the title arg 5120: inherit_jsmath -> when creating popup window in a page, 5121: should it have jsmath forced on by the 5122: current page 5123: 5124: =item * $advtoolsref, optional argument, ref to an array containing 5125: inlineremote items to be added in "Functions" menu below 5126: breadcrumbs. 5127: 5128: =back 5129: 5130: Returns: A uniform header for LON-CAPA web pages. 5131: If $bodyonly is nonzero, a string containing a <body> tag will be returned. 5132: If $bodyonly is undef or zero, an html string containing a <body> tag and 5133: other decorations will be returned. 5134: 5135: =cut 5136: 5137: sub bodytag { 5138: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg, 5139: $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_; 5140: 5141: my $public; 5142: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')) 5143: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) { 5144: $public = 1; 5145: } 5146: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } 5147: my $httphost = $args->{'use_absolute'}; 5148: 5149: $function = &get_users_function() if (!$function); 5150: my $img = &designparm($function.'.img',$domain); 5151: my $font = &designparm($function.'.font',$domain); 5152: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain); 5153: 5154: my %design = ( 'style' => 'margin-top: 0', 5155: 'bgcolor' => $pgbg, 5156: 'text' => $font, 5157: 'alink' => &designparm($function.'.alink',$domain), 5158: 'vlink' => &designparm($function.'.vlink',$domain), 5159: 'link' => &designparm($function.'.link',$domain),); 5160: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 5161: 5162: # role and realm 5163: my ($role,$realm) = split(m{\./},$env{'request.role'},2); 5164: if ($realm) { 5165: $realm = '/'.$realm; 5166: } 5167: if ($role eq 'ca') { 5168: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$}); 5169: $realm = &plainname($rname,$rdom); 5170: } 5171: # realm 5172: if ($env{'request.course.id'}) { 5173: if ($env{'request.role'} !~ /^cr/) { 5174: $role = &Apache::lonnet::plaintext($role,&course_type()); 5175: } 5176: if ($env{'request.course.sec'}) { 5177: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'}; 5178: } 5179: $realm = $env{'course.'.$env{'request.course.id'}.'.description'}; 5180: } else { 5181: $role = &Apache::lonnet::plaintext($role); 5182: } 5183: 5184: if (!$realm) { $realm=' '; } 5185: 5186: my $extra_body_attr = &make_attr_string($forcereg,\%design); 5187: 5188: # construct main body tag 5189: my $bodytag = "<body $extra_body_attr>". 5190: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'}); 5191: 5192: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']); 5193: 5194: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) { 5195: return $bodytag; 5196: } 5197: 5198: if ($public) { 5199: undef($role); 5200: } 5201: 5202: my $titleinfo = '<h1>'.$title.'</h1>'; 5203: # 5204: # Extra info if you are the DC 5205: my $dc_info = ''; 5206: if ($env{'user.adv'} && exists($env{'user.role.dc./'. 5207: $env{'course.'.$env{'request.course.id'}. 5208: '.domain'}.'/'})) { 5209: my $cid = $env{'request.course.id'}; 5210: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'}; 5211: $dc_info =~ s/\s+$//; 5212: } 5213: 5214: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role; 5215: 5216: if ($env{'request.state'} eq 'construct') { $forcereg=1; } 5217: 5218: 5219: 5220: my $funclist; 5221: if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) { 5222: $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n". 5223: Apache::lonmenu::serverform(); 5224: my $forbodytag; 5225: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'}, 5226: $forcereg,$args->{'group'}, 5227: $args->{'bread_crumbs'}, 5228: $advtoolsref,'',\$forbodytag); 5229: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') { 5230: $funclist = $forbodytag; 5231: } 5232: } else { 5233: 5234: # if ($env{'request.state'} eq 'construct') { 5235: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls 5236: # } 5237: 5238: $bodytag .= Apache::lonhtmlcommon::scripttag( 5239: Apache::lonmenu::utilityfunctions($httphost), 'start'); 5240: 5241: my ($left,$right) = Apache::lonmenu::primary_menu(); 5242: 5243: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) { 5244: if ($dc_info) { 5245: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|; 5246: } 5247: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br /> 5248: <em>$realm</em> $dc_info</div>|; 5249: return $bodytag; 5250: } 5251: 5252: unless ($env{'request.symb'} =~ m/\.page___\d+___/) { 5253: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|; 5254: } 5255: 5256: $bodytag .= $right; 5257: 5258: if ($dc_info) { 5259: $dc_info = &dc_courseid_toggle($dc_info); 5260: } 5261: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|; 5262: 5263: #if directed to not display the secondary menu, don't. 5264: if ($args->{'no_secondary_menu'}) { 5265: return $bodytag; 5266: } 5267: #don't show menus for public users 5268: if (!$public){ 5269: $bodytag .= Apache::lonmenu::secondary_menu($httphost); 5270: $bodytag .= Apache::lonmenu::serverform(); 5271: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 5272: if ($env{'request.state'} eq 'construct') { 5273: $bodytag .= &Apache::lonmenu::innerregister($forcereg, 5274: $args->{'bread_crumbs'}); 5275: } elsif ($forcereg) { 5276: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef, 5277: $args->{'group'}); 5278: } else { 5279: my $forbodytag; 5280: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'}, 5281: $forcereg,$args->{'group'}, 5282: $args->{'bread_crumbs'}, 5283: $advtoolsref,'',\$forbodytag); 5284: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') { 5285: $bodytag .= $forbodytag; 5286: } 5287: } 5288: }else{ 5289: # this is to seperate menu from content when there's no secondary 5290: # menu. Especially needed for public accessible ressources. 5291: $bodytag .= '<hr style="clear:both" />'; 5292: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 5293: } 5294: 5295: return $bodytag; 5296: } 5297: 5298: # 5299: # Top frame rendering, Remote is up 5300: # 5301: 5302: my $imgsrc = $img; 5303: if ($img =~ /^\/adm/) { 5304: $imgsrc = &lonhttpdurl($img); 5305: } 5306: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />'; 5307: 5308: my $help=($no_inline_link?'' 5309: :&Apache::loncommon::top_nav_help('Help')); 5310: 5311: # Explicit link to get inline menu 5312: my $menu= ($no_inline_link?'' 5313: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>'); 5314: 5315: if ($dc_info) { 5316: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|; 5317: } 5318: 5319: my $name = &plainname($env{'user.name'},$env{'user.domain'}); 5320: unless ($public) { 5321: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'}, 5322: undef,'LC_menubuttons_link'); 5323: } 5324: 5325: unless ($env{'form.inhibitmenu'}) { 5326: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div> 5327: <ol class="LC_primary_menu LC_floatright LC_right"> 5328: <li>$help</li> 5329: <li>$menu</li> 5330: </ol><div id="LC_realm"> $realm $dc_info</div>|; 5331: } 5332: if ($env{'request.state'} eq 'construct') { 5333: if (!$public){ 5334: if ($env{'request.state'} eq 'construct') { 5335: $funclist = &Apache::lonhtmlcommon::scripttag( 5336: &Apache::lonmenu::utilityfunctions($httphost), 'start'). 5337: &Apache::lonhtmlcommon::scripttag('','end'). 5338: &Apache::lonmenu::innerregister($forcereg, 5339: $args->{'bread_crumbs'}); 5340: } 5341: } 5342: } 5343: return $bodytag."\n".$funclist; 5344: } 5345: 5346: sub dc_courseid_toggle { 5347: my ($dc_info) = @_; 5348: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'. 5349: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'. 5350: &mt('(More ...)').'</a></span>'. 5351: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>'; 5352: } 5353: 5354: sub make_attr_string { 5355: my ($register,$attr_ref) = @_; 5356: 5357: if ($attr_ref && !ref($attr_ref)) { 5358: die("addentries Must be a hash ref ". 5359: join(':',caller(1))." ". 5360: join(':',caller(0))." "); 5361: } 5362: 5363: if ($register) { 5364: my ($on_load,$on_unload); 5365: foreach my $key (keys(%{$attr_ref})) { 5366: if (lc($key) eq 'onload') { 5367: $on_load.=$attr_ref->{$key}.';'; 5368: delete($attr_ref->{$key}); 5369: 5370: } elsif (lc($key) eq 'onunload') { 5371: $on_unload.=$attr_ref->{$key}.';'; 5372: delete($attr_ref->{$key}); 5373: } 5374: } 5375: if ($env{'environment.remote'} eq 'on') { 5376: $attr_ref->{'onload'} = 5377: &Apache::lonmenu::loadevents(). $on_load; 5378: $attr_ref->{'onunload'}= 5379: &Apache::lonmenu::unloadevents().$on_unload; 5380: } else { 5381: $attr_ref->{'onload'} = $on_load; 5382: $attr_ref->{'onunload'}= $on_unload; 5383: } 5384: } 5385: 5386: my $attr_string; 5387: foreach my $attr (sort(keys(%$attr_ref))) { 5388: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" '; 5389: } 5390: return $attr_string; 5391: } 5392: 5393: 5394: ############################################### 5395: ############################################### 5396: 5397: =pod 5398: 5399: =item * &endbodytag() 5400: 5401: Returns a uniform footer for LON-CAPA web pages. 5402: 5403: Inputs: 1 - optional reference to an args hash 5404: If in the hash, key for noredirectlink has a value which evaluates to true, 5405: a 'Continue' link is not displayed if the page contains an 5406: internal redirect in the <head></head> section, 5407: i.e., $env{'internal.head.redirect'} exists 5408: 5409: =cut 5410: 5411: sub endbodytag { 5412: my ($args) = @_; 5413: my $endbodytag; 5414: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) { 5415: $endbodytag='</body>'; 5416: } 5417: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag; 5418: if ( exists( $env{'internal.head.redirect'} ) ) { 5419: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) { 5420: $endbodytag= 5421: "<br /><a href=\"$env{'internal.head.redirect'}\">". 5422: &mt('Continue').'</a>'. 5423: $endbodytag; 5424: } 5425: } 5426: return $endbodytag; 5427: } 5428: 5429: =pod 5430: 5431: =item * &standard_css() 5432: 5433: Returns a style sheet 5434: 5435: Inputs: (all optional) 5436: domain -> force to color decorate a page for a specific 5437: domain 5438: function -> force usage of a specific rolish color scheme 5439: bgcolor -> override the default page bgcolor 5440: 5441: =cut 5442: 5443: sub standard_css { 5444: my ($function,$domain,$bgcolor) = @_; 5445: $function = &get_users_function() if (!$function); 5446: my $img = &designparm($function.'.img', $domain); 5447: my $tabbg = &designparm($function.'.tabbg', $domain); 5448: my $font = &designparm($function.'.font', $domain); 5449: my $fontmenu = &designparm($function.'.fontmenu', $domain); 5450: #second colour for later usage 5451: my $sidebg = &designparm($function.'.sidebg',$domain); 5452: my $pgbg_or_bgcolor = 5453: $bgcolor || 5454: &designparm($function.'.pgbg', $domain); 5455: my $pgbg = &designparm($function.'.pgbg', $domain); 5456: my $alink = &designparm($function.'.alink', $domain); 5457: my $vlink = &designparm($function.'.vlink', $domain); 5458: my $link = &designparm($function.'.link', $domain); 5459: 5460: my $sans = 'Verdana,Arial,Helvetica,sans-serif'; 5461: my $mono = 'monospace'; 5462: my $data_table_head = $sidebg; 5463: my $data_table_light = '#FAFAFA'; 5464: my $data_table_dark = '#E0E0E0'; 5465: my $data_table_darker = '#CCCCCC'; 5466: my $data_table_highlight = '#FFFF00'; 5467: my $mail_new = '#FFBB77'; 5468: my $mail_new_hover = '#DD9955'; 5469: my $mail_read = '#BBBB77'; 5470: my $mail_read_hover = '#999944'; 5471: my $mail_replied = '#AAAA88'; 5472: my $mail_replied_hover = '#888855'; 5473: my $mail_other = '#99BBBB'; 5474: my $mail_other_hover = '#669999'; 5475: my $table_header = '#DDDDDD'; 5476: my $feedback_link_bg = '#BBBBBB'; 5477: my $lg_border_color = '#C8C8C8'; 5478: my $button_hover = '#BF2317'; 5479: 5480: my $border = ($env{'browser.type'} eq 'explorer' || 5481: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px' 5482: : '0 3px 0 4px'; 5483: 5484: 5485: return <<END; 5486: 5487: /* needed for iframe to allow 100% height in FF */ 5488: body, html { 5489: margin: 0; 5490: padding: 0 0.5%; 5491: height: 99%; /* to avoid scrollbars */ 5492: } 5493: 5494: body { 5495: font-family: $sans; 5496: line-height:130%; 5497: font-size:0.83em; 5498: color:$font; 5499: } 5500: 5501: a:focus, 5502: a:focus img { 5503: color: red; 5504: } 5505: 5506: form, .inline { 5507: display: inline; 5508: } 5509: 5510: .LC_right { 5511: text-align:right; 5512: } 5513: 5514: .LC_middle { 5515: vertical-align:middle; 5516: } 5517: 5518: .LC_floatleft { 5519: float: left; 5520: } 5521: 5522: .LC_floatright { 5523: float: right; 5524: } 5525: 5526: .LC_400Box { 5527: width:400px; 5528: } 5529: 5530: .LC_iframecontainer { 5531: width: 98%; 5532: margin: 0; 5533: position: fixed; 5534: top: 8.5em; 5535: bottom: 0; 5536: } 5537: 5538: .LC_iframecontainer iframe{ 5539: border: none; 5540: width: 100%; 5541: height: 100%; 5542: } 5543: 5544: .LC_filename { 5545: font-family: $mono; 5546: white-space:pre; 5547: font-size: 120%; 5548: } 5549: 5550: .LC_fileicon { 5551: border: none; 5552: height: 1.3em; 5553: vertical-align: text-bottom; 5554: margin-right: 0.3em; 5555: text-decoration:none; 5556: } 5557: 5558: .LC_setting { 5559: text-decoration:underline; 5560: } 5561: 5562: .LC_error { 5563: color: red; 5564: } 5565: 5566: .LC_warning { 5567: color: darkorange; 5568: } 5569: 5570: .LC_diff_removed { 5571: color: red; 5572: } 5573: 5574: .LC_info, 5575: .LC_success, 5576: .LC_diff_added { 5577: color: green; 5578: } 5579: 5580: div.LC_confirm_box { 5581: background-color: #FAFAFA; 5582: border: 1px solid $lg_border_color; 5583: margin-right: 0; 5584: padding: 5px; 5585: } 5586: 5587: div.LC_confirm_box .LC_error img, 5588: div.LC_confirm_box .LC_success img { 5589: vertical-align: middle; 5590: } 5591: 5592: .LC_icon { 5593: border: none; 5594: vertical-align: middle; 5595: } 5596: 5597: .LC_docs_spacer { 5598: width: 25px; 5599: height: 1px; 5600: border: none; 5601: } 5602: 5603: .LC_internal_info { 5604: color: #999999; 5605: } 5606: 5607: .LC_discussion { 5608: background: $data_table_dark; 5609: border: 1px solid black; 5610: margin: 2px; 5611: } 5612: 5613: .LC_disc_action_left { 5614: background: $sidebg; 5615: text-align: left; 5616: padding: 4px; 5617: margin: 2px; 5618: } 5619: 5620: .LC_disc_action_right { 5621: background: $sidebg; 5622: text-align: right; 5623: padding: 4px; 5624: margin: 2px; 5625: } 5626: 5627: .LC_disc_new_item { 5628: background: white; 5629: border: 2px solid red; 5630: margin: 4px; 5631: padding: 4px; 5632: } 5633: 5634: .LC_disc_old_item { 5635: background: white; 5636: margin: 4px; 5637: padding: 4px; 5638: } 5639: 5640: table.LC_pastsubmission { 5641: border: 1px solid black; 5642: margin: 2px; 5643: } 5644: 5645: table#LC_menubuttons { 5646: width: 100%; 5647: background: $pgbg; 5648: border: 2px; 5649: border-collapse: separate; 5650: padding: 0; 5651: } 5652: 5653: table#LC_title_bar a { 5654: color: $fontmenu; 5655: } 5656: 5657: table#LC_title_bar { 5658: clear: both; 5659: display: none; 5660: } 5661: 5662: table#LC_title_bar, 5663: table.LC_breadcrumbs, /* obsolete? */ 5664: table#LC_title_bar.LC_with_remote { 5665: width: 100%; 5666: border-color: $pgbg; 5667: border-style: solid; 5668: border-width: $border; 5669: background: $pgbg; 5670: color: $fontmenu; 5671: border-collapse: collapse; 5672: padding: 0; 5673: margin: 0; 5674: } 5675: 5676: ul.LC_breadcrumb_tools_outerlist { 5677: margin: 0; 5678: padding: 0; 5679: position: relative; 5680: list-style: none; 5681: } 5682: ul.LC_breadcrumb_tools_outerlist li { 5683: display: inline; 5684: } 5685: 5686: .LC_breadcrumb_tools_navigation { 5687: padding: 0; 5688: margin: 0; 5689: float: left; 5690: } 5691: .LC_breadcrumb_tools_tools { 5692: padding: 0; 5693: margin: 0; 5694: float: right; 5695: } 5696: 5697: table#LC_title_bar td { 5698: background: $tabbg; 5699: } 5700: 5701: table#LC_menubuttons img { 5702: border: none; 5703: } 5704: 5705: .LC_breadcrumbs_component { 5706: float: right; 5707: margin: 0 1em; 5708: } 5709: .LC_breadcrumbs_component img { 5710: vertical-align: middle; 5711: } 5712: 5713: td.LC_table_cell_checkbox { 5714: text-align: center; 5715: } 5716: 5717: .LC_fontsize_small { 5718: font-size: 70%; 5719: } 5720: 5721: #LC_breadcrumbs { 5722: clear:both; 5723: background: $sidebg; 5724: border-bottom: 1px solid $lg_border_color; 5725: line-height: 2.5em; 5726: overflow: hidden; 5727: margin: 0; 5728: padding: 0; 5729: text-align: left; 5730: } 5731: 5732: .LC_head_subbox, .LC_actionbox { 5733: clear:both; 5734: background: #F8F8F8; /* $sidebg; */ 5735: border: 1px solid $sidebg; 5736: margin: 0 0 10px 0; 5737: padding: 3px; 5738: text-align: left; 5739: } 5740: 5741: .LC_fontsize_medium { 5742: font-size: 85%; 5743: } 5744: 5745: .LC_fontsize_large { 5746: font-size: 120%; 5747: } 5748: 5749: .LC_menubuttons_inline_text { 5750: color: $font; 5751: font-size: 90%; 5752: padding-left:3px; 5753: } 5754: 5755: .LC_menubuttons_inline_text img{ 5756: vertical-align: middle; 5757: } 5758: 5759: li.LC_menubuttons_inline_text img { 5760: cursor:pointer; 5761: text-decoration: none; 5762: } 5763: 5764: .LC_menubuttons_link { 5765: text-decoration: none; 5766: } 5767: 5768: .LC_menubuttons_category { 5769: color: $font; 5770: background: $pgbg; 5771: font-size: larger; 5772: font-weight: bold; 5773: } 5774: 5775: td.LC_menubuttons_text { 5776: color: $font; 5777: } 5778: 5779: .LC_current_location { 5780: background: $tabbg; 5781: } 5782: 5783: table.LC_data_table { 5784: border: 1px solid #000000; 5785: border-collapse: separate; 5786: border-spacing: 1px; 5787: background: $pgbg; 5788: } 5789: 5790: .LC_data_table_dense { 5791: font-size: small; 5792: } 5793: 5794: table.LC_nested_outer { 5795: border: 1px solid #000000; 5796: border-collapse: collapse; 5797: border-spacing: 0; 5798: width: 100%; 5799: } 5800: 5801: table.LC_innerpickbox, 5802: table.LC_nested { 5803: border: none; 5804: border-collapse: collapse; 5805: border-spacing: 0; 5806: width: 100%; 5807: } 5808: 5809: table.LC_data_table tr th, 5810: table.LC_calendar tr th, 5811: table.LC_prior_tries tr th, 5812: table.LC_innerpickbox tr th { 5813: font-weight: bold; 5814: background-color: $data_table_head; 5815: color:$fontmenu; 5816: font-size:90%; 5817: } 5818: 5819: table.LC_innerpickbox tr th, 5820: table.LC_innerpickbox tr td { 5821: vertical-align: top; 5822: } 5823: 5824: table.LC_data_table tr.LC_info_row > td { 5825: background-color: #CCCCCC; 5826: font-weight: bold; 5827: text-align: left; 5828: } 5829: 5830: table.LC_data_table tr.LC_odd_row > td { 5831: background-color: $data_table_light; 5832: padding: 2px; 5833: vertical-align: top; 5834: } 5835: 5836: table.LC_pick_box tr > td.LC_odd_row { 5837: background-color: $data_table_light; 5838: vertical-align: top; 5839: } 5840: 5841: table.LC_data_table tr.LC_even_row > td { 5842: background-color: $data_table_dark; 5843: padding: 2px; 5844: vertical-align: top; 5845: } 5846: 5847: table.LC_pick_box tr > td.LC_even_row { 5848: background-color: $data_table_dark; 5849: vertical-align: top; 5850: } 5851: 5852: table.LC_data_table tr.LC_data_table_highlight td { 5853: background-color: $data_table_darker; 5854: } 5855: 5856: table.LC_data_table tr td.LC_leftcol_header { 5857: background-color: $data_table_head; 5858: font-weight: bold; 5859: } 5860: 5861: table.LC_data_table tr.LC_empty_row td, 5862: table.LC_nested tr.LC_empty_row td { 5863: font-weight: bold; 5864: font-style: italic; 5865: text-align: center; 5866: padding: 8px; 5867: } 5868: 5869: table.LC_data_table tr.LC_empty_row td, 5870: table.LC_data_table tr.LC_footer_row td { 5871: background-color: $sidebg; 5872: } 5873: 5874: table.LC_nested tr.LC_empty_row td { 5875: background-color: #FFFFFF; 5876: } 5877: 5878: table.LC_caption { 5879: } 5880: 5881: table.LC_nested tr.LC_empty_row td { 5882: padding: 4ex 5883: } 5884: 5885: table.LC_nested_outer tr th { 5886: font-weight: bold; 5887: color:$fontmenu; 5888: background-color: $data_table_head; 5889: font-size: small; 5890: border-bottom: 1px solid #000000; 5891: } 5892: 5893: table.LC_nested_outer tr td.LC_subheader { 5894: background-color: $data_table_head; 5895: font-weight: bold; 5896: font-size: small; 5897: border-bottom: 1px solid #000000; 5898: text-align: right; 5899: } 5900: 5901: table.LC_nested tr.LC_info_row td { 5902: background-color: #CCCCCC; 5903: font-weight: bold; 5904: font-size: small; 5905: text-align: center; 5906: } 5907: 5908: table.LC_nested tr.LC_info_row td.LC_left_item, 5909: table.LC_nested_outer tr th.LC_left_item { 5910: text-align: left; 5911: } 5912: 5913: table.LC_nested td { 5914: background-color: #FFFFFF; 5915: font-size: small; 5916: } 5917: 5918: table.LC_nested_outer tr th.LC_right_item, 5919: table.LC_nested tr.LC_info_row td.LC_right_item, 5920: table.LC_nested tr.LC_odd_row td.LC_right_item, 5921: table.LC_nested tr td.LC_right_item { 5922: text-align: right; 5923: } 5924: 5925: table.LC_nested tr.LC_odd_row td { 5926: background-color: #EEEEEE; 5927: } 5928: 5929: table.LC_createuser { 5930: } 5931: 5932: table.LC_createuser tr.LC_section_row td { 5933: font-size: small; 5934: } 5935: 5936: table.LC_createuser tr.LC_info_row td { 5937: background-color: #CCCCCC; 5938: font-weight: bold; 5939: text-align: center; 5940: } 5941: 5942: table.LC_calendar { 5943: border: 1px solid #000000; 5944: border-collapse: collapse; 5945: width: 98%; 5946: } 5947: 5948: table.LC_calendar_pickdate { 5949: font-size: xx-small; 5950: } 5951: 5952: table.LC_calendar tr td { 5953: border: 1px solid #000000; 5954: vertical-align: top; 5955: width: 14%; 5956: } 5957: 5958: table.LC_calendar tr td.LC_calendar_day_empty { 5959: background-color: $data_table_dark; 5960: } 5961: 5962: table.LC_calendar tr td.LC_calendar_day_current { 5963: background-color: $data_table_highlight; 5964: } 5965: 5966: table.LC_data_table tr td.LC_mail_new { 5967: background-color: $mail_new; 5968: } 5969: 5970: table.LC_data_table tr.LC_mail_new:hover { 5971: background-color: $mail_new_hover; 5972: } 5973: 5974: table.LC_data_table tr td.LC_mail_read { 5975: background-color: $mail_read; 5976: } 5977: 5978: /* 5979: table.LC_data_table tr.LC_mail_read:hover { 5980: background-color: $mail_read_hover; 5981: } 5982: */ 5983: 5984: table.LC_data_table tr td.LC_mail_replied { 5985: background-color: $mail_replied; 5986: } 5987: 5988: /* 5989: table.LC_data_table tr.LC_mail_replied:hover { 5990: background-color: $mail_replied_hover; 5991: } 5992: */ 5993: 5994: table.LC_data_table tr td.LC_mail_other { 5995: background-color: $mail_other; 5996: } 5997: 5998: /* 5999: table.LC_data_table tr.LC_mail_other:hover { 6000: background-color: $mail_other_hover; 6001: } 6002: */ 6003: 6004: table.LC_data_table tr > td.LC_browser_file, 6005: table.LC_data_table tr > td.LC_browser_file_published { 6006: background: #AAEE77; 6007: } 6008: 6009: table.LC_data_table tr > td.LC_browser_file_locked, 6010: table.LC_data_table tr > td.LC_browser_file_unpublished { 6011: background: #FFAA99; 6012: } 6013: 6014: table.LC_data_table tr > td.LC_browser_file_obsolete { 6015: background: #888888; 6016: } 6017: 6018: table.LC_data_table tr > td.LC_browser_file_modified, 6019: table.LC_data_table tr > td.LC_browser_file_metamodified { 6020: background: #F8F866; 6021: } 6022: 6023: table.LC_data_table tr.LC_browser_folder > td { 6024: background: #E0E8FF; 6025: } 6026: 6027: table.LC_data_table tr > td.LC_roles_is { 6028: /* background: #77FF77; */ 6029: } 6030: 6031: table.LC_data_table tr > td.LC_roles_future { 6032: border-right: 8px solid #FFFF77; 6033: } 6034: 6035: table.LC_data_table tr > td.LC_roles_will { 6036: border-right: 8px solid #FFAA77; 6037: } 6038: 6039: table.LC_data_table tr > td.LC_roles_expired { 6040: border-right: 8px solid #FF7777; 6041: } 6042: 6043: table.LC_data_table tr > td.LC_roles_will_not { 6044: border-right: 8px solid #AAFF77; 6045: } 6046: 6047: table.LC_data_table tr > td.LC_roles_selected { 6048: border-right: 8px solid #11CC55; 6049: } 6050: 6051: span.LC_current_location { 6052: font-size:larger; 6053: background: $pgbg; 6054: } 6055: 6056: span.LC_current_nav_location { 6057: font-weight:bold; 6058: background: $sidebg; 6059: } 6060: 6061: span.LC_parm_menu_item { 6062: font-size: larger; 6063: } 6064: 6065: span.LC_parm_scope_all { 6066: color: red; 6067: } 6068: 6069: span.LC_parm_scope_folder { 6070: color: green; 6071: } 6072: 6073: span.LC_parm_scope_resource { 6074: color: orange; 6075: } 6076: 6077: span.LC_parm_part { 6078: color: blue; 6079: } 6080: 6081: span.LC_parm_folder, 6082: span.LC_parm_symb { 6083: font-size: x-small; 6084: font-family: $mono; 6085: color: #AAAAAA; 6086: } 6087: 6088: ul.LC_parm_parmlist li { 6089: display: inline-block; 6090: padding: 0.3em 0.8em; 6091: vertical-align: top; 6092: width: 150px; 6093: border-top:1px solid $lg_border_color; 6094: } 6095: 6096: td.LC_parm_overview_level_menu, 6097: td.LC_parm_overview_map_menu, 6098: td.LC_parm_overview_parm_selectors, 6099: td.LC_parm_overview_restrictions { 6100: border: 1px solid black; 6101: border-collapse: collapse; 6102: } 6103: 6104: table.LC_parm_overview_restrictions td { 6105: border-width: 1px 4px 1px 4px; 6106: border-style: solid; 6107: border-color: $pgbg; 6108: text-align: center; 6109: } 6110: 6111: table.LC_parm_overview_restrictions th { 6112: background: $tabbg; 6113: border-width: 1px 4px 1px 4px; 6114: border-style: solid; 6115: border-color: $pgbg; 6116: } 6117: 6118: table#LC_helpmenu { 6119: border: none; 6120: height: 55px; 6121: border-spacing: 0; 6122: } 6123: 6124: table#LC_helpmenu fieldset legend { 6125: font-size: larger; 6126: } 6127: 6128: table#LC_helpmenu_links { 6129: width: 100%; 6130: border: 1px solid black; 6131: background: $pgbg; 6132: padding: 0; 6133: border-spacing: 1px; 6134: } 6135: 6136: table#LC_helpmenu_links tr td { 6137: padding: 1px; 6138: background: $tabbg; 6139: text-align: center; 6140: font-weight: bold; 6141: } 6142: 6143: table#LC_helpmenu_links a:link, 6144: table#LC_helpmenu_links a:visited, 6145: table#LC_helpmenu_links a:active { 6146: text-decoration: none; 6147: color: $font; 6148: } 6149: 6150: table#LC_helpmenu_links a:hover { 6151: text-decoration: underline; 6152: color: $vlink; 6153: } 6154: 6155: .LC_chrt_popup_exists { 6156: border: 1px solid #339933; 6157: margin: -1px; 6158: } 6159: 6160: .LC_chrt_popup_up { 6161: border: 1px solid yellow; 6162: margin: -1px; 6163: } 6164: 6165: .LC_chrt_popup { 6166: border: 1px solid #8888FF; 6167: background: #CCCCFF; 6168: } 6169: 6170: table.LC_pick_box { 6171: border-collapse: separate; 6172: background: white; 6173: border: 1px solid black; 6174: border-spacing: 1px; 6175: } 6176: 6177: table.LC_pick_box td.LC_pick_box_title { 6178: background: $sidebg; 6179: font-weight: bold; 6180: text-align: left; 6181: vertical-align: top; 6182: width: 184px; 6183: padding: 8px; 6184: } 6185: 6186: table.LC_pick_box td.LC_pick_box_value { 6187: text-align: left; 6188: padding: 8px; 6189: } 6190: 6191: table.LC_pick_box td.LC_pick_box_select { 6192: text-align: left; 6193: padding: 8px; 6194: } 6195: 6196: table.LC_pick_box td.LC_pick_box_separator { 6197: padding: 0; 6198: height: 1px; 6199: background: black; 6200: } 6201: 6202: table.LC_pick_box td.LC_pick_box_submit { 6203: text-align: right; 6204: } 6205: 6206: table.LC_pick_box td.LC_evenrow_value { 6207: text-align: left; 6208: padding: 8px; 6209: background-color: $data_table_light; 6210: } 6211: 6212: table.LC_pick_box td.LC_oddrow_value { 6213: text-align: left; 6214: padding: 8px; 6215: background-color: $data_table_light; 6216: } 6217: 6218: span.LC_helpform_receipt_cat { 6219: font-weight: bold; 6220: } 6221: 6222: table.LC_group_priv_box { 6223: background: white; 6224: border: 1px solid black; 6225: border-spacing: 1px; 6226: } 6227: 6228: table.LC_group_priv_box td.LC_pick_box_title { 6229: background: $tabbg; 6230: font-weight: bold; 6231: text-align: right; 6232: width: 184px; 6233: } 6234: 6235: table.LC_group_priv_box td.LC_groups_fixed { 6236: background: $data_table_light; 6237: text-align: center; 6238: } 6239: 6240: table.LC_group_priv_box td.LC_groups_optional { 6241: background: $data_table_dark; 6242: text-align: center; 6243: } 6244: 6245: table.LC_group_priv_box td.LC_groups_functionality { 6246: background: $data_table_darker; 6247: text-align: center; 6248: font-weight: bold; 6249: } 6250: 6251: table.LC_group_priv td { 6252: text-align: left; 6253: padding: 0; 6254: } 6255: 6256: .LC_navbuttons { 6257: margin: 2ex 0ex 2ex 0ex; 6258: } 6259: 6260: .LC_topic_bar { 6261: font-weight: bold; 6262: background: $tabbg; 6263: margin: 1em 0em 1em 2em; 6264: padding: 3px; 6265: font-size: 1.2em; 6266: } 6267: 6268: .LC_topic_bar span { 6269: left: 0.5em; 6270: position: absolute; 6271: vertical-align: middle; 6272: font-size: 1.2em; 6273: } 6274: 6275: table.LC_course_group_status { 6276: margin: 20px; 6277: } 6278: 6279: table.LC_status_selector td { 6280: vertical-align: top; 6281: text-align: center; 6282: padding: 4px; 6283: } 6284: 6285: div.LC_feedback_link { 6286: clear: both; 6287: background: $sidebg; 6288: width: 100%; 6289: padding-bottom: 10px; 6290: border: 1px $tabbg solid; 6291: height: 22px; 6292: line-height: 22px; 6293: padding-top: 5px; 6294: } 6295: 6296: div.LC_feedback_link img { 6297: height: 22px; 6298: vertical-align:middle; 6299: } 6300: 6301: div.LC_feedback_link a { 6302: text-decoration: none; 6303: } 6304: 6305: div.LC_comblock { 6306: display:inline; 6307: color:$font; 6308: font-size:90%; 6309: } 6310: 6311: div.LC_feedback_link div.LC_comblock { 6312: padding-left:5px; 6313: } 6314: 6315: div.LC_feedback_link div.LC_comblock a { 6316: color:$font; 6317: } 6318: 6319: span.LC_feedback_link { 6320: /* background: $feedback_link_bg; */ 6321: font-size: larger; 6322: } 6323: 6324: span.LC_message_link { 6325: /* background: $feedback_link_bg; */ 6326: font-size: larger; 6327: position: absolute; 6328: right: 1em; 6329: } 6330: 6331: table.LC_prior_tries { 6332: border: 1px solid #000000; 6333: border-collapse: separate; 6334: border-spacing: 1px; 6335: } 6336: 6337: table.LC_prior_tries td { 6338: padding: 2px; 6339: } 6340: 6341: .LC_answer_correct { 6342: background: lightgreen; 6343: color: darkgreen; 6344: padding: 6px; 6345: } 6346: 6347: .LC_answer_charged_try { 6348: background: #FFAAAA; 6349: color: darkred; 6350: padding: 6px; 6351: } 6352: 6353: .LC_answer_not_charged_try, 6354: .LC_answer_no_grade, 6355: .LC_answer_late { 6356: background: lightyellow; 6357: color: black; 6358: padding: 6px; 6359: } 6360: 6361: .LC_answer_previous { 6362: background: lightblue; 6363: color: darkblue; 6364: padding: 6px; 6365: } 6366: 6367: .LC_answer_no_message { 6368: background: #FFFFFF; 6369: color: black; 6370: padding: 6px; 6371: } 6372: 6373: .LC_answer_unknown { 6374: background: orange; 6375: color: black; 6376: padding: 6px; 6377: } 6378: 6379: span.LC_prior_numerical, 6380: span.LC_prior_string, 6381: span.LC_prior_custom, 6382: span.LC_prior_reaction, 6383: span.LC_prior_math { 6384: font-family: $mono; 6385: white-space: pre; 6386: } 6387: 6388: span.LC_prior_string { 6389: font-family: $mono; 6390: white-space: pre; 6391: } 6392: 6393: table.LC_prior_option { 6394: width: 100%; 6395: border-collapse: collapse; 6396: } 6397: 6398: table.LC_prior_rank, 6399: table.LC_prior_match { 6400: border-collapse: collapse; 6401: } 6402: 6403: table.LC_prior_option tr td, 6404: table.LC_prior_rank tr td, 6405: table.LC_prior_match tr td { 6406: border: 1px solid #000000; 6407: } 6408: 6409: .LC_nobreak { 6410: white-space: nowrap; 6411: } 6412: 6413: span.LC_cusr_emph { 6414: font-style: italic; 6415: } 6416: 6417: span.LC_cusr_subheading { 6418: font-weight: normal; 6419: font-size: 85%; 6420: } 6421: 6422: div.LC_docs_entry_move { 6423: border: 1px solid #BBBBBB; 6424: background: #DDDDDD; 6425: width: 22px; 6426: padding: 1px; 6427: margin: 0; 6428: } 6429: 6430: table.LC_data_table tr > td.LC_docs_entry_commands, 6431: table.LC_data_table tr > td.LC_docs_entry_parameter { 6432: font-size: x-small; 6433: } 6434: 6435: .LC_docs_entry_parameter { 6436: white-space: nowrap; 6437: } 6438: 6439: .LC_docs_copy { 6440: color: #000099; 6441: } 6442: 6443: .LC_docs_cut { 6444: color: #550044; 6445: } 6446: 6447: .LC_docs_rename { 6448: color: #009900; 6449: } 6450: 6451: .LC_docs_remove { 6452: color: #990000; 6453: } 6454: 6455: .LC_docs_reinit_warn, 6456: .LC_docs_ext_edit { 6457: font-size: x-small; 6458: } 6459: 6460: table.LC_docs_adddocs td, 6461: table.LC_docs_adddocs th { 6462: border: 1px solid #BBBBBB; 6463: padding: 4px; 6464: background: #DDDDDD; 6465: } 6466: 6467: table.LC_sty_begin { 6468: background: #BBFFBB; 6469: } 6470: 6471: table.LC_sty_end { 6472: background: #FFBBBB; 6473: } 6474: 6475: table.LC_double_column { 6476: border-width: 0; 6477: border-collapse: collapse; 6478: width: 100%; 6479: padding: 2px; 6480: } 6481: 6482: table.LC_double_column tr td.LC_left_col { 6483: top: 2px; 6484: left: 2px; 6485: width: 47%; 6486: vertical-align: top; 6487: } 6488: 6489: table.LC_double_column tr td.LC_right_col { 6490: top: 2px; 6491: right: 2px; 6492: width: 47%; 6493: vertical-align: top; 6494: } 6495: 6496: div.LC_left_float { 6497: float: left; 6498: padding-right: 5%; 6499: padding-bottom: 4px; 6500: } 6501: 6502: div.LC_clear_float_header { 6503: padding-bottom: 2px; 6504: } 6505: 6506: div.LC_clear_float_footer { 6507: padding-top: 10px; 6508: clear: both; 6509: } 6510: 6511: div.LC_grade_show_user { 6512: /* border-left: 5px solid $sidebg; */ 6513: border-top: 5px solid #000000; 6514: margin: 50px 0 0 0; 6515: padding: 15px 0 5px 10px; 6516: } 6517: 6518: div.LC_grade_show_user_odd_row { 6519: /* border-left: 5px solid #000000; */ 6520: } 6521: 6522: div.LC_grade_show_user div.LC_Box { 6523: margin-right: 50px; 6524: } 6525: 6526: div.LC_grade_submissions, 6527: div.LC_grade_message_center, 6528: div.LC_grade_info_links { 6529: margin: 5px; 6530: width: 99%; 6531: background: #FFFFFF; 6532: } 6533: 6534: div.LC_grade_submissions_header, 6535: div.LC_grade_message_center_header { 6536: font-weight: bold; 6537: font-size: large; 6538: } 6539: 6540: div.LC_grade_submissions_body, 6541: div.LC_grade_message_center_body { 6542: border: 1px solid black; 6543: width: 99%; 6544: background: #FFFFFF; 6545: } 6546: 6547: table.LC_scantron_action { 6548: width: 100%; 6549: } 6550: 6551: table.LC_scantron_action tr th { 6552: font-weight:bold; 6553: font-style:normal; 6554: } 6555: 6556: .LC_edit_problem_header, 6557: div.LC_edit_problem_footer { 6558: font-weight: normal; 6559: font-size: medium; 6560: margin: 2px; 6561: background-color: $sidebg; 6562: } 6563: 6564: div.LC_edit_problem_header, 6565: div.LC_edit_problem_header div, 6566: div.LC_edit_problem_footer, 6567: div.LC_edit_problem_footer div, 6568: div.LC_edit_problem_editxml_header, 6569: div.LC_edit_problem_editxml_header div { 6570: margin-top: 5px; 6571: } 6572: 6573: div.LC_edit_problem_header_title { 6574: font-weight: bold; 6575: font-size: larger; 6576: background: $tabbg; 6577: padding: 3px; 6578: margin: 0 0 5px 0; 6579: } 6580: 6581: table.LC_edit_problem_header_title { 6582: width: 100%; 6583: background: $tabbg; 6584: } 6585: 6586: div.LC_edit_problem_discards { 6587: float: left; 6588: padding-bottom: 5px; 6589: } 6590: 6591: div.LC_edit_problem_saves { 6592: float: right; 6593: padding-bottom: 5px; 6594: } 6595: 6596: .LC_edit_opt { 6597: padding-left: 1em; 6598: white-space: nowrap; 6599: } 6600: 6601: .LC_edit_problem_latexhelper{ 6602: text-align: right; 6603: } 6604: 6605: #LC_edit_problem_colorful div{ 6606: margin-left: 40px; 6607: } 6608: 6609: img.stift { 6610: border-width: 0; 6611: vertical-align: middle; 6612: } 6613: 6614: table td.LC_mainmenu_col_fieldset { 6615: vertical-align: top; 6616: } 6617: 6618: div.LC_createcourse { 6619: margin: 10px 10px 10px 10px; 6620: } 6621: 6622: .LC_dccid { 6623: float: right; 6624: margin: 0.2em 0 0 0; 6625: padding: 0; 6626: font-size: 90%; 6627: display:none; 6628: } 6629: 6630: ol.LC_primary_menu a:hover, 6631: ol#LC_MenuBreadcrumbs a:hover, 6632: ol#LC_PathBreadcrumbs a:hover, 6633: ul#LC_secondary_menu a:hover, 6634: .LC_FormSectionClearButton input:hover 6635: ul.LC_TabContent li:hover a { 6636: color:$button_hover; 6637: text-decoration:none; 6638: } 6639: 6640: h1 { 6641: padding: 0; 6642: line-height:130%; 6643: } 6644: 6645: h2, 6646: h3, 6647: h4, 6648: h5, 6649: h6 { 6650: margin: 5px 0 5px 0; 6651: padding: 0; 6652: line-height:130%; 6653: } 6654: 6655: .LC_hcell { 6656: padding:3px 15px 3px 15px; 6657: margin: 0; 6658: background-color:$tabbg; 6659: color:$fontmenu; 6660: border-bottom:solid 1px $lg_border_color; 6661: } 6662: 6663: .LC_Box > .LC_hcell { 6664: margin: 0 -10px 10px -10px; 6665: } 6666: 6667: .LC_noBorder { 6668: border: 0; 6669: } 6670: 6671: .LC_FormSectionClearButton input { 6672: background-color:transparent; 6673: border: none; 6674: cursor:pointer; 6675: text-decoration:underline; 6676: } 6677: 6678: .LC_help_open_topic { 6679: color: #FFFFFF; 6680: background-color: #EEEEFF; 6681: margin: 1px; 6682: padding: 4px; 6683: border: 1px solid #000033; 6684: white-space: nowrap; 6685: /* vertical-align: middle; */ 6686: } 6687: 6688: dl, 6689: ul, 6690: div, 6691: fieldset { 6692: margin: 10px 10px 10px 0; 6693: /* overflow: hidden; */ 6694: } 6695: 6696: article.geogebraweb div { 6697: margin: 0; 6698: } 6699: 6700: fieldset > legend { 6701: font-weight: bold; 6702: padding: 0 5px 0 5px; 6703: } 6704: 6705: #LC_nav_bar { 6706: float: left; 6707: background-color: $pgbg_or_bgcolor; 6708: margin: 0 0 2px 0; 6709: } 6710: 6711: #LC_realm { 6712: margin: 0.2em 0 0 0; 6713: padding: 0; 6714: font-weight: bold; 6715: text-align: center; 6716: background-color: $pgbg_or_bgcolor; 6717: } 6718: 6719: #LC_nav_bar em { 6720: font-weight: bold; 6721: font-style: normal; 6722: } 6723: 6724: ol.LC_primary_menu { 6725: margin: 0; 6726: padding: 0; 6727: background-color: $pgbg_or_bgcolor; 6728: } 6729: 6730: ol#LC_PathBreadcrumbs { 6731: margin: 0; 6732: } 6733: 6734: ol.LC_primary_menu li { 6735: color: RGB(80, 80, 80); 6736: vertical-align: middle; 6737: text-align: left; 6738: list-style: none; 6739: float: left; 6740: } 6741: 6742: ol.LC_primary_menu li a { 6743: display: block; 6744: margin: 0; 6745: padding: 0 5px 0 10px; 6746: text-decoration: none; 6747: } 6748: 6749: ol.LC_primary_menu li ul { 6750: display: none; 6751: width: 10em; 6752: background-color: $data_table_light; 6753: } 6754: 6755: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul { 6756: display: block; 6757: position: absolute; 6758: margin: 0; 6759: padding: 0; 6760: z-index: 2; 6761: } 6762: 6763: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li { 6764: font-size: 90%; 6765: vertical-align: top; 6766: float: none; 6767: border-left: 1px solid black; 6768: border-right: 1px solid black; 6769: } 6770: 6771: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a { 6772: background-color:$data_table_light; 6773: } 6774: 6775: ol.LC_primary_menu li li a:hover { 6776: color:$button_hover; 6777: background-color:$data_table_dark; 6778: } 6779: 6780: ol.LC_primary_menu li img { 6781: vertical-align: bottom; 6782: height: 1.1em; 6783: margin: 0.2em 0 0 0; 6784: } 6785: 6786: ol.LC_primary_menu a { 6787: color: RGB(80, 80, 80); 6788: text-decoration: none; 6789: } 6790: 6791: ol.LC_primary_menu a.LC_new_message { 6792: font-weight:bold; 6793: color: darkred; 6794: } 6795: 6796: ol.LC_docs_parameters { 6797: margin-left: 0; 6798: padding: 0; 6799: list-style: none; 6800: } 6801: 6802: ol.LC_docs_parameters li { 6803: margin: 0; 6804: padding-right: 20px; 6805: display: inline; 6806: } 6807: 6808: ol.LC_docs_parameters li:before { 6809: content: "\\002022 \\0020"; 6810: } 6811: 6812: li.LC_docs_parameters_title { 6813: font-weight: bold; 6814: } 6815: 6816: ol.LC_docs_parameters li.LC_docs_parameters_title:before { 6817: content: ""; 6818: } 6819: 6820: ul#LC_secondary_menu { 6821: clear: right; 6822: color: $fontmenu; 6823: background: $tabbg; 6824: list-style: none; 6825: padding: 0; 6826: margin: 0; 6827: width: 100%; 6828: text-align: left; 6829: float: left; 6830: } 6831: 6832: ul#LC_secondary_menu li { 6833: font-weight: bold; 6834: line-height: 1.8em; 6835: border-right: 1px solid black; 6836: vertical-align: middle; 6837: float: left; 6838: } 6839: 6840: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover { 6841: background-color: $data_table_light; 6842: } 6843: 6844: ul#LC_secondary_menu li a { 6845: padding: 0 0.8em; 6846: } 6847: 6848: ul#LC_secondary_menu li ul { 6849: display: none; 6850: } 6851: 6852: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul { 6853: display: block; 6854: position: absolute; 6855: margin: 0; 6856: padding: 0; 6857: list-style:none; 6858: float: none; 6859: background-color: $data_table_light; 6860: z-index: 2; 6861: margin-left: -1px; 6862: } 6863: 6864: ul#LC_secondary_menu li ul li { 6865: font-size: 90%; 6866: vertical-align: top; 6867: border-left: 1px solid black; 6868: border-right: 1px solid black; 6869: background-color: $data_table_light; 6870: list-style:none; 6871: float: none; 6872: } 6873: 6874: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover { 6875: background-color: $data_table_dark; 6876: } 6877: 6878: ul.LC_TabContent { 6879: display:block; 6880: background: $sidebg; 6881: border-bottom: solid 1px $lg_border_color; 6882: list-style:none; 6883: margin: -1px -10px 0 -10px; 6884: padding: 0; 6885: } 6886: 6887: ul.LC_TabContent li, 6888: ul.LC_TabContentBigger li { 6889: float:left; 6890: } 6891: 6892: ul#LC_secondary_menu li a { 6893: color: $fontmenu; 6894: text-decoration: none; 6895: } 6896: 6897: ul.LC_TabContent { 6898: min-height:20px; 6899: } 6900: 6901: ul.LC_TabContent li { 6902: vertical-align:middle; 6903: padding: 0 16px 0 10px; 6904: background-color:$tabbg; 6905: border-bottom:solid 1px $lg_border_color; 6906: border-left: solid 1px $font; 6907: } 6908: 6909: ul.LC_TabContent .right { 6910: float:right; 6911: } 6912: 6913: ul.LC_TabContent li a, 6914: ul.LC_TabContent li { 6915: color:rgb(47,47,47); 6916: text-decoration:none; 6917: font-size:95%; 6918: font-weight:bold; 6919: min-height:20px; 6920: } 6921: 6922: ul.LC_TabContent li a:hover, 6923: ul.LC_TabContent li a:focus { 6924: color: $button_hover; 6925: background:none; 6926: outline:none; 6927: } 6928: 6929: ul.LC_TabContent li:hover { 6930: color: $button_hover; 6931: cursor:pointer; 6932: } 6933: 6934: ul.LC_TabContent li.active { 6935: color: $font; 6936: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center; 6937: border-bottom:solid 1px #FFFFFF; 6938: cursor: default; 6939: } 6940: 6941: ul.LC_TabContent li.active a { 6942: color:$font; 6943: background:#FFFFFF; 6944: outline: none; 6945: } 6946: 6947: ul.LC_TabContent li.goback { 6948: float: left; 6949: border-left: none; 6950: } 6951: 6952: #maincoursedoc { 6953: clear:both; 6954: } 6955: 6956: ul.LC_TabContentBigger { 6957: display:block; 6958: list-style:none; 6959: padding: 0; 6960: } 6961: 6962: ul.LC_TabContentBigger li { 6963: vertical-align:bottom; 6964: height: 30px; 6965: font-size:110%; 6966: font-weight:bold; 6967: color: #737373; 6968: } 6969: 6970: ul.LC_TabContentBigger li.active { 6971: position: relative; 6972: top: 1px; 6973: } 6974: 6975: ul.LC_TabContentBigger li a { 6976: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat; 6977: height: 30px; 6978: line-height: 30px; 6979: text-align: center; 6980: display: block; 6981: text-decoration: none; 6982: outline: none; 6983: } 6984: 6985: ul.LC_TabContentBigger li.active a { 6986: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat; 6987: color:$font; 6988: } 6989: 6990: ul.LC_TabContentBigger li b { 6991: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom; 6992: display: block; 6993: float: left; 6994: padding: 0 30px; 6995: border-bottom: 1px solid $lg_border_color; 6996: } 6997: 6998: ul.LC_TabContentBigger li:hover b { 6999: color:$button_hover; 7000: } 7001: 7002: ul.LC_TabContentBigger li.active b { 7003: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat; 7004: color:$font; 7005: border: 0; 7006: } 7007: 7008: 7009: ul.LC_CourseBreadcrumbs { 7010: background: $sidebg; 7011: height: 2em; 7012: padding-left: 10px; 7013: margin: 0; 7014: list-style-position: inside; 7015: } 7016: 7017: ol#LC_MenuBreadcrumbs, 7018: ol#LC_PathBreadcrumbs { 7019: padding-left: 10px; 7020: margin: 0; 7021: height: 2.5em; /* equal to #LC_breadcrumbs line-height */ 7022: } 7023: 7024: ol#LC_MenuBreadcrumbs li, 7025: ol#LC_PathBreadcrumbs li, 7026: ul.LC_CourseBreadcrumbs li { 7027: display: inline; 7028: white-space: normal; 7029: } 7030: 7031: ol#LC_MenuBreadcrumbs li a, 7032: ul.LC_CourseBreadcrumbs li a { 7033: text-decoration: none; 7034: font-size:90%; 7035: } 7036: 7037: ol#LC_MenuBreadcrumbs h1 { 7038: display: inline; 7039: font-size: 90%; 7040: line-height: 2.5em; 7041: margin: 0; 7042: padding: 0; 7043: } 7044: 7045: ol#LC_PathBreadcrumbs li a { 7046: text-decoration:none; 7047: font-size:100%; 7048: font-weight:bold; 7049: } 7050: 7051: .LC_Box { 7052: border: solid 1px $lg_border_color; 7053: padding: 0 10px 10px 10px; 7054: } 7055: 7056: .LC_DocsBox { 7057: border: solid 1px $lg_border_color; 7058: padding: 0 0 10px 10px; 7059: } 7060: 7061: .LC_AboutMe_Image { 7062: float:left; 7063: margin-right:10px; 7064: } 7065: 7066: .LC_Clear_AboutMe_Image { 7067: clear:left; 7068: } 7069: 7070: dl.LC_ListStyleClean dt { 7071: padding-right: 5px; 7072: display: table-header-group; 7073: } 7074: 7075: dl.LC_ListStyleClean dd { 7076: display: table-row; 7077: } 7078: 7079: .LC_ListStyleClean, 7080: .LC_ListStyleSimple, 7081: .LC_ListStyleNormal, 7082: .LC_ListStyleSpecial { 7083: /* display:block; */ 7084: list-style-position: inside; 7085: list-style-type: none; 7086: overflow: hidden; 7087: padding: 0; 7088: } 7089: 7090: .LC_ListStyleSimple li, 7091: .LC_ListStyleSimple dd, 7092: .LC_ListStyleNormal li, 7093: .LC_ListStyleNormal dd, 7094: .LC_ListStyleSpecial li, 7095: .LC_ListStyleSpecial dd { 7096: margin: 0; 7097: padding: 5px 5px 5px 10px; 7098: clear: both; 7099: } 7100: 7101: .LC_ListStyleClean li, 7102: .LC_ListStyleClean dd { 7103: padding-top: 0; 7104: padding-bottom: 0; 7105: } 7106: 7107: .LC_ListStyleSimple dd, 7108: .LC_ListStyleSimple li { 7109: border-bottom: solid 1px $lg_border_color; 7110: } 7111: 7112: .LC_ListStyleSpecial li, 7113: .LC_ListStyleSpecial dd { 7114: list-style-type: none; 7115: background-color: RGB(220, 220, 220); 7116: margin-bottom: 4px; 7117: } 7118: 7119: table.LC_SimpleTable { 7120: margin:5px; 7121: border:solid 1px $lg_border_color; 7122: } 7123: 7124: table.LC_SimpleTable tr { 7125: padding: 0; 7126: border:solid 1px $lg_border_color; 7127: } 7128: 7129: table.LC_SimpleTable thead { 7130: background:rgb(220,220,220); 7131: } 7132: 7133: div.LC_columnSection { 7134: display: block; 7135: clear: both; 7136: overflow: hidden; 7137: margin: 0; 7138: } 7139: 7140: div.LC_columnSection>* { 7141: float: left; 7142: margin: 10px 20px 10px 0; 7143: overflow:hidden; 7144: } 7145: 7146: table em { 7147: font-weight: bold; 7148: font-style: normal; 7149: } 7150: 7151: table.LC_tableBrowseRes, 7152: table.LC_tableOfContent { 7153: border:none; 7154: border-spacing: 1px; 7155: padding: 3px; 7156: background-color: #FFFFFF; 7157: font-size: 90%; 7158: } 7159: 7160: table.LC_tableOfContent { 7161: border-collapse: collapse; 7162: } 7163: 7164: table.LC_tableBrowseRes a, 7165: table.LC_tableOfContent a { 7166: background-color: transparent; 7167: text-decoration: none; 7168: } 7169: 7170: table.LC_tableOfContent img { 7171: border: none; 7172: height: 1.3em; 7173: vertical-align: text-bottom; 7174: margin-right: 0.3em; 7175: } 7176: 7177: a#LC_content_toolbar_firsthomework { 7178: background-image:url(/res/adm/pages/open-first-problem.gif); 7179: } 7180: 7181: a#LC_content_toolbar_everything { 7182: background-image:url(/res/adm/pages/show-all.gif); 7183: } 7184: 7185: a#LC_content_toolbar_uncompleted { 7186: background-image:url(/res/adm/pages/show-incomplete-problems.gif); 7187: } 7188: 7189: #LC_content_toolbar_clearbubbles { 7190: background-image:url(/res/adm/pages/mark-discussionentries-read.gif); 7191: } 7192: 7193: a#LC_content_toolbar_changefolder { 7194: background : url(/res/adm/pages/close-all-folders.gif) top center ; 7195: } 7196: 7197: a#LC_content_toolbar_changefolder_toggled { 7198: background-image:url(/res/adm/pages/open-all-folders.gif); 7199: } 7200: 7201: a#LC_content_toolbar_edittoplevel { 7202: background-image:url(/res/adm/pages/edittoplevel.gif); 7203: } 7204: 7205: ul#LC_toolbar li a:hover { 7206: background-position: bottom center; 7207: } 7208: 7209: ul#LC_toolbar { 7210: padding: 0; 7211: margin: 2px; 7212: list-style:none; 7213: position:relative; 7214: background-color:white; 7215: overflow: auto; 7216: } 7217: 7218: ul#LC_toolbar li { 7219: border:1px solid white; 7220: padding: 0; 7221: margin: 0; 7222: float: left; 7223: display:inline; 7224: vertical-align:middle; 7225: white-space: nowrap; 7226: } 7227: 7228: 7229: a.LC_toolbarItem { 7230: display:block; 7231: padding: 0; 7232: margin: 0; 7233: height: 32px; 7234: width: 32px; 7235: color:white; 7236: border: none; 7237: background-repeat:no-repeat; 7238: background-color:transparent; 7239: } 7240: 7241: ul.LC_funclist { 7242: margin: 0; 7243: padding: 0.5em 1em 0.5em 0; 7244: } 7245: 7246: ul.LC_funclist > li:first-child { 7247: font-weight:bold; 7248: margin-left:0.8em; 7249: } 7250: 7251: ul.LC_funclist + ul.LC_funclist { 7252: /* 7253: left border as a seperator if we have more than 7254: one list 7255: */ 7256: border-left: 1px solid $sidebg; 7257: /* 7258: this hides the left border behind the border of the 7259: outer box if element is wrapped to the next 'line' 7260: */ 7261: margin-left: -1px; 7262: } 7263: 7264: ul.LC_funclist li { 7265: display: inline; 7266: white-space: nowrap; 7267: margin: 0 0 0 25px; 7268: line-height: 150%; 7269: } 7270: 7271: .LC_hidden { 7272: display: none; 7273: } 7274: 7275: .LCmodal-overlay { 7276: position:fixed; 7277: top:0; 7278: right:0; 7279: bottom:0; 7280: left:0; 7281: height:100%; 7282: width:100%; 7283: margin:0; 7284: padding:0; 7285: background:#999; 7286: opacity:.75; 7287: filter: alpha(opacity=75); 7288: -moz-opacity: 0.75; 7289: z-index:101; 7290: } 7291: 7292: * html .LCmodal-overlay { 7293: position: absolute; 7294: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); 7295: } 7296: 7297: .LCmodal-window { 7298: position:fixed; 7299: top:50%; 7300: left:50%; 7301: margin:0; 7302: padding:0; 7303: z-index:102; 7304: } 7305: 7306: * html .LCmodal-window { 7307: position:absolute; 7308: } 7309: 7310: .LCclose-window { 7311: position:absolute; 7312: width:32px; 7313: height:32px; 7314: right:8px; 7315: top:8px; 7316: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top; 7317: text-indent:-99999px; 7318: overflow:hidden; 7319: cursor:pointer; 7320: } 7321: 7322: /* 7323: styles used by TTH when "Default set of options to pass to tth/m 7324: when converting TeX" in course settings has been set 7325: 7326: option passed: -t 7327: 7328: */ 7329: 7330: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;} 7331: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;} 7332: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;} 7333: td div.norm {line-height:normal;} 7334: 7335: /* 7336: option passed -y3 7337: */ 7338: 7339: span.roman {font-family: serif; font-style: normal; font-weight: normal;} 7340: span.overacc2 {position: relative; left: .8em; top: -1.2ex;} 7341: span.overacc1 {position: relative; left: .6em; top: -1.2ex;} 7342: 7343: END 7344: } 7345: 7346: =pod 7347: 7348: =item * &headtag() 7349: 7350: Returns a uniform footer for LON-CAPA web pages. 7351: 7352: Inputs: $title - optional title for the head 7353: $head_extra - optional extra HTML to put inside the <head> 7354: $args - optional arguments 7355: force_register - if is true call registerurl so the remote is 7356: informed 7357: redirect -> array ref of 7358: 1- seconds before redirect occurs 7359: 2- url to redirect to 7360: 3- whether the side effect should occur 7361: (side effect of setting 7362: $env{'internal.head.redirect'} to the url 7363: redirected too) 7364: domain -> force to color decorate a page for a specific 7365: domain 7366: function -> force usage of a specific rolish color scheme 7367: bgcolor -> override the default page bgcolor 7368: no_auto_mt_title 7369: -> prevent &mt()ing the title arg 7370: 7371: =cut 7372: 7373: sub headtag { 7374: my ($title,$head_extra,$args) = @_; 7375: 7376: my $function = $args->{'function'} || &get_users_function(); 7377: my $domain = $args->{'domain'} || &determinedomain(); 7378: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain); 7379: my $httphost = $args->{'use_absolute'}; 7380: my $url = join(':',$env{'user.name'},$env{'user.domain'}, 7381: $Apache::lonnet::perlvar{'lonVersion'}, 7382: #time(), 7383: $env{'environment.color.timestamp'}, 7384: $function,$domain,$bgcolor); 7385: 7386: $url = '/adm/css/'.&escape($url).'.css'; 7387: 7388: my $result = 7389: '<head>'. 7390: &font_settings($args); 7391: 7392: my $inhibitprint; 7393: if ($args->{'print_suppress'}) { 7394: $inhibitprint = &print_suppression(); 7395: } 7396: 7397: if (!$args->{'frameset'}) { 7398: $result .= &Apache::lonhtmlcommon::htmlareaheaders(); 7399: } 7400: if ($args->{'force_register'}) { 7401: $result .= &Apache::lonmenu::registerurl(1); 7402: } 7403: if (!$args->{'no_nav_bar'} 7404: && !$args->{'only_body'} 7405: && !$args->{'frameset'}) { 7406: $result .= &help_menu_js($httphost); 7407: $result.=&modal_window(); 7408: $result.=&togglebox_script(); 7409: $result.=&wishlist_window(); 7410: $result.=&LCprogressbarUpdate_script(); 7411: } else { 7412: if ($args->{'add_modal'}) { 7413: $result.=&modal_window(); 7414: } 7415: if ($args->{'add_wishlist'}) { 7416: $result.=&wishlist_window(); 7417: } 7418: if ($args->{'add_togglebox'}) { 7419: $result.=&togglebox_script(); 7420: } 7421: if ($args->{'add_progressbar'}) { 7422: $result.=&LCprogressbarUpdate_script(); 7423: } 7424: } 7425: if (ref($args->{'redirect'})) { 7426: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}}; 7427: $url = &Apache::lonenc::check_encrypt($url); 7428: if (!$inhibit_continue) { 7429: $env{'internal.head.redirect'} = $url; 7430: } 7431: $result.=<<ADDMETA 7432: <meta http-equiv="pragma" content="no-cache" /> 7433: <meta http-equiv="Refresh" content="$time; url=$url" /> 7434: ADDMETA 7435: } else { 7436: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) { 7437: my $requrl = $env{'request.uri'}; 7438: if ($requrl eq '') { 7439: $requrl = $ENV{'REQUEST_URI'}; 7440: $requrl =~ s/\?.+$//; 7441: } 7442: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) || 7443: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') || 7444: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) { 7445: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'}; 7446: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) { 7447: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use); 7448: if (ref($domdefs{'offloadnow'}) eq 'HASH') { 7449: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'}; 7450: if ($domdefs{'offloadnow'}{$lonhost}) { 7451: my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use); 7452: if (($newserver) && ($newserver ne $lonhost)) { 7453: my $numsec = 5; 7454: my $timeout = $numsec * 1000; 7455: my ($newurl,$locknum,%locks,$msg); 7456: if ($env{'request.role.adv'}) { 7457: ($locknum,%locks) = &Apache::lonnet::get_locks(); 7458: } 7459: my $disable_submit = 0; 7460: if ($requrl =~ /$LONCAPA::assess_re/) { 7461: $disable_submit = 1; 7462: } 7463: if ($locknum) { 7464: my @lockinfo = sort(values(%locks)); 7465: $msg = &mt('Once the following tasks are complete: ')."\\n". 7466: join(", ",sort(values(%locks)))."\\n". 7467: &mt('your session will be transferred to a different server, after you click "Roles".'); 7468: } else { 7469: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) { 7470: $msg = &mt('Your LON-CAPA submission has been recorded')."\\n"; 7471: } 7472: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec); 7473: $newurl = '/adm/switchserver?otherserver='.$newserver; 7474: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) { 7475: $newurl .= '&role='.$env{'request.role'}; 7476: } 7477: if ($env{'request.symb'}) { 7478: $newurl .= '&symb='.$env{'request.symb'}; 7479: } else { 7480: $newurl .= '&origurl='.$requrl; 7481: } 7482: } 7483: $result.=<<OFFLOAD 7484: <meta http-equiv="pragma" content="no-cache" /> 7485: <script type="text/javascript"> 7486: // <![CDATA[ 7487: function LC_Offload_Now() { 7488: var dest = "$newurl"; 7489: if (dest != '') { 7490: window.location.href="$newurl"; 7491: } 7492: } 7493: \$(document).ready(function () { 7494: window.alert('$msg'); 7495: if ($disable_submit) { 7496: \$(".LC_hwk_submit").prop("disabled", true); 7497: \$( ".LC_textline" ).prop( "readonly", "readonly"); 7498: } 7499: setTimeout('LC_Offload_Now()', $timeout); 7500: }); 7501: // ]]> 7502: </script> 7503: OFFLOAD 7504: } 7505: } 7506: } 7507: } 7508: } 7509: } 7510: } 7511: if (!defined($title)) { 7512: $title = 'The LearningOnline Network with CAPA'; 7513: } 7514: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } 7515: $result .= '<title> LON-CAPA '.$title.'</title>' 7516: .'<link rel="stylesheet" type="text/css" href="'.$url.'"'; 7517: if (!$args->{'frameset'}) { 7518: $result .= ' /'; 7519: } 7520: $result .= '>' 7521: .$inhibitprint 7522: .$head_extra; 7523: if ($env{'browser.mobile'}) { 7524: $result .= ' 7525: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> 7526: <meta name="apple-mobile-web-app-capable" content="yes" />'; 7527: } 7528: return $result.'</head>'; 7529: } 7530: 7531: =pod 7532: 7533: =item * &font_settings() 7534: 7535: Returns neccessary <meta> to set the proper encoding 7536: 7537: Inputs: optional reference to HASH -- $args passed to &headtag() 7538: 7539: =cut 7540: 7541: sub font_settings { 7542: my ($args) = @_; 7543: my $headerstring=''; 7544: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) || 7545: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) { 7546: $headerstring.= 7547: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"'; 7548: if (!$args->{'frameset'}) { 7549: $headerstring.= ' /'; 7550: } 7551: $headerstring .= '>'."\n"; 7552: } 7553: return $headerstring; 7554: } 7555: 7556: =pod 7557: 7558: =item * &print_suppression() 7559: 7560: In course context returns css which causes the body to be blank when media="print", 7561: if printout generation is unavailable for the current resource. 7562: 7563: This could be because: 7564: 7565: (a) printstartdate is in the future 7566: 7567: (b) printenddate is in the past 7568: 7569: (c) there is an active exam block with "printout" 7570: functionality blocked 7571: 7572: Users with pav, pfo or evb privileges are exempt. 7573: 7574: Inputs: none 7575: 7576: =cut 7577: 7578: 7579: sub print_suppression { 7580: my $noprint; 7581: if ($env{'request.course.id'}) { 7582: my $scope = $env{'request.course.id'}; 7583: if ((&Apache::lonnet::allowed('pav',$scope)) || 7584: (&Apache::lonnet::allowed('pfo',$scope))) { 7585: return; 7586: } 7587: if ($env{'request.course.sec'} ne '') { 7588: $scope .= "/$env{'request.course.sec'}"; 7589: if ((&Apache::lonnet::allowed('pav',$scope)) || 7590: (&Apache::lonnet::allowed('pfo',$scope))) { 7591: return; 7592: } 7593: } 7594: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; 7595: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; 7596: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1); 7597: if ($blocked) { 7598: my $checkrole = "cm./$cdom/$cnum"; 7599: if ($env{'request.course.sec'} ne '') { 7600: $checkrole .= "/$env{'request.course.sec'}"; 7601: } 7602: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) && 7603: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) { 7604: $noprint = 1; 7605: } 7606: } 7607: unless ($noprint) { 7608: my $symb = &Apache::lonnet::symbread(); 7609: if ($symb ne '') { 7610: my $navmap = Apache::lonnavmaps::navmap->new(); 7611: if (ref($navmap)) { 7612: my $res = $navmap->getBySymb($symb); 7613: if (ref($res)) { 7614: if (!$res->resprintable()) { 7615: $noprint = 1; 7616: } 7617: } 7618: } 7619: } 7620: } 7621: if ($noprint) { 7622: return <<"ENDSTYLE"; 7623: <style type="text/css" media="print"> 7624: body { display:none } 7625: </style> 7626: ENDSTYLE 7627: } 7628: } 7629: return; 7630: } 7631: 7632: =pod 7633: 7634: =item * &xml_begin() 7635: 7636: Returns the needed doctype and <html> 7637: 7638: Inputs: none 7639: 7640: =cut 7641: 7642: sub xml_begin { 7643: my ($is_frameset) = @_; 7644: my $output=''; 7645: 7646: if ($env{'browser.mathml'}) { 7647: $output='<?xml version="1.0"?>' 7648: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n" 7649: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" ' 7650: 7651: # .'<!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">] >' 7652: .'<!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">' 7653: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 7654: .'xmlns="http://www.w3.org/1999/xhtml">'; 7655: } elsif ($is_frameset) { 7656: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n". 7657: '<html>'."\n"; 7658: } else { 7659: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n". 7660: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n"; 7661: } 7662: return $output; 7663: } 7664: 7665: =pod 7666: 7667: =item * &start_page() 7668: 7669: Returns a complete <html> .. <body> section for LON-CAPA web pages. 7670: 7671: Inputs: 7672: 7673: =over 4 7674: 7675: $title - optional title for the page 7676: 7677: $head_extra - optional extra HTML to incude inside the <head> 7678: 7679: $args - additional optional args supported are: 7680: 7681: =over 8 7682: 7683: only_body -> is true will set &bodytag() onlybodytag 7684: arg on 7685: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on 7686: add_entries -> additional attributes to add to the <body> 7687: domain -> force to color decorate a page for a 7688: specific domain 7689: function -> force usage of a specific rolish color 7690: scheme 7691: redirect -> see &headtag() 7692: bgcolor -> override the default page bg color 7693: js_ready -> return a string ready for being used in 7694: a javascript writeln 7695: html_encode -> return a string ready for being used in 7696: a html attribute 7697: force_register -> if is true will turn on the &bodytag() 7698: $forcereg arg 7699: frameset -> if true will start with a <frameset> 7700: rather than <body> 7701: skip_phases -> hash ref of 7702: head -> skip the <html><head> generation 7703: body -> skip all <body> generation 7704: no_inline_link -> if true and in remote mode, don't show the 7705: 'Switch To Inline Menu' link 7706: no_auto_mt_title -> prevent &mt()ing the title arg 7707: inherit_jsmath -> when creating popup window in a page, 7708: should it have jsmath forced on by the 7709: current page 7710: bread_crumbs -> Array containing breadcrumbs 7711: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs 7712: group -> includes the current group, if page is for a 7713: specific group 7714: 7715: =back 7716: 7717: =back 7718: 7719: =cut 7720: 7721: sub start_page { 7722: my ($title,$head_extra,$args) = @_; 7723: #&Apache::lonnet::logthis("start_page ".join(':',caller(0))); 7724: 7725: $env{'internal.start_page'}++; 7726: my ($result,@advtools); 7727: 7728: if (! exists($args->{'skip_phases'}{'head'}) ) { 7729: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args); 7730: } 7731: 7732: if (! exists($args->{'skip_phases'}{'body'}) ) { 7733: if ($args->{'frameset'}) { 7734: my $attr_string = &make_attr_string($args->{'force_register'}, 7735: $args->{'add_entries'}); 7736: $result .= "\n<frameset $attr_string>\n"; 7737: } else { 7738: $result .= 7739: &bodytag($title, 7740: $args->{'function'}, $args->{'add_entries'}, 7741: $args->{'only_body'}, $args->{'domain'}, 7742: $args->{'force_register'}, $args->{'no_nav_bar'}, 7743: $args->{'bgcolor'}, $args->{'no_inline_link'}, 7744: $args, \@advtools); 7745: } 7746: } 7747: 7748: if ($args->{'js_ready'}) { 7749: $result = &js_ready($result); 7750: } 7751: if ($args->{'html_encode'}) { 7752: $result = &html_encode($result); 7753: } 7754: 7755: # Preparation for new and consistent functionlist at top of screen 7756: # if ($args->{'functionlist'}) { 7757: # $result .= &build_functionlist(); 7758: #} 7759: 7760: # Don't add anything more if only_body wanted or in const space 7761: return $result if $args->{'only_body'} 7762: || $env{'request.state'} eq 'construct'; 7763: 7764: #Breadcrumbs 7765: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) { 7766: &Apache::lonhtmlcommon::clear_breadcrumbs(); 7767: #if any br links exists, add them to the breadcrumbs 7768: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') { 7769: foreach my $crumb (@{$args->{'bread_crumbs'}}){ 7770: &Apache::lonhtmlcommon::add_breadcrumb($crumb); 7771: } 7772: } 7773: # if @advtools array contains items add then to the breadcrumbs 7774: if (@advtools > 0) { 7775: &Apache::lonmenu::advtools_crumbs(@advtools); 7776: } 7777: 7778: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs 7779: if(exists($args->{'bread_crumbs_component'})){ 7780: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'}); 7781: }else{ 7782: $result .= &Apache::lonhtmlcommon::breadcrumbs(); 7783: } 7784: } elsif (($env{'environment.remote'} eq 'on') && 7785: ($env{'form.inhibitmenu'} ne 'yes') && 7786: ($env{'request.noversionuri'} =~ m{^/res/}) && 7787: ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) { 7788: $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>'; 7789: } 7790: return $result; 7791: } 7792: 7793: sub end_page { 7794: my ($args) = @_; 7795: $env{'internal.end_page'}++; 7796: my $result; 7797: if ($args->{'discussion'}) { 7798: my ($target,$parser); 7799: if (ref($args->{'discussion'})) { 7800: ($target,$parser) =($args->{'discussion'}{'target'}, 7801: $args->{'discussion'}{'parser'}); 7802: } 7803: $result .= &Apache::lonxml::xmlend($target,$parser); 7804: } 7805: if ($args->{'frameset'}) { 7806: $result .= '</frameset>'; 7807: } else { 7808: $result .= &endbodytag($args); 7809: } 7810: unless ($args->{'notbody'}) { 7811: $result .= "\n</html>"; 7812: } 7813: 7814: if ($args->{'js_ready'}) { 7815: $result = &js_ready($result); 7816: } 7817: 7818: if ($args->{'html_encode'}) { 7819: $result = &html_encode($result); 7820: } 7821: 7822: return $result; 7823: } 7824: 7825: sub wishlist_window { 7826: return(<<'ENDWISHLIST'); 7827: <script type="text/javascript"> 7828: // <![CDATA[ 7829: // <!-- BEGIN LON-CAPA Internal 7830: function set_wishlistlink(title, path) { 7831: if (!title) { 7832: title = document.title; 7833: title = title.replace(/^LON-CAPA /,''); 7834: } 7835: title = encodeURIComponent(title); 7836: title = title.replace("'","\\\'"); 7837: if (!path) { 7838: path = location.pathname; 7839: } 7840: path = encodeURIComponent(path); 7841: path = path.replace("'","\\\'"); 7842: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path, 7843: 'wishlistNewLink','width=560,height=350,scrollbars=0'); 7844: } 7845: // END LON-CAPA Internal --> 7846: // ]]> 7847: </script> 7848: ENDWISHLIST 7849: } 7850: 7851: sub modal_window { 7852: return(<<'ENDMODAL'); 7853: <script type="text/javascript"> 7854: // <![CDATA[ 7855: // <!-- BEGIN LON-CAPA Internal 7856: var modalWindow = { 7857: parent:"body", 7858: windowId:null, 7859: content:null, 7860: width:null, 7861: height:null, 7862: close:function() 7863: { 7864: $(".LCmodal-window").remove(); 7865: $(".LCmodal-overlay").remove(); 7866: }, 7867: open:function() 7868: { 7869: var modal = ""; 7870: modal += "<div class=\"LCmodal-overlay\"></div>"; 7871: 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;\">"; 7872: modal += this.content; 7873: modal += "</div>"; 7874: 7875: $(this.parent).append(modal); 7876: 7877: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>"); 7878: $(".LCclose-window").click(function(){modalWindow.close();}); 7879: $(".LCmodal-overlay").click(function(){modalWindow.close();}); 7880: } 7881: }; 7882: var openMyModal = function(source,width,height,scrolling,transparency,style) 7883: { 7884: source = source.replace("'","'"); 7885: modalWindow.windowId = "myModal"; 7886: modalWindow.width = width; 7887: modalWindow.height = height; 7888: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>"; 7889: modalWindow.open(); 7890: }; 7891: // END LON-CAPA Internal --> 7892: // ]]> 7893: </script> 7894: ENDMODAL 7895: } 7896: 7897: sub modal_link { 7898: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_; 7899: unless ($width) { $width=480; } 7900: unless ($height) { $height=400; } 7901: unless ($scrolling) { $scrolling='yes'; } 7902: unless ($transparency) { $transparency='true'; } 7903: 7904: my $target_attr; 7905: if (defined($target)) { 7906: $target_attr = 'target="'.$target.'"'; 7907: } 7908: return <<"ENDLINK"; 7909: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;"> 7910: $linktext</a> 7911: ENDLINK 7912: } 7913: 7914: sub modal_adhoc_script { 7915: my ($funcname,$width,$height,$content)=@_; 7916: return (<<ENDADHOC); 7917: <script type="text/javascript"> 7918: // <![CDATA[ 7919: var $funcname = function() 7920: { 7921: modalWindow.windowId = "myModal"; 7922: modalWindow.width = $width; 7923: modalWindow.height = $height; 7924: modalWindow.content = '$content'; 7925: modalWindow.open(); 7926: }; 7927: // ]]> 7928: </script> 7929: ENDADHOC 7930: } 7931: 7932: sub modal_adhoc_inner { 7933: my ($funcname,$width,$height,$content)=@_; 7934: my $innerwidth=$width-20; 7935: $content=&js_ready( 7936: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}). 7937: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1). 7938: $content. 7939: &end_scrollbox(). 7940: &end_page() 7941: ); 7942: return &modal_adhoc_script($funcname,$width,$height,$content); 7943: } 7944: 7945: sub modal_adhoc_window { 7946: my ($funcname,$width,$height,$content,$linktext)=@_; 7947: return &modal_adhoc_inner($funcname,$width,$height,$content). 7948: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>"; 7949: } 7950: 7951: sub modal_adhoc_launch { 7952: my ($funcname,$width,$height,$content)=@_; 7953: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH); 7954: <script type="text/javascript"> 7955: // <![CDATA[ 7956: $funcname(); 7957: // ]]> 7958: </script> 7959: ENDLAUNCH 7960: } 7961: 7962: sub modal_adhoc_close { 7963: return (<<ENDCLOSE); 7964: <script type="text/javascript"> 7965: // <![CDATA[ 7966: modalWindow.close(); 7967: // ]]> 7968: </script> 7969: ENDCLOSE 7970: } 7971: 7972: sub togglebox_script { 7973: return(<<ENDTOGGLE); 7974: <script type="text/javascript"> 7975: // <![CDATA[ 7976: function LCtoggleDisplay(id,hidetext,showtext) { 7977: link = document.getElementById(id + "link").childNodes[0]; 7978: with (document.getElementById(id).style) { 7979: if (display == "none" ) { 7980: display = "inline"; 7981: link.nodeValue = hidetext; 7982: } else { 7983: display = "none"; 7984: link.nodeValue = showtext; 7985: } 7986: } 7987: } 7988: // ]]> 7989: </script> 7990: ENDTOGGLE 7991: } 7992: 7993: sub start_togglebox { 7994: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_; 7995: unless ($heading) { $heading=''; } else { $heading.=' '; } 7996: unless ($showtext) { $showtext=&mt('show'); } 7997: unless ($hidetext) { $hidetext=&mt('hide'); } 7998: unless ($headerbg) { $headerbg='#FFFFFF'; } 7999: return &start_data_table(). 8000: &start_data_table_header_row(). 8001: '<td bgcolor="'.$headerbg.'">'.$heading. 8002: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''. 8003: $showtext.'\')">'.$showtext.'</a>]</td>'. 8004: &end_data_table_header_row(). 8005: '<tr id="'.$id.'" style="display:none""><td>'; 8006: } 8007: 8008: sub end_togglebox { 8009: return '</td></tr>'.&end_data_table(); 8010: } 8011: 8012: sub LCprogressbar_script { 8013: my ($id)=@_; 8014: return(<<ENDPROGRESS); 8015: <script type="text/javascript"> 8016: // <![CDATA[ 8017: \$('#progressbar$id').progressbar({ 8018: value: 0, 8019: change: function(event, ui) { 8020: var newVal = \$(this).progressbar('option', 'value'); 8021: \$('.pblabel', this).text(LCprogressTxt); 8022: } 8023: }); 8024: // ]]> 8025: </script> 8026: ENDPROGRESS 8027: } 8028: 8029: sub LCprogressbarUpdate_script { 8030: return(<<ENDPROGRESSUPDATE); 8031: <style type="text/css"> 8032: .ui-progressbar { position:relative; } 8033: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; } 8034: </style> 8035: <script type="text/javascript"> 8036: // <![CDATA[ 8037: var LCprogressTxt='---'; 8038: 8039: function LCupdateProgress(percent,progresstext,id) { 8040: LCprogressTxt=progresstext; 8041: \$('#progressbar'+id).progressbar('value',percent); 8042: } 8043: // ]]> 8044: </script> 8045: ENDPROGRESSUPDATE 8046: } 8047: 8048: my $LClastpercent; 8049: my $LCidcnt; 8050: my $LCcurrentid; 8051: 8052: sub LCprogressbar { 8053: my ($r)=(@_); 8054: $LClastpercent=0; 8055: $LCidcnt++; 8056: $LCcurrentid=$$.'_'.$LCidcnt; 8057: my $starting=&mt('Starting'); 8058: my $content=(<<ENDPROGBAR); 8059: <div id="progressbar$LCcurrentid"> 8060: <span class="pblabel">$starting</span> 8061: </div> 8062: ENDPROGBAR 8063: &r_print($r,$content.&LCprogressbar_script($LCcurrentid)); 8064: } 8065: 8066: sub LCprogressbarUpdate { 8067: my ($r,$val,$text)=@_; 8068: unless ($val) { 8069: if ($LClastpercent) { 8070: $val=$LClastpercent; 8071: } else { 8072: $val=0; 8073: } 8074: } 8075: if ($val<0) { $val=0; } 8076: if ($val>100) { $val=0; } 8077: $LClastpercent=$val; 8078: unless ($text) { $text=$val.'%'; } 8079: $text=&js_ready($text); 8080: &r_print($r,<<ENDUPDATE); 8081: <script type="text/javascript"> 8082: // <![CDATA[ 8083: LCupdateProgress($val,'$text','$LCcurrentid'); 8084: // ]]> 8085: </script> 8086: ENDUPDATE 8087: } 8088: 8089: sub LCprogressbarClose { 8090: my ($r)=@_; 8091: $LClastpercent=0; 8092: &r_print($r,<<ENDCLOSE); 8093: <script type="text/javascript"> 8094: // <![CDATA[ 8095: \$("#progressbar$LCcurrentid").hide('slow'); 8096: // ]]> 8097: </script> 8098: ENDCLOSE 8099: } 8100: 8101: sub r_print { 8102: my ($r,$to_print)=@_; 8103: if ($r) { 8104: $r->print($to_print); 8105: $r->rflush(); 8106: } else { 8107: print($to_print); 8108: } 8109: } 8110: 8111: sub html_encode { 8112: my ($result) = @_; 8113: 8114: $result = &HTML::Entities::encode($result,'<>&"'); 8115: 8116: return $result; 8117: } 8118: 8119: sub js_ready { 8120: my ($result) = @_; 8121: 8122: $result =~ s/[\n\r]/ /xmsg; 8123: $result =~ s/\\/\\\\/xmsg; 8124: $result =~ s/'/\\'/xmsg; 8125: $result =~ s{</}{<\\/}xmsg; 8126: 8127: return $result; 8128: } 8129: 8130: sub validate_page { 8131: if ( exists($env{'internal.start_page'}) 8132: && $env{'internal.start_page'} > 1) { 8133: &Apache::lonnet::logthis('start_page called multiple times '. 8134: $env{'internal.start_page'}.' '. 8135: $ENV{'request.filename'}); 8136: } 8137: if ( exists($env{'internal.end_page'}) 8138: && $env{'internal.end_page'} > 1) { 8139: &Apache::lonnet::logthis('end_page called multiple times '. 8140: $env{'internal.end_page'}.' '. 8141: $env{'request.filename'}); 8142: } 8143: if ( exists($env{'internal.start_page'}) 8144: && ! exists($env{'internal.end_page'})) { 8145: &Apache::lonnet::logthis('start_page called without end_page '. 8146: $env{'request.filename'}); 8147: } 8148: if ( ! exists($env{'internal.start_page'}) 8149: && exists($env{'internal.end_page'})) { 8150: &Apache::lonnet::logthis('end_page called without start_page'. 8151: $env{'request.filename'}); 8152: } 8153: } 8154: 8155: 8156: sub start_scrollbox { 8157: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_; 8158: unless ($outerwidth) { $outerwidth='520px'; } 8159: unless ($width) { $width='500px'; } 8160: unless ($height) { $height='200px'; } 8161: my ($table_id,$div_id,$tdcol); 8162: if ($id ne '') { 8163: $table_id = ' id="table_'.$id.'"'; 8164: $div_id = ' id="div_'.$id.'"'; 8165: } 8166: if ($bgcolor ne '') { 8167: $tdcol = "background-color: $bgcolor;"; 8168: } 8169: my $nicescroll_js; 8170: if ($env{'browser.mobile'}) { 8171: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready); 8172: } 8173: return <<"END"; 8174: $nicescroll_js 8175: 8176: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"> 8177: <div style="overflow:auto; width:$width; height:$height;"$div_id> 8178: END 8179: } 8180: 8181: sub end_scrollbox { 8182: return '</div></td></tr></table>'; 8183: } 8184: 8185: sub nicescroll_javascript { 8186: my ($id,$cursor,$needjsready,$framecheck,$location) = @_; 8187: my %options; 8188: if (ref($cursor) eq 'HASH') { 8189: %options = %{$cursor}; 8190: } 8191: unless ($options{'railalign'} =~ /^left|right$/) { 8192: $options{'railalign'} = 'left'; 8193: } 8194: unless ($options{'cursorcolor'} =~ /^\#\w+$/) { 8195: my $function = &get_users_function(); 8196: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'}); 8197: unless ($options{'cursorcolor'} =~ /^\#\w+$/) { 8198: $options{'cursorcolor'} = '#00F'; 8199: } 8200: } 8201: if ($options{'cursoropacity'} =~ /^[\d.]+$/) { 8202: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) { 8203: $options{'cursoropacity'}='1.0'; 8204: } 8205: } else { 8206: $options{'cursoropacity'}='1.0'; 8207: } 8208: if ($options{'cursorfixedheight'} eq 'none') { 8209: delete($options{'cursorfixedheight'}); 8210: } else { 8211: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; } 8212: } 8213: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) { 8214: delete($options{'railoffset'}); 8215: } 8216: my @niceoptions; 8217: while (my($key,$value) = each(%options)) { 8218: if ($value =~ /^\{.+\}$/) { 8219: push(@niceoptions,$key.':'.$value); 8220: } else { 8221: push(@niceoptions,$key.':"'.$value.'"'); 8222: } 8223: } 8224: my $nicescroll_js = ' 8225: $(document).ready( 8226: function() { 8227: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'}); 8228: } 8229: ); 8230: '; 8231: if ($framecheck) { 8232: $nicescroll_js .= ' 8233: function expand_div(caller) { 8234: if (top === self) { 8235: document.getElementById("'.$id.'").style.width = "auto"; 8236: document.getElementById("'.$id.'").style.height = "auto"; 8237: } else { 8238: try { 8239: if (parent.frames) { 8240: if (parent.frames.length > 1) { 8241: var framesrc = parent.frames[1].location.href; 8242: var currsrc = framesrc.replace(/\#.*$/,""); 8243: if ((caller == "search") || (currsrc == "'.$location.'")) { 8244: document.getElementById("'.$id.'").style.width = "auto"; 8245: document.getElementById("'.$id.'").style.height = "auto"; 8246: } 8247: } 8248: } 8249: } catch (e) { 8250: return; 8251: } 8252: } 8253: return; 8254: } 8255: '; 8256: } 8257: if ($needjsready) { 8258: $nicescroll_js = ' 8259: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n"; 8260: } else { 8261: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js); 8262: } 8263: return $nicescroll_js; 8264: } 8265: 8266: sub simple_error_page { 8267: my ($r,$title,$msg,$args) = @_; 8268: if (ref($args) eq 'HASH') { 8269: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); } 8270: } else { 8271: $msg = &mt($msg); 8272: } 8273: 8274: my $page = 8275: &Apache::loncommon::start_page($title). 8276: '<p class="LC_error">'.$msg.'</p>'. 8277: &Apache::loncommon::end_page(); 8278: if (ref($r)) { 8279: $r->print($page); 8280: return; 8281: } 8282: return $page; 8283: } 8284: 8285: { 8286: my @row_count; 8287: 8288: sub start_data_table_count { 8289: unshift(@row_count, 0); 8290: return; 8291: } 8292: 8293: sub end_data_table_count { 8294: shift(@row_count); 8295: return; 8296: } 8297: 8298: sub start_data_table { 8299: my ($add_class,$id) = @_; 8300: my $css_class = (join(' ','LC_data_table',$add_class)); 8301: my $table_id; 8302: if (defined($id)) { 8303: $table_id = ' id="'.$id.'"'; 8304: } 8305: &start_data_table_count(); 8306: return '<table class="'.$css_class.'"'.$table_id.'>'."\n"; 8307: } 8308: 8309: sub end_data_table { 8310: &end_data_table_count(); 8311: return '</table>'."\n";; 8312: } 8313: 8314: sub start_data_table_row { 8315: my ($add_class, $id) = @_; 8316: $row_count[0]++; 8317: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row'; 8318: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq ''); 8319: $id = (' id="'.$id.'"') unless ($id eq ''); 8320: return '<tr class="'.$css_class.'"'.$id.'>'."\n"; 8321: } 8322: 8323: sub continue_data_table_row { 8324: my ($add_class, $id) = @_; 8325: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row'; 8326: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq ''); 8327: $id = (' id="'.$id.'"') unless ($id eq ''); 8328: return '<tr class="'.$css_class.'"'.$id.'>'."\n"; 8329: } 8330: 8331: sub end_data_table_row { 8332: return '</tr>'."\n";; 8333: } 8334: 8335: sub start_data_table_empty_row { 8336: # $row_count[0]++; 8337: return '<tr class="LC_empty_row" >'."\n";; 8338: } 8339: 8340: sub end_data_table_empty_row { 8341: return '</tr>'."\n";; 8342: } 8343: 8344: sub start_data_table_header_row { 8345: return '<tr class="LC_header_row">'."\n";; 8346: } 8347: 8348: sub end_data_table_header_row { 8349: return '</tr>'."\n";; 8350: } 8351: 8352: sub data_table_caption { 8353: my $caption = shift; 8354: return "<caption class=\"LC_caption\">$caption</caption>"; 8355: } 8356: } 8357: 8358: =pod 8359: 8360: =item * &inhibit_menu_check($arg) 8361: 8362: Checks for a inhibitmenu state and generates output to preserve it 8363: 8364: Inputs: $arg - can be any of 8365: - undef - in which case the return value is a string 8366: to add into arguments list of a uri 8367: - 'input' - in which case the return value is a HTML 8368: <form> <input> field of type hidden to 8369: preserve the value 8370: - a url - in which case the return value is the url with 8371: the neccesary cgi args added to preserve the 8372: inhibitmenu state 8373: - a ref to a url - no return value, but the string is 8374: updated to include the neccessary cgi 8375: args to preserve the inhibitmenu state 8376: 8377: =cut 8378: 8379: sub inhibit_menu_check { 8380: my ($arg) = @_; 8381: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']); 8382: if ($arg eq 'input') { 8383: if ($env{'form.inhibitmenu'}) { 8384: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />'; 8385: } else { 8386: return 8387: } 8388: } 8389: if ($env{'form.inhibitmenu'}) { 8390: if (ref($arg)) { 8391: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'}; 8392: } elsif ($arg eq '') { 8393: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'}; 8394: } else { 8395: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'}; 8396: } 8397: } 8398: if (!ref($arg)) { 8399: return $arg; 8400: } 8401: } 8402: 8403: ############################################### 8404: 8405: =pod 8406: 8407: =back 8408: 8409: =head1 User Information Routines 8410: 8411: =over 4 8412: 8413: =item * &get_users_function() 8414: 8415: Used by &bodytag to determine the current users primary role. 8416: Returns either 'student','coordinator','admin', or 'author'. 8417: 8418: =cut 8419: 8420: ############################################### 8421: sub get_users_function { 8422: my $function = 'norole'; 8423: if ($env{'request.role'}=~/^(st)/) { 8424: $function='student'; 8425: } 8426: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) { 8427: $function='coordinator'; 8428: } 8429: if ($env{'request.role'}=~/^(su|dc|ad|li)/) { 8430: $function='admin'; 8431: } 8432: if (($env{'request.role'}=~/^(au|ca|aa)/) || 8433: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) { 8434: $function='author'; 8435: } 8436: return $function; 8437: } 8438: 8439: ############################################### 8440: 8441: =pod 8442: 8443: =item * &show_course() 8444: 8445: Used by lonmenu.pm and lonroles.pm to determine whether to use the word 8446: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles. 8447: 8448: Inputs: 8449: None 8450: 8451: Outputs: 8452: Scalar: 1 if 'Course' to be used, 0 otherwise. 8453: 8454: =cut 8455: 8456: ############################################### 8457: sub show_course { 8458: my $course = !$env{'user.adv'}; 8459: if (!$env{'user.adv'}) { 8460: foreach my $env (keys(%env)) { 8461: next if ($env !~ m/^user\.priv\./); 8462: if ($env !~ m/^user\.priv\.(?:st|cm)/) { 8463: $course = 0; 8464: last; 8465: } 8466: } 8467: } 8468: return $course; 8469: } 8470: 8471: ############################################### 8472: 8473: =pod 8474: 8475: =item * &check_user_status() 8476: 8477: Determines current status of supplied role for a 8478: specific user. Roles can be active, previous or future. 8479: 8480: Inputs: 8481: user's domain, user's username, course's domain, 8482: course's number, optional section ID. 8483: 8484: Outputs: 8485: role status: active, previous or future. 8486: 8487: =cut 8488: 8489: sub check_user_status { 8490: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_; 8491: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname); 8492: my @uroles = keys(%userinfo); 8493: my $srchstr; 8494: my $active_chk = 'none'; 8495: my $now = time; 8496: if (@uroles > 0) { 8497: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) { 8498: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role; 8499: } else { 8500: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role; 8501: } 8502: if (grep/^\Q$srchstr\E$/,@uroles) { 8503: my $role_end = 0; 8504: my $role_start = 0; 8505: $active_chk = 'active'; 8506: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) { 8507: $role_end = $1; 8508: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) { 8509: $role_start = $1; 8510: } 8511: } 8512: if ($role_start > 0) { 8513: if ($now < $role_start) { 8514: $active_chk = 'future'; 8515: } 8516: } 8517: if ($role_end > 0) { 8518: if ($now > $role_end) { 8519: $active_chk = 'previous'; 8520: } 8521: } 8522: } 8523: } 8524: return $active_chk; 8525: } 8526: 8527: ############################################### 8528: 8529: =pod 8530: 8531: =item * &get_sections() 8532: 8533: Determines all the sections for a course including 8534: sections with students and sections containing other roles. 8535: Incoming parameters: 8536: 8537: 1. domain 8538: 2. course number 8539: 3. reference to array containing roles for which sections should 8540: be gathered (optional). 8541: 4. reference to array containing status types for which sections 8542: should be gathered (optional). 8543: 8544: If the third argument is undefined, sections are gathered for any role. 8545: If the fourth argument is undefined, sections are gathered for any status. 8546: Permissible values are 'active' or 'future' or 'previous'. 8547: 8548: Returns section hash (keys are section IDs, values are 8549: number of users in each section), subject to the 8550: optional roles filter, optional status filter 8551: 8552: =cut 8553: 8554: ############################################### 8555: sub get_sections { 8556: my ($cdom,$cnum,$possible_roles,$possible_status) = @_; 8557: if (!defined($cdom) || !defined($cnum)) { 8558: my $cid = $env{'request.course.id'}; 8559: 8560: return if (!defined($cid)); 8561: 8562: $cdom = $env{'course.'.$cid.'.domain'}; 8563: $cnum = $env{'course.'.$cid.'.num'}; 8564: } 8565: 8566: my %sectioncount; 8567: my $now = time; 8568: 8569: my $check_students = 1; 8570: my $only_students = 0; 8571: if (ref($possible_roles) eq 'ARRAY') { 8572: if (grep(/^st$/,@{$possible_roles})) { 8573: if (@{$possible_roles} == 1) { 8574: $only_students = 1; 8575: } 8576: } else { 8577: $check_students = 0; 8578: } 8579: } 8580: 8581: if ($check_students) { 8582: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum); 8583: my $sec_index = &Apache::loncoursedata::CL_SECTION(); 8584: my $status_index = &Apache::loncoursedata::CL_STATUS(); 8585: my $start_index = &Apache::loncoursedata::CL_START(); 8586: my $end_index = &Apache::loncoursedata::CL_END(); 8587: my $status; 8588: while (my ($student,$data) = each(%$classlist)) { 8589: my ($section,$stu_status,$start,$end) = ($data->[$sec_index], 8590: $data->[$status_index], 8591: $data->[$start_index], 8592: $data->[$end_index]); 8593: if ($stu_status eq 'Active') { 8594: $status = 'active'; 8595: } elsif ($end < $now) { 8596: $status = 'previous'; 8597: } elsif ($start > $now) { 8598: $status = 'future'; 8599: } 8600: if ($section ne '-1' && $section !~ /^\s*$/) { 8601: if ((!defined($possible_status)) || (($status ne '') && 8602: (grep/^\Q$status\E$/,@{$possible_status}))) { 8603: $sectioncount{$section}++; 8604: } 8605: } 8606: } 8607: } 8608: if ($only_students) { 8609: return %sectioncount; 8610: } 8611: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum); 8612: foreach my $user (sort(keys(%courseroles))) { 8613: if ($user !~ /^(\w{2})/) { next; } 8614: my ($role) = ($user =~ /^(\w{2})/); 8615: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; } 8616: my ($section,$status); 8617: if ($role eq 'cr' && 8618: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) { 8619: $section=$1; 8620: } 8621: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; } 8622: if (!defined($section) || $section eq '-1') { next; } 8623: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/); 8624: if ($end == -1 && $start == -1) { 8625: next; #deleted role 8626: } 8627: if (!defined($possible_status)) { 8628: $sectioncount{$section}++; 8629: } else { 8630: if ((!$end || $end >= $now) && (!$start || $start <= $now)) { 8631: $status = 'active'; 8632: } elsif ($end < $now) { 8633: $status = 'future'; 8634: } elsif ($start > $now) { 8635: $status = 'previous'; 8636: } 8637: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) { 8638: $sectioncount{$section}++; 8639: } 8640: } 8641: } 8642: return %sectioncount; 8643: } 8644: 8645: ############################################### 8646: 8647: =pod 8648: 8649: =item * &get_course_users() 8650: 8651: Retrieves usernames:domains for users in the specified course 8652: with specific role(s), and access status. 8653: 8654: Incoming parameters: 8655: 1. course domain 8656: 2. course number 8657: 3. access status: users must have - either active, 8658: previous, future, or all. 8659: 4. reference to array of permissible roles 8660: 5. reference to array of section restrictions (optional) 8661: 6. reference to results object (hash of hashes). 8662: 7. reference to optional userdata hash 8663: 8. reference to optional statushash 8664: 9. flag if privileged users (except those set to unhide in 8665: course settings) should be excluded 8666: Keys of top level results hash are roles. 8667: Keys of inner hashes are username:domain, with 8668: values set to access type. 8669: Optional userdata hash returns an array with arguments in the 8670: same order as loncoursedata::get_classlist() for student data. 8671: 8672: Optional statushash returns 8673: 8674: Entries for end, start, section and status are blank because 8675: of the possibility of multiple values for non-student roles. 8676: 8677: =cut 8678: 8679: ############################################### 8680: 8681: sub get_course_users { 8682: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_; 8683: my %idx = (); 8684: my %seclists; 8685: 8686: $idx{udom} = &Apache::loncoursedata::CL_SDOM(); 8687: $idx{uname} = &Apache::loncoursedata::CL_SNAME(); 8688: $idx{end} = &Apache::loncoursedata::CL_END(); 8689: $idx{start} = &Apache::loncoursedata::CL_START(); 8690: $idx{id} = &Apache::loncoursedata::CL_ID(); 8691: $idx{section} = &Apache::loncoursedata::CL_SECTION(); 8692: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME(); 8693: $idx{status} = &Apache::loncoursedata::CL_STATUS(); 8694: 8695: if (grep(/^st$/,@{$roles})) { 8696: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum); 8697: my $now = time; 8698: foreach my $student (keys(%{$classlist})) { 8699: my $match = 0; 8700: my $secmatch = 0; 8701: my $section = $$classlist{$student}[$idx{section}]; 8702: my $status = $$classlist{$student}[$idx{status}]; 8703: if ($section eq '') { 8704: $section = 'none'; 8705: } 8706: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) { 8707: if (grep(/^all$/,@{$sections})) { 8708: $secmatch = 1; 8709: } elsif ($$classlist{$student}[$idx{section}] eq '') { 8710: if (grep(/^none$/,@{$sections})) { 8711: $secmatch = 1; 8712: } 8713: } else { 8714: if (grep(/^\Q$section\E$/,@{$sections})) { 8715: $secmatch = 1; 8716: } 8717: } 8718: if (!$secmatch) { 8719: next; 8720: } 8721: } 8722: if (defined($$types{'active'})) { 8723: if ($$classlist{$student}[$idx{status}] eq 'Active') { 8724: push(@{$$users{st}{$student}},'active'); 8725: $match = 1; 8726: } 8727: } 8728: if (defined($$types{'previous'})) { 8729: if ($$classlist{$student}[$idx{status}] eq 'Expired') { 8730: push(@{$$users{st}{$student}},'previous'); 8731: $match = 1; 8732: } 8733: } 8734: if (defined($$types{'future'})) { 8735: if ($$classlist{$student}[$idx{status}] eq 'Future') { 8736: push(@{$$users{st}{$student}},'future'); 8737: $match = 1; 8738: } 8739: } 8740: if ($match) { 8741: push(@{$seclists{$student}},$section); 8742: if (ref($userdata) eq 'HASH') { 8743: $$userdata{$student} = $$classlist{$student}; 8744: } 8745: if (ref($statushash) eq 'HASH') { 8746: $statushash->{$student}{'st'}{$section} = $status; 8747: } 8748: } 8749: } 8750: } 8751: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) { 8752: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum); 8753: my $now = time; 8754: my %displaystatus = ( previous => 'Expired', 8755: active => 'Active', 8756: future => 'Future', 8757: ); 8758: my (%nothide,@possdoms); 8759: if ($hidepriv) { 8760: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum); 8761: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) { 8762: if ($user !~ /:/) { 8763: $nothide{join(':',split(/[\@]/,$user))}=1; 8764: } else { 8765: $nothide{$user} = 1; 8766: } 8767: } 8768: my @possdoms = ($cdom); 8769: if ($coursehash{'checkforpriv'}) { 8770: push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 8771: } 8772: } 8773: foreach my $person (sort(keys(%coursepersonnel))) { 8774: my $match = 0; 8775: my $secmatch = 0; 8776: my $status; 8777: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/); 8778: $user =~ s/:$//; 8779: my ($end,$start) = split(/:/,$coursepersonnel{$person}); 8780: if ($end == -1 || $start == -1) { 8781: next; 8782: } 8783: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) || 8784: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) { 8785: my ($uname,$udom) = split(/:/,$user); 8786: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) { 8787: if (grep(/^all$/,@{$sections})) { 8788: $secmatch = 1; 8789: } elsif ($usec eq '') { 8790: if (grep(/^none$/,@{$sections})) { 8791: $secmatch = 1; 8792: } 8793: } else { 8794: if (grep(/^\Q$usec\E$/,@{$sections})) { 8795: $secmatch = 1; 8796: } 8797: } 8798: if (!$secmatch) { 8799: next; 8800: } 8801: } 8802: if ($usec eq '') { 8803: $usec = 'none'; 8804: } 8805: if ($uname ne '' && $udom ne '') { 8806: if ($hidepriv) { 8807: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) && 8808: (!$nothide{$uname.':'.$udom})) { 8809: next; 8810: } 8811: } 8812: if ($end > 0 && $end < $now) { 8813: $status = 'previous'; 8814: } elsif ($start > $now) { 8815: $status = 'future'; 8816: } else { 8817: $status = 'active'; 8818: } 8819: foreach my $type (keys(%{$types})) { 8820: if ($status eq $type) { 8821: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) { 8822: push(@{$$users{$role}{$user}},$type); 8823: } 8824: $match = 1; 8825: } 8826: } 8827: if (($match) && (ref($userdata) eq 'HASH')) { 8828: if (!exists($$userdata{$uname.':'.$udom})) { 8829: &get_user_info($udom,$uname,\%idx,$userdata); 8830: } 8831: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) { 8832: push(@{$seclists{$uname.':'.$udom}},$usec); 8833: } 8834: if (ref($statushash) eq 'HASH') { 8835: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status}; 8836: } 8837: } 8838: } 8839: } 8840: } 8841: if (grep(/^ow$/,@{$roles})) { 8842: if ((defined($cdom)) && (defined($cnum))) { 8843: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum); 8844: if ( defined($csettings{'internal.courseowner'}) ) { 8845: my $owner = $csettings{'internal.courseowner'}; 8846: next if ($owner eq ''); 8847: my ($ownername,$ownerdom); 8848: if ($owner =~ /^([^:]+):([^:]+)$/) { 8849: $ownername = $1; 8850: $ownerdom = $2; 8851: } else { 8852: $ownername = $owner; 8853: $ownerdom = $cdom; 8854: $owner = $ownername.':'.$ownerdom; 8855: } 8856: @{$$users{'ow'}{$owner}} = 'any'; 8857: if (defined($userdata) && 8858: !exists($$userdata{$owner})) { 8859: &get_user_info($ownerdom,$ownername,\%idx,$userdata); 8860: if (!grep(/^none$/,@{$seclists{$owner}})) { 8861: push(@{$seclists{$owner}},'none'); 8862: } 8863: if (ref($statushash) eq 'HASH') { 8864: $statushash->{$owner}{'ow'}{'none'} = 'Any'; 8865: } 8866: } 8867: } 8868: } 8869: } 8870: foreach my $user (keys(%seclists)) { 8871: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}}); 8872: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}}); 8873: } 8874: } 8875: return; 8876: } 8877: 8878: sub get_user_info { 8879: my ($udom,$uname,$idx,$userdata) = @_; 8880: $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 8881: &plainname($uname,$udom,'lastname'); 8882: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname; 8883: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom; 8884: my %idhash = &Apache::lonnet::idrget($udom,($uname)); 8885: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 8886: return; 8887: } 8888: 8889: ############################################### 8890: 8891: =pod 8892: 8893: =item * &get_user_quota() 8894: 8895: Retrieves quota assigned for storage of user files. 8896: Default is to report quota for portfolio files. 8897: 8898: Incoming parameters: 8899: 1. user's username 8900: 2. user's domain 8901: 3. quota name - portfolio, author, or course 8902: (if no quota name provided, defaults to portfolio). 8903: 4. crstype - official, unofficial, textbook or community, if quota name is 8904: course 8905: 8906: Returns: 8907: 1. Disk quota (in MB) assigned to student. 8908: 2. (Optional) Type of setting: custom or default 8909: (individually assigned or default for user's 8910: institutional status). 8911: 3. (Optional) - User's institutional status (e.g., faculty, staff 8912: or student - types as defined in localenroll::inst_usertypes 8913: for user's domain, which determines default quota for user. 8914: 4. (Optional) - Default quota which would apply to the user. 8915: 8916: If a value has been stored in the user's environment, 8917: it will return that, otherwise it returns the maximal default 8918: defined for the user's institutional status(es) in the domain. 8919: 8920: =cut 8921: 8922: ############################################### 8923: 8924: 8925: sub get_user_quota { 8926: my ($uname,$udom,$quotaname,$crstype) = @_; 8927: my ($quota,$quotatype,$settingstatus,$defquota); 8928: if (!defined($udom)) { 8929: $udom = $env{'user.domain'}; 8930: } 8931: if (!defined($uname)) { 8932: $uname = $env{'user.name'}; 8933: } 8934: if (($udom eq '' || $uname eq '') || 8935: ($udom eq 'public') && ($uname eq 'public')) { 8936: $quota = 0; 8937: $quotatype = 'default'; 8938: $defquota = 0; 8939: } else { 8940: my $inststatus; 8941: if ($quotaname eq 'course') { 8942: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) && 8943: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) { 8944: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'}; 8945: } else { 8946: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname"); 8947: $quota = $cenv{'internal.uploadquota'}; 8948: } 8949: } else { 8950: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) { 8951: if ($quotaname eq 'author') { 8952: $quota = $env{'environment.authorquota'}; 8953: } else { 8954: $quota = $env{'environment.portfolioquota'}; 8955: } 8956: $inststatus = $env{'environment.inststatus'}; 8957: } else { 8958: my %userenv = 8959: &Apache::lonnet::get('environment',['portfolioquota', 8960: 'authorquota','inststatus'],$udom,$uname); 8961: my ($tmp) = keys(%userenv); 8962: if ($tmp !~ /^(con_lost|error|no_such_host)/i) { 8963: if ($quotaname eq 'author') { 8964: $quota = $userenv{'authorquota'}; 8965: } else { 8966: $quota = $userenv{'portfolioquota'}; 8967: } 8968: $inststatus = $userenv{'inststatus'}; 8969: } else { 8970: undef(%userenv); 8971: } 8972: } 8973: } 8974: if ($quota eq '' || wantarray) { 8975: if ($quotaname eq 'course') { 8976: my %domdefs = &Apache::lonnet::get_domain_defaults($udom); 8977: if (($crstype eq 'official') || ($crstype eq 'unofficial') || 8978: ($crstype eq 'community') || ($crstype eq 'textbook')) { 8979: $defquota = $domdefs{$crstype.'quota'}; 8980: } 8981: if ($defquota eq '') { 8982: $defquota = 500; 8983: } 8984: } else { 8985: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname); 8986: } 8987: if ($quota eq '') { 8988: $quota = $defquota; 8989: $quotatype = 'default'; 8990: } else { 8991: $quotatype = 'custom'; 8992: } 8993: } 8994: } 8995: if (wantarray) { 8996: return ($quota,$quotatype,$settingstatus,$defquota); 8997: } else { 8998: return $quota; 8999: } 9000: } 9001: 9002: ############################################### 9003: 9004: =pod 9005: 9006: =item * &default_quota() 9007: 9008: Retrieves default quota assigned for storage of user portfolio files, 9009: given an (optional) user's institutional status. 9010: 9011: Incoming parameters: 9012: 9013: 1. domain 9014: 2. (Optional) institutional status(es). This is a : separated list of 9015: status types (e.g., faculty, staff, student etc.) 9016: which apply to the user for whom the default is being retrieved. 9017: If the institutional status string in undefined, the domain 9018: default quota will be returned. 9019: 3. quota name - portfolio, author, or course 9020: (if no quota name provided, defaults to portfolio). 9021: 9022: Returns: 9023: 9024: 1. Default disk quota (in MB) for user portfolios in the domain. 9025: 2. (Optional) institutional type which determined the value of the 9026: default quota. 9027: 9028: If a value has been stored in the domain's configuration db, 9029: it will return that, otherwise it returns 20 (for backwards 9030: compatibility with domains which have not set up a configuration 9031: db file; the original statically defined portfolio quota was 20 MB). 9032: 9033: If the user's status includes multiple types (e.g., staff and student), 9034: the largest default quota which applies to the user determines the 9035: default quota returned. 9036: 9037: =cut 9038: 9039: ############################################### 9040: 9041: 9042: sub default_quota { 9043: my ($udom,$inststatus,$quotaname) = @_; 9044: my ($defquota,$settingstatus); 9045: my %quotahash = &Apache::lonnet::get_dom('configuration', 9046: ['quotas'],$udom); 9047: my $key = 'defaultquota'; 9048: if ($quotaname eq 'author') { 9049: $key = 'authorquota'; 9050: } 9051: if (ref($quotahash{'quotas'}) eq 'HASH') { 9052: if ($inststatus ne '') { 9053: my @statuses = map { &unescape($_); } split(/:/,$inststatus); 9054: foreach my $item (@statuses) { 9055: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') { 9056: if ($quotahash{'quotas'}{$key}{$item} ne '') { 9057: if ($defquota eq '') { 9058: $defquota = $quotahash{'quotas'}{$key}{$item}; 9059: $settingstatus = $item; 9060: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) { 9061: $defquota = $quotahash{'quotas'}{$key}{$item}; 9062: $settingstatus = $item; 9063: } 9064: } 9065: } elsif ($key eq 'defaultquota') { 9066: if ($quotahash{'quotas'}{$item} ne '') { 9067: if ($defquota eq '') { 9068: $defquota = $quotahash{'quotas'}{$item}; 9069: $settingstatus = $item; 9070: } elsif ($quotahash{'quotas'}{$item} > $defquota) { 9071: $defquota = $quotahash{'quotas'}{$item}; 9072: $settingstatus = $item; 9073: } 9074: } 9075: } 9076: } 9077: } 9078: if ($defquota eq '') { 9079: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') { 9080: $defquota = $quotahash{'quotas'}{$key}{'default'}; 9081: } elsif ($key eq 'defaultquota') { 9082: $defquota = $quotahash{'quotas'}{'default'}; 9083: } 9084: $settingstatus = 'default'; 9085: if ($defquota eq '') { 9086: if ($quotaname eq 'author') { 9087: $defquota = 500; 9088: } 9089: } 9090: } 9091: } else { 9092: $settingstatus = 'default'; 9093: if ($quotaname eq 'author') { 9094: $defquota = 500; 9095: } else { 9096: $defquota = 20; 9097: } 9098: } 9099: if (wantarray) { 9100: return ($defquota,$settingstatus); 9101: } else { 9102: return $defquota; 9103: } 9104: } 9105: 9106: ############################################### 9107: 9108: =pod 9109: 9110: =item * &excess_filesize_warning() 9111: 9112: Returns warning message if upload of file to authoring space, or copying 9113: of existing file within authoring space will cause quota for the authoring 9114: space to be exceeded. 9115: 9116: Same, if upload of a file directly to a course/community via Course Editor 9117: will cause quota for uploaded content for the course to be exceeded. 9118: 9119: Inputs: 7 9120: 1. username or coursenum 9121: 2. domain 9122: 3. context ('author' or 'course') 9123: 4. filename of file for which action is being requested 9124: 5. filesize (kB) of file 9125: 6. action being taken: copy or upload. 9126: 7. quotatype (in course context -- official, unofficial, community or textbook). 9127: 9128: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded, 9129: otherwise return null. 9130: 9131: =back 9132: 9133: =cut 9134: 9135: sub excess_filesize_warning { 9136: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_; 9137: my $current_disk_usage = 0; 9138: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB 9139: if ($context eq 'author') { 9140: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname"; 9141: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace); 9142: } else { 9143: foreach my $subdir ('docs','supplemental') { 9144: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1); 9145: } 9146: } 9147: $disk_quota = int($disk_quota * 1000); 9148: if (($current_disk_usage + $filesize) > $disk_quota) { 9149: return '<p class="LC_warning">'. 9150: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.", 9151: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'. 9152: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.', 9153: $disk_quota,$current_disk_usage). 9154: '</p>'; 9155: } 9156: return; 9157: } 9158: 9159: ############################################### 9160: 9161: 9162: sub get_secgrprole_info { 9163: my ($cdom,$cnum,$needroles,$type) = @_; 9164: my %sections_count = &get_sections($cdom,$cnum); 9165: my @sections = (sort {$a <=> $b} keys(%sections_count)); 9166: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum); 9167: my @groups = sort(keys(%curr_groups)); 9168: my $allroles = []; 9169: my $rolehash; 9170: my $accesshash = { 9171: active => 'Currently has access', 9172: future => 'Will have future access', 9173: previous => 'Previously had access', 9174: }; 9175: if ($needroles) { 9176: $rolehash = {'all' => 'all'}; 9177: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum); 9178: if (&Apache::lonnet::error(%user_roles)) { 9179: undef(%user_roles); 9180: } 9181: foreach my $item (keys(%user_roles)) { 9182: my ($role)=split(/\:/,$item,2); 9183: if ($role eq 'cr') { next; } 9184: if ($role =~ /^cr/) { 9185: $$rolehash{$role} = (split('/',$role))[3]; 9186: } else { 9187: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type); 9188: } 9189: } 9190: foreach my $key (sort(keys(%{$rolehash}))) { 9191: push(@{$allroles},$key); 9192: } 9193: push (@{$allroles},'st'); 9194: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type); 9195: } 9196: return (\@sections,\@groups,$allroles,$rolehash,$accesshash); 9197: } 9198: 9199: sub user_picker { 9200: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_; 9201: my $currdom = $dom; 9202: my %curr_selected = ( 9203: srchin => 'dom', 9204: srchby => 'lastname', 9205: ); 9206: my $srchterm; 9207: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) { 9208: if ($srch->{'srchby'} ne '') { 9209: $curr_selected{'srchby'} = $srch->{'srchby'}; 9210: } 9211: if ($srch->{'srchin'} ne '') { 9212: $curr_selected{'srchin'} = $srch->{'srchin'}; 9213: } 9214: if ($srch->{'srchtype'} ne '') { 9215: $curr_selected{'srchtype'} = $srch->{'srchtype'}; 9216: } 9217: if ($srch->{'srchdomain'} ne '') { 9218: $currdom = $srch->{'srchdomain'}; 9219: } 9220: $srchterm = $srch->{'srchterm'}; 9221: } 9222: my %lt=&Apache::lonlocal::texthash( 9223: 'usr' => 'Search criteria', 9224: 'doma' => 'Domain/institution to search', 9225: 'uname' => 'username', 9226: 'lastname' => 'last name', 9227: 'lastfirst' => 'last name, first name', 9228: 'crs' => 'in this course', 9229: 'dom' => 'in selected LON-CAPA domain', 9230: 'alc' => 'all LON-CAPA', 9231: 'instd' => 'in institutional directory for selected domain', 9232: 'exact' => 'is', 9233: 'contains' => 'contains', 9234: 'begins' => 'begins with', 9235: 'youm' => "You must include some text to search for.", 9236: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.", 9237: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.", 9238: 'yomc' => "You must choose a domain when using an institutional directory search.", 9239: 'ymcd' => "You must choose a domain when using a domain search.", 9240: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.", 9241: 'whse' => "When searching by last,first you must include at least one character in the first name.", 9242: 'thfo' => "The following need to be corrected before the search can be run:", 9243: ); 9244: my $domform = &select_dom_form($currdom,'srchdomain',1,1); 9245: my $srchinsel = ' <select name="srchin">'; 9246: 9247: my @srchins = ('crs','dom','alc','instd'); 9248: 9249: foreach my $option (@srchins) { 9250: # FIXME 'alc' option unavailable until 9251: # loncreateuser::print_user_query_page() 9252: # has been completed. 9253: next if ($option eq 'alc'); 9254: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs')); 9255: next if ($option eq 'crs' && !$env{'request.course.id'}); 9256: if ($curr_selected{'srchin'} eq $option) { 9257: $srchinsel .= ' 9258: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>'; 9259: } else { 9260: $srchinsel .= ' 9261: <option value="'.$option.'">'.$lt{$option}.'</option>'; 9262: } 9263: } 9264: $srchinsel .= "\n </select>\n"; 9265: 9266: my $srchbysel = ' <select name="srchby">'; 9267: foreach my $option ('lastname','lastfirst','uname') { 9268: if ($curr_selected{'srchby'} eq $option) { 9269: $srchbysel .= ' 9270: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>'; 9271: } else { 9272: $srchbysel .= ' 9273: <option value="'.$option.'">'.$lt{$option}.'</option>'; 9274: } 9275: } 9276: $srchbysel .= "\n </select>\n"; 9277: 9278: my $srchtypesel = ' <select name="srchtype">'; 9279: foreach my $option ('begins','contains','exact') { 9280: if ($curr_selected{'srchtype'} eq $option) { 9281: $srchtypesel .= ' 9282: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>'; 9283: } else { 9284: $srchtypesel .= ' 9285: <option value="'.$option.'">'.$lt{$option}.'</option>'; 9286: } 9287: } 9288: $srchtypesel .= "\n </select>\n"; 9289: 9290: my ($newuserscript,$new_user_create); 9291: my $context_dom = $env{'request.role.domain'}; 9292: if ($context eq 'requestcrs') { 9293: if ($env{'form.coursedom'} ne '') { 9294: $context_dom = $env{'form.coursedom'}; 9295: } 9296: } 9297: if ($forcenewuser) { 9298: if (ref($srch) eq 'HASH') { 9299: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) { 9300: if ($cancreate) { 9301: $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>'; 9302: } else { 9303: my $helplink = 'javascript:helpMenu('."'display'".')'; 9304: my %usertypetext = ( 9305: official => 'institutional', 9306: unofficial => 'non-institutional', 9307: ); 9308: $new_user_create = '<p class="LC_warning">' 9309: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.") 9310: .' ' 9311: .&mt('Please contact the [_1]helpdesk[_2] for assistance.' 9312: ,'<a href="'.$helplink.'">','</a>') 9313: .'</p><br />'; 9314: } 9315: } 9316: } 9317: 9318: $newuserscript = <<"ENDSCRIPT"; 9319: 9320: function setSearch(createnew,callingForm) { 9321: if (createnew == 1) { 9322: for (var i=0; i<callingForm.srchby.length; i++) { 9323: if (callingForm.srchby.options[i].value == 'uname') { 9324: callingForm.srchby.selectedIndex = i; 9325: } 9326: } 9327: for (var i=0; i<callingForm.srchin.length; i++) { 9328: if ( callingForm.srchin.options[i].value == 'dom') { 9329: callingForm.srchin.selectedIndex = i; 9330: } 9331: } 9332: for (var i=0; i<callingForm.srchtype.length; i++) { 9333: if (callingForm.srchtype.options[i].value == 'exact') { 9334: callingForm.srchtype.selectedIndex = i; 9335: } 9336: } 9337: for (var i=0; i<callingForm.srchdomain.length; i++) { 9338: if (callingForm.srchdomain.options[i].value == '$context_dom') { 9339: callingForm.srchdomain.selectedIndex = i; 9340: } 9341: } 9342: } 9343: } 9344: ENDSCRIPT 9345: 9346: } 9347: 9348: my $output = <<"END_BLOCK"; 9349: <script type="text/javascript"> 9350: // <![CDATA[ 9351: function validateEntry(callingForm) { 9352: 9353: var checkok = 1; 9354: var srchin; 9355: for (var i=0; i<callingForm.srchin.length; i++) { 9356: if ( callingForm.srchin[i].checked ) { 9357: srchin = callingForm.srchin[i].value; 9358: } 9359: } 9360: 9361: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value; 9362: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value; 9363: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value; 9364: var srchterm = callingForm.srchterm.value; 9365: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value; 9366: var msg = ""; 9367: 9368: if (srchterm == "") { 9369: checkok = 0; 9370: msg += "$lt{'youm'}\\n"; 9371: } 9372: 9373: if (srchtype== 'begins') { 9374: if (srchterm.length < 2) { 9375: checkok = 0; 9376: msg += "$lt{'thte'}\\n"; 9377: } 9378: } 9379: 9380: if (srchtype== 'contains') { 9381: if (srchterm.length < 3) { 9382: checkok = 0; 9383: msg += "$lt{'thet'}\\n"; 9384: } 9385: } 9386: if (srchin == 'instd') { 9387: if (srchdomain == '') { 9388: checkok = 0; 9389: msg += "$lt{'yomc'}\\n"; 9390: } 9391: } 9392: if (srchin == 'dom') { 9393: if (srchdomain == '') { 9394: checkok = 0; 9395: msg += "$lt{'ymcd'}\\n"; 9396: } 9397: } 9398: if (srchby == 'lastfirst') { 9399: if (srchterm.indexOf(",") == -1) { 9400: checkok = 0; 9401: msg += "$lt{'whus'}\\n"; 9402: } 9403: if (srchterm.indexOf(",") == srchterm.length -1) { 9404: checkok = 0; 9405: msg += "$lt{'whse'}\\n"; 9406: } 9407: } 9408: if (checkok == 0) { 9409: alert("$lt{'thfo'}\\n"+msg); 9410: return; 9411: } 9412: if (checkok == 1) { 9413: callingForm.submit(); 9414: } 9415: } 9416: 9417: $newuserscript 9418: 9419: // ]]> 9420: </script> 9421: 9422: $new_user_create 9423: 9424: END_BLOCK 9425: 9426: $output .= &Apache::lonhtmlcommon::start_pick_box(). 9427: &Apache::lonhtmlcommon::row_title($lt{'doma'}). 9428: $domform. 9429: &Apache::lonhtmlcommon::row_closure(). 9430: &Apache::lonhtmlcommon::row_title($lt{'usr'}). 9431: $srchbysel. 9432: $srchtypesel. 9433: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'. 9434: $srchinsel. 9435: &Apache::lonhtmlcommon::row_closure(1). 9436: &Apache::lonhtmlcommon::end_pick_box(). 9437: '<br />'; 9438: return $output; 9439: } 9440: 9441: sub user_rule_check { 9442: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_; 9443: my $response; 9444: if (ref($usershash) eq 'HASH') { 9445: foreach my $user (keys(%{$usershash})) { 9446: my ($uname,$udom) = split(/:/,$user); 9447: next if ($udom eq '' || $uname eq ''); 9448: my ($id,$newuser); 9449: if (ref($usershash->{$user}) eq 'HASH') { 9450: $newuser = $usershash->{$user}->{'newuser'}; 9451: $id = $usershash->{$user}->{'id'}; 9452: } 9453: my $inst_response; 9454: if (ref($checks) eq 'HASH') { 9455: if (defined($checks->{'username'})) { 9456: ($inst_response,%{$inst_results->{$user}}) = 9457: &Apache::lonnet::get_instuser($udom,$uname); 9458: } elsif (defined($checks->{'id'})) { 9459: ($inst_response,%{$inst_results->{$user}}) = 9460: &Apache::lonnet::get_instuser($udom,undef,$id); 9461: } 9462: } else { 9463: ($inst_response,%{$inst_results->{$user}}) = 9464: &Apache::lonnet::get_instuser($udom,$uname); 9465: return; 9466: } 9467: if (!$got_rules->{$udom}) { 9468: my %domconfig = &Apache::lonnet::get_dom('configuration', 9469: ['usercreation'],$udom); 9470: if (ref($domconfig{'usercreation'}) eq 'HASH') { 9471: foreach my $item ('username','id') { 9472: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') { 9473: $$curr_rules{$udom}{$item} = 9474: $domconfig{'usercreation'}{$item.'_rule'}; 9475: } 9476: } 9477: } 9478: $got_rules->{$udom} = 1; 9479: } 9480: foreach my $item (keys(%{$checks})) { 9481: if (ref($$curr_rules{$udom}) eq 'HASH') { 9482: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') { 9483: if (@{$$curr_rules{$udom}{$item}} > 0) { 9484: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item}); 9485: foreach my $rule (@{$$curr_rules{$udom}{$item}}) { 9486: if ($rule_check{$rule}) { 9487: $$rulematch{$user}{$item} = $rule; 9488: if ($inst_response eq 'ok') { 9489: if (ref($inst_results) eq 'HASH') { 9490: if (ref($inst_results->{$user}) eq 'HASH') { 9491: if (keys(%{$inst_results->{$user}}) == 0) { 9492: $$alerts{$item}{$udom}{$uname} = 1; 9493: } 9494: } 9495: } 9496: } 9497: last; 9498: } 9499: } 9500: } 9501: } 9502: } 9503: } 9504: } 9505: } 9506: return; 9507: } 9508: 9509: sub user_rule_formats { 9510: my ($domain,$domdesc,$curr_rules,$check) = @_; 9511: my %text = ( 9512: 'username' => 'Usernames', 9513: 'id' => 'IDs', 9514: ); 9515: my $output; 9516: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check); 9517: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) { 9518: if (@{$ruleorder} > 0) { 9519: $output = '<br />'. 9520: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:', 9521: '<span class="LC_cusr_emph">','</span>',$domdesc). 9522: ' <ul>'; 9523: foreach my $rule (@{$ruleorder}) { 9524: if (ref($curr_rules) eq 'ARRAY') { 9525: if (grep(/^\Q$rule\E$/,@{$curr_rules})) { 9526: if (ref($rules->{$rule}) eq 'HASH') { 9527: $output .= '<li>'.$rules->{$rule}{'name'}.': '. 9528: $rules->{$rule}{'desc'}.'</li>'; 9529: } 9530: } 9531: } 9532: } 9533: $output .= '</ul>'; 9534: } 9535: } 9536: return $output; 9537: } 9538: 9539: sub instrule_disallow_msg { 9540: my ($checkitem,$domdesc,$count,$mode) = @_; 9541: my $response; 9542: my %text = ( 9543: item => 'username', 9544: items => 'usernames', 9545: match => 'matches', 9546: do => 'does', 9547: action => 'a username', 9548: one => 'one', 9549: ); 9550: if ($count > 1) { 9551: $text{'item'} = 'usernames'; 9552: $text{'match'} ='match'; 9553: $text{'do'} = 'do'; 9554: $text{'action'} = 'usernames', 9555: $text{'one'} = 'ones'; 9556: } 9557: if ($checkitem eq 'id') { 9558: $text{'items'} = 'IDs'; 9559: $text{'item'} = 'ID'; 9560: $text{'action'} = 'an ID'; 9561: if ($count > 1) { 9562: $text{'item'} = 'IDs'; 9563: $text{'action'} = 'IDs'; 9564: } 9565: } 9566: $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 />'; 9567: if ($mode eq 'upload') { 9568: if ($checkitem eq 'username') { 9569: $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'}."); 9570: } elsif ($checkitem eq 'id') { 9571: $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."); 9572: } 9573: } elsif ($mode eq 'selfcreate') { 9574: if ($checkitem eq 'id') { 9575: $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."); 9576: } 9577: } else { 9578: if ($checkitem eq 'username') { 9579: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}."); 9580: } elsif ($checkitem eq 'id') { 9581: $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."); 9582: } 9583: } 9584: return $response; 9585: } 9586: 9587: sub personal_data_fieldtitles { 9588: my %fieldtitles = &Apache::lonlocal::texthash ( 9589: id => 'Student/Employee ID', 9590: permanentemail => 'E-mail address', 9591: lastname => 'Last Name', 9592: firstname => 'First Name', 9593: middlename => 'Middle Name', 9594: generation => 'Generation', 9595: gen => 'Generation', 9596: inststatus => 'Affiliation', 9597: ); 9598: return %fieldtitles; 9599: } 9600: 9601: sub sorted_inst_types { 9602: my ($dom) = @_; 9603: my ($usertypes,$order); 9604: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom); 9605: if (ref($domdefaults{'inststatus'}) eq 'HASH') { 9606: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'}; 9607: $order = $domdefaults{'inststatus'}{'inststatusorder'}; 9608: } else { 9609: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom); 9610: } 9611: my $othertitle = &mt('All users'); 9612: if ($env{'request.course.id'}) { 9613: $othertitle = &mt('Any users'); 9614: } 9615: my @types; 9616: if (ref($order) eq 'ARRAY') { 9617: @types = @{$order}; 9618: } 9619: if (@types == 0) { 9620: if (ref($usertypes) eq 'HASH') { 9621: @types = sort(keys(%{$usertypes})); 9622: } 9623: } 9624: if (keys(%{$usertypes}) > 0) { 9625: $othertitle = &mt('Other users'); 9626: } 9627: return ($othertitle,$usertypes,\@types); 9628: } 9629: 9630: sub get_institutional_codes { 9631: my ($settings,$allcourses,$LC_code) = @_; 9632: # Get complete list of course sections to update 9633: my @currsections = (); 9634: my @currxlists = (); 9635: my $coursecode = $$settings{'internal.coursecode'}; 9636: 9637: if ($$settings{'internal.sectionnums'} ne '') { 9638: @currsections = split(/,/,$$settings{'internal.sectionnums'}); 9639: } 9640: 9641: if ($$settings{'internal.crosslistings'} ne '') { 9642: @currxlists = split(/,/,$$settings{'internal.crosslistings'}); 9643: } 9644: 9645: if (@currxlists > 0) { 9646: foreach (@currxlists) { 9647: if (m/^([^:]+):(\w*)$/) { 9648: unless (grep/^$1$/,@{$allcourses}) { 9649: push @{$allcourses},$1; 9650: $$LC_code{$1} = $2; 9651: } 9652: } 9653: } 9654: } 9655: 9656: if (@currsections > 0) { 9657: foreach (@currsections) { 9658: if (m/^(\w+):(\w*)$/) { 9659: my $sec = $coursecode.$1; 9660: my $lc_sec = $2; 9661: unless (grep/^$sec$/,@{$allcourses}) { 9662: push @{$allcourses},$sec; 9663: $$LC_code{$sec} = $lc_sec; 9664: } 9665: } 9666: } 9667: } 9668: return; 9669: } 9670: 9671: sub get_standard_codeitems { 9672: return ('Year','Semester','Department','Number','Section'); 9673: } 9674: 9675: =pod 9676: 9677: =head1 Slot Helpers 9678: 9679: =over 4 9680: 9681: =item * sorted_slots() 9682: 9683: Sorts an array of slot names in order of an optional sort key, 9684: default sort is by slot start time (earliest first). 9685: 9686: Inputs: 9687: 9688: =over 4 9689: 9690: slotsarr - Reference to array of unsorted slot names. 9691: 9692: slots - Reference to hash of hash, where outer hash keys are slot names. 9693: 9694: sortkey - Name of key in inner hash to be sorted on (e.g., starttime). 9695: 9696: =back 9697: 9698: Returns: 9699: 9700: =over 4 9701: 9702: sorted - An array of slot names sorted by a specified sort key 9703: (default sort key is start time of the slot). 9704: 9705: =back 9706: 9707: =cut 9708: 9709: 9710: sub sorted_slots { 9711: my ($slotsarr,$slots,$sortkey) = @_; 9712: if ($sortkey eq '') { 9713: $sortkey = 'starttime'; 9714: } 9715: my @sorted; 9716: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) { 9717: @sorted = 9718: sort { 9719: if (ref($slots->{$a}) && ref($slots->{$b})) { 9720: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey} 9721: } 9722: if (ref($slots->{$a})) { return -1;} 9723: if (ref($slots->{$b})) { return 1;} 9724: return 0; 9725: } @{$slotsarr}; 9726: } 9727: return @sorted; 9728: } 9729: 9730: =pod 9731: 9732: =item * get_future_slots() 9733: 9734: Inputs: 9735: 9736: =over 4 9737: 9738: cnum - course number 9739: 9740: cdom - course domain 9741: 9742: now - current UNIX time 9743: 9744: symb - optional symb 9745: 9746: =back 9747: 9748: Returns: 9749: 9750: =over 4 9751: 9752: sorted_reservable - ref to array of student_schedulable slots currently 9753: reservable, ordered by end date of reservation period. 9754: 9755: reservable_now - ref to hash of student_schedulable slots currently 9756: reservable. 9757: 9758: Keys in inner hash are: 9759: (a) symb: either blank or symb to which slot use is restricted. 9760: (b) endreserve: end date of reservation period. 9761: 9762: sorted_future - ref to array of student_schedulable slots reservable in 9763: the future, ordered by start date of reservation period. 9764: 9765: future_reservable - ref to hash of student_schedulable slots reservable 9766: in the future. 9767: 9768: Keys in inner hash are: 9769: (a) symb: either blank or symb to which slot use is restricted. 9770: (b) startreserve: start date of reservation period. 9771: 9772: =back 9773: 9774: =cut 9775: 9776: sub get_future_slots { 9777: my ($cnum,$cdom,$now,$symb) = @_; 9778: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future); 9779: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom); 9780: foreach my $slot (keys(%slots)) { 9781: next unless($slots{$slot}->{'type'} eq 'schedulable_student'); 9782: if ($symb) { 9783: next if (($slots{$slot}->{'symb'} ne '') && 9784: ($slots{$slot}->{'symb'} ne $symb)); 9785: } 9786: if (($slots{$slot}->{'starttime'} > $now) && 9787: ($slots{$slot}->{'endtime'} > $now)) { 9788: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) { 9789: my $userallowed = 0; 9790: if ($slots{$slot}->{'allowedsections'}) { 9791: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'}); 9792: if (!defined($env{'request.role.sec'}) 9793: && grep(/^No section assigned$/,@allowed_sec)) { 9794: $userallowed=1; 9795: } else { 9796: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) { 9797: $userallowed=1; 9798: } 9799: } 9800: unless ($userallowed) { 9801: if (defined($env{'request.course.groups'})) { 9802: my @groups = split(/:/,$env{'request.course.groups'}); 9803: foreach my $group (@groups) { 9804: if (grep(/^\Q$group\E$/,@allowed_sec)) { 9805: $userallowed=1; 9806: last; 9807: } 9808: } 9809: } 9810: } 9811: } 9812: if ($slots{$slot}->{'allowedusers'}) { 9813: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'}); 9814: my $user = $env{'user.name'}.':'.$env{'user.domain'}; 9815: if (grep(/^\Q$user\E$/,@allowed_users)) { 9816: $userallowed = 1; 9817: } 9818: } 9819: next unless($userallowed); 9820: } 9821: my $startreserve = $slots{$slot}->{'startreserve'}; 9822: my $endreserve = $slots{$slot}->{'endreserve'}; 9823: my $symb = $slots{$slot}->{'symb'}; 9824: if (($startreserve < $now) && 9825: (!$endreserve || $endreserve > $now)) { 9826: my $lastres = $endreserve; 9827: if (!$lastres) { 9828: $lastres = $slots{$slot}->{'starttime'}; 9829: } 9830: $reservable_now{$slot} = { 9831: symb => $symb, 9832: endreserve => $lastres 9833: }; 9834: } elsif (($startreserve > $now) && 9835: (!$endreserve || $endreserve > $startreserve)) { 9836: $future_reservable{$slot} = { 9837: symb => $symb, 9838: startreserve => $startreserve 9839: }; 9840: } 9841: } 9842: } 9843: my @unsorted_reservable = keys(%reservable_now); 9844: if (@unsorted_reservable > 0) { 9845: @sorted_reservable = 9846: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve'); 9847: } 9848: my @unsorted_future = keys(%future_reservable); 9849: if (@unsorted_future > 0) { 9850: @sorted_future = 9851: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve'); 9852: } 9853: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable); 9854: } 9855: 9856: =pod 9857: 9858: =back 9859: 9860: =head1 HTTP Helpers 9861: 9862: =over 4 9863: 9864: =item * &get_unprocessed_cgi($query,$possible_names) 9865: 9866: Modify the %env hash to contain unprocessed CGI form parameters held in 9867: $query. The parameters listed in $possible_names (an array reference), 9868: will be set in $env{'form.name'} if they do not already exist. 9869: 9870: Typically called with $ENV{'QUERY_STRING'} as the first parameter. 9871: $possible_names is an ref to an array of form element names. As an example: 9872: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']); 9873: will result in $env{'form.uname'} and $env{'form.udom'} being set. 9874: 9875: =cut 9876: 9877: sub get_unprocessed_cgi { 9878: my ($query,$possible_names)= @_; 9879: # $Apache::lonxml::debug=1; 9880: foreach my $pair (split(/&/,$query)) { 9881: my ($name, $value) = split(/=/,$pair); 9882: $name = &unescape($name); 9883: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) { 9884: $value =~ tr/+/ /; 9885: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg; 9886: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) }; 9887: } 9888: } 9889: } 9890: 9891: =pod 9892: 9893: =item * &cacheheader() 9894: 9895: returns cache-controlling header code 9896: 9897: =cut 9898: 9899: sub cacheheader { 9900: unless ($env{'request.method'} eq 'GET') { return ''; } 9901: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime); 9902: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" /> 9903: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" /> 9904: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />'; 9905: return $output; 9906: } 9907: 9908: =pod 9909: 9910: =item * &no_cache($r) 9911: 9912: specifies header code to not have cache 9913: 9914: =cut 9915: 9916: sub no_cache { 9917: my ($r) = @_; 9918: if ($ENV{'REQUEST_METHOD'} ne 'GET' && 9919: $env{'request.method'} ne 'GET') { return ''; } 9920: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time)); 9921: $r->no_cache(1); 9922: $r->header_out("Expires" => $date); 9923: $r->header_out("Pragma" => "no-cache"); 9924: } 9925: 9926: sub content_type { 9927: my ($r,$type,$charset) = @_; 9928: if ($r) { 9929: # Note that printout.pl calls this with undef for $r. 9930: &no_cache($r); 9931: } 9932: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; } 9933: unless ($charset) { 9934: $charset=&Apache::lonlocal::current_encoding; 9935: } 9936: if ($charset) { $type.='; charset='.$charset; } 9937: if ($r) { 9938: $r->content_type($type); 9939: } else { 9940: print("Content-type: $type\n\n"); 9941: } 9942: } 9943: 9944: =pod 9945: 9946: =item * &add_to_env($name,$value) 9947: 9948: adds $name to the %env hash with value 9949: $value, if $name already exists, the entry is converted to an array 9950: reference and $value is added to the array. 9951: 9952: =cut 9953: 9954: sub add_to_env { 9955: my ($name,$value)=@_; 9956: if (defined($env{$name})) { 9957: if (ref($env{$name})) { 9958: #already have multiple values 9959: push(@{ $env{$name} },$value); 9960: } else { 9961: #first time seeing multiple values, convert hash entry to an arrayref 9962: my $first=$env{$name}; 9963: undef($env{$name}); 9964: push(@{ $env{$name} },$first,$value); 9965: } 9966: } else { 9967: $env{$name}=$value; 9968: } 9969: } 9970: 9971: =pod 9972: 9973: =item * &get_env_multiple($name) 9974: 9975: gets $name from the %env hash, it seemlessly handles the cases where multiple 9976: values may be defined and end up as an array ref. 9977: 9978: returns an array of values 9979: 9980: =cut 9981: 9982: sub get_env_multiple { 9983: my ($name) = @_; 9984: my @values; 9985: if (defined($env{$name})) { 9986: # exists is it an array 9987: if (ref($env{$name})) { 9988: @values=@{ $env{$name} }; 9989: } else { 9990: $values[0]=$env{$name}; 9991: } 9992: } 9993: return(@values); 9994: } 9995: 9996: sub ask_for_embedded_content { 9997: my ($actionurl,$state,$allfiles,$codebase,$args)=@_; 9998: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges, 9999: %currsubfile,%unused,$rem); 10000: my $counter = 0; 10001: my $numnew = 0; 10002: my $numremref = 0; 10003: my $numinvalid = 0; 10004: my $numpathchg = 0; 10005: my $numexisting = 0; 10006: my $numunused = 0; 10007: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum, 10008: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap); 10009: my $heading = &mt('Upload embedded files'); 10010: my $buttontext = &mt('Upload'); 10011: 10012: if ($env{'request.course.id'}) { 10013: if ($actionurl eq '/adm/dependencies') { 10014: $navmap = Apache::lonnavmaps::navmap->new(); 10015: } 10016: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; 10017: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; 10018: } 10019: if (($actionurl eq '/adm/portfolio') || 10020: ($actionurl eq '/adm/coursegrp_portfolio')) { 10021: my $current_path='/'; 10022: if ($env{'form.currentpath'}) { 10023: $current_path = $env{'form.currentpath'}; 10024: } 10025: if ($actionurl eq '/adm/coursegrp_portfolio') { 10026: $udom = $cdom; 10027: $uname = $cnum; 10028: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio'; 10029: } else { 10030: $udom = $env{'user.domain'}; 10031: $uname = $env{'user.name'}; 10032: $url = '/userfiles/portfolio'; 10033: } 10034: $toplevel = $url.'/'; 10035: $url .= $current_path; 10036: $getpropath = 1; 10037: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 10038: ($actionurl eq '/adm/imsimport')) { 10039: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$}); 10040: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/"; 10041: $toplevel = $url; 10042: if ($rest ne '') { 10043: $url .= $rest; 10044: } 10045: } elsif ($actionurl eq '/adm/coursedocs') { 10046: if (ref($args) eq 'HASH') { 10047: $url = $args->{'docs_url'}; 10048: $toplevel = $url; 10049: if ($args->{'context'} eq 'paste') { 10050: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/}); 10051: ($path) = 10052: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/}); 10053: $fileloc = &Apache::lonnet::filelocation('',$toplevel); 10054: $fileloc =~ s{^/}{}; 10055: } 10056: } 10057: } elsif ($actionurl eq '/adm/dependencies') { 10058: if ($env{'request.course.id'} ne '') { 10059: if (ref($args) eq 'HASH') { 10060: $url = $args->{'docs_url'}; 10061: $title = $args->{'docs_title'}; 10062: $toplevel = $url; 10063: unless ($toplevel =~ m{^/}) { 10064: $toplevel = "/$url"; 10065: } 10066: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$}); 10067: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) { 10068: $path = $1; 10069: } else { 10070: ($path) = 10071: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/}); 10072: } 10073: if ($toplevel=~/^\/*(uploaded|editupload)/) { 10074: $fileloc = $toplevel; 10075: $fileloc=~ s/^\s*(\S+)\s*$/$1/; 10076: my ($udom,$uname,$fname) = 10077: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$}); 10078: $fileloc = propath($udom,$uname).'/userfiles/'.$fname; 10079: } else { 10080: $fileloc = &Apache::lonnet::filelocation('',$toplevel); 10081: } 10082: $fileloc =~ s{^/}{}; 10083: ($filename) = ($fileloc =~ m{.+/([^/]+)$}); 10084: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)"); 10085: } 10086: } 10087: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") { 10088: $udom = $cdom; 10089: $uname = $cnum; 10090: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus"; 10091: $toplevel = $url; 10092: $path = $url; 10093: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/'; 10094: $fileloc =~ s{^/}{}; 10095: } 10096: foreach my $file (keys(%{$allfiles})) { 10097: my $embed_file; 10098: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) { 10099: $embed_file = $1; 10100: } else { 10101: $embed_file = $file; 10102: } 10103: my ($absolutepath,$cleaned_file); 10104: if ($embed_file =~ m{^\w+://}) { 10105: $cleaned_file = $embed_file; 10106: $newfiles{$cleaned_file} = 1; 10107: $mapping{$cleaned_file} = $embed_file; 10108: } else { 10109: $cleaned_file = &clean_path($embed_file); 10110: if ($embed_file =~ m{^/}) { 10111: $absolutepath = $embed_file; 10112: } 10113: if ($cleaned_file =~ m{/}) { 10114: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$}); 10115: $path = &check_for_traversal($path,$url,$toplevel); 10116: my $item = $fname; 10117: if ($path ne '') { 10118: $item = $path.'/'.$fname; 10119: $subdependencies{$path}{$fname} = 1; 10120: } else { 10121: $dependencies{$item} = 1; 10122: } 10123: if ($absolutepath) { 10124: $mapping{$item} = $absolutepath; 10125: } else { 10126: $mapping{$item} = $embed_file; 10127: } 10128: } else { 10129: $dependencies{$embed_file} = 1; 10130: if ($absolutepath) { 10131: $mapping{$cleaned_file} = $absolutepath; 10132: } else { 10133: $mapping{$cleaned_file} = $embed_file; 10134: } 10135: } 10136: } 10137: } 10138: my $dirptr = 16384; 10139: foreach my $path (keys(%subdependencies)) { 10140: $currsubfile{$path} = {}; 10141: if (($actionurl eq '/adm/portfolio') || 10142: ($actionurl eq '/adm/coursegrp_portfolio')) { 10143: my ($sublistref,$listerror) = 10144: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath); 10145: if (ref($sublistref) eq 'ARRAY') { 10146: foreach my $line (@{$sublistref}) { 10147: my ($file_name,$rest) = split(/\&/,$line,2); 10148: $currsubfile{$path}{$file_name} = 1; 10149: } 10150: } 10151: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) { 10152: if (opendir(my $dir,$url.'/'.$path)) { 10153: my @subdir_list = grep(!/^\./,readdir($dir)); 10154: map {$currsubfile{$path}{$_} = 1;} @subdir_list; 10155: } 10156: } elsif (($actionurl eq '/adm/dependencies') || 10157: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && 10158: ($args->{'context'} eq 'paste')) || 10159: ($actionurl eq "/public/$cdom/$cnum/syllabus")) { 10160: if ($env{'request.course.id'} ne '') { 10161: my $dir; 10162: if ($actionurl eq "/public/$cdom/$cnum/syllabus") { 10163: $dir = $fileloc; 10164: } else { 10165: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$}); 10166: } 10167: if ($dir ne '') { 10168: my ($sublistref,$listerror) = 10169: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/'); 10170: if (ref($sublistref) eq 'ARRAY') { 10171: foreach my $line (@{$sublistref}) { 10172: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size, 10173: undef,$mtime)=split(/\&/,$line,12); 10174: unless (($testdir&$dirptr) || 10175: ($file_name =~ /^\.\.?$/)) { 10176: $currsubfile{$path}{$file_name} = [$size,$mtime]; 10177: } 10178: } 10179: } 10180: } 10181: } 10182: } 10183: foreach my $file (keys(%{$subdependencies{$path}})) { 10184: if (exists($currsubfile{$path}{$file})) { 10185: my $item = $path.'/'.$file; 10186: unless ($mapping{$item} eq $item) { 10187: $pathchanges{$item} = 1; 10188: } 10189: $existing{$item} = 1; 10190: $numexisting ++; 10191: } else { 10192: $newfiles{$path.'/'.$file} = 1; 10193: } 10194: } 10195: if ($actionurl eq '/adm/dependencies') { 10196: foreach my $path (keys(%currsubfile)) { 10197: if (ref($currsubfile{$path}) eq 'HASH') { 10198: foreach my $file (keys(%{$currsubfile{$path}})) { 10199: unless ($subdependencies{$path}{$file}) { 10200: next if (($rem ne '') && 10201: (($env{"httpref.$rem"."$path/$file"} ne '') || 10202: (ref($navmap) && 10203: (($navmap->getResourceByUrl($rem."$path/$file") ne '') || 10204: (($file =~ /^(.*\.s?html?)\.bak$/i) && 10205: ($navmap->getResourceByUrl($rem."$path/$1"))))))); 10206: $unused{$path.'/'.$file} = 1; 10207: } 10208: } 10209: } 10210: } 10211: } 10212: } 10213: my %currfile; 10214: if (($actionurl eq '/adm/portfolio') || 10215: ($actionurl eq '/adm/coursegrp_portfolio')) { 10216: my ($dirlistref,$listerror) = 10217: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath); 10218: if (ref($dirlistref) eq 'ARRAY') { 10219: foreach my $line (@{$dirlistref}) { 10220: my ($file_name,$rest) = split(/\&/,$line,2); 10221: $currfile{$file_name} = 1; 10222: } 10223: } 10224: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) { 10225: if (opendir(my $dir,$url)) { 10226: my @dir_list = grep(!/^\./,readdir($dir)); 10227: map {$currfile{$_} = 1;} @dir_list; 10228: } 10229: } elsif (($actionurl eq '/adm/dependencies') || 10230: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && 10231: ($args->{'context'} eq 'paste')) || 10232: ($actionurl eq "/public/$cdom/$cnum/syllabus")) { 10233: if ($env{'request.course.id'} ne '') { 10234: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$}); 10235: if ($dir ne '') { 10236: my ($dirlistref,$listerror) = 10237: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/'); 10238: if (ref($dirlistref) eq 'ARRAY') { 10239: foreach my $line (@{$dirlistref}) { 10240: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef, 10241: $size,undef,$mtime)=split(/\&/,$line,12); 10242: unless (($testdir&$dirptr) || 10243: ($file_name =~ /^\.\.?$/)) { 10244: $currfile{$file_name} = [$size,$mtime]; 10245: } 10246: } 10247: } 10248: } 10249: } 10250: } 10251: foreach my $file (keys(%dependencies)) { 10252: if (exists($currfile{$file})) { 10253: unless ($mapping{$file} eq $file) { 10254: $pathchanges{$file} = 1; 10255: } 10256: $existing{$file} = 1; 10257: $numexisting ++; 10258: } else { 10259: $newfiles{$file} = 1; 10260: } 10261: } 10262: foreach my $file (keys(%currfile)) { 10263: unless (($file eq $filename) || 10264: ($file eq $filename.'.bak') || 10265: ($dependencies{$file})) { 10266: if ($actionurl eq '/adm/dependencies') { 10267: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) { 10268: next if (($rem ne '') && 10269: (($env{"httpref.$rem".$file} ne '') || 10270: (ref($navmap) && 10271: (($navmap->getResourceByUrl($rem.$file) ne '') || 10272: (($file =~ /^(.*\.s?html?)\.bak$/i) && 10273: ($navmap->getResourceByUrl($rem.$1))))))); 10274: } 10275: } 10276: $unused{$file} = 1; 10277: } 10278: } 10279: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && 10280: ($args->{'context'} eq 'paste')) { 10281: $counter = scalar(keys(%existing)); 10282: $numpathchg = scalar(keys(%pathchanges)); 10283: return ($output,$counter,$numpathchg,\%existing); 10284: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 10285: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) { 10286: $counter = scalar(keys(%existing)); 10287: $numpathchg = scalar(keys(%pathchanges)); 10288: return ($output,$counter,$numpathchg,\%existing,\%mapping); 10289: } 10290: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) { 10291: if ($actionurl eq '/adm/dependencies') { 10292: next if ($embed_file =~ m{^\w+://}); 10293: } 10294: $upload_output .= &start_data_table_row(). 10295: '<td valign="top"><img src="'.&icon($embed_file).'" /> '. 10296: '<span class="LC_filename">'.$embed_file.'</span>'; 10297: unless ($mapping{$embed_file} eq $embed_file) { 10298: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'. 10299: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>'; 10300: } 10301: $upload_output .= '</td>'; 10302: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 10303: $upload_output.='<td align="right">'. 10304: '<span class="LC_info LC_fontsize_medium">'. 10305: &mt("URL points to web address").'</span>'; 10306: $numremref++; 10307: } elsif ($args->{'error_on_invalid_names'} 10308: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) { 10309: $upload_output.='<td align="right"><span class="LC_warning">'. 10310: &mt('Invalid characters').'</span>'; 10311: $numinvalid++; 10312: } else { 10313: $upload_output .= '<td>'. 10314: &embedded_file_element('upload_embedded',$counter, 10315: $embed_file,\%mapping, 10316: $allfiles,$codebase,'upload'); 10317: $counter ++; 10318: $numnew ++; 10319: } 10320: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n"; 10321: } 10322: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) { 10323: if ($actionurl eq '/adm/dependencies') { 10324: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file); 10325: $modify_output .= &start_data_table_row(). 10326: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'. 10327: '<img src="'.&icon($embed_file).'" border="0" />'. 10328: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'. 10329: '<td>'.$size.'</td>'. 10330: '<td>'.$mtime.'</td>'. 10331: '<td><label><input type="checkbox" name="mod_upload_dep" '. 10332: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'. 10333: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'. 10334: '<div id="moduploaddep_'.$counter.'" style="display:none;">'. 10335: &embedded_file_element('upload_embedded',$counter, 10336: $embed_file,\%mapping, 10337: $allfiles,$codebase,'modify'). 10338: '</div></td>'. 10339: &end_data_table_row()."\n"; 10340: $counter ++; 10341: } else { 10342: $upload_output .= &start_data_table_row(). 10343: '<td valign="top"><img src="'.&icon($embed_file).'" /> '. 10344: '<span class="LC_filename">'.$embed_file.'</span></td>'. 10345: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'. 10346: &Apache::loncommon::end_data_table_row()."\n"; 10347: } 10348: } 10349: my $delidx = $counter; 10350: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) { 10351: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile); 10352: $delete_output .= &start_data_table_row(). 10353: '<td><img src="'.&icon($oldfile).'" />'. 10354: ' <span class="LC_filename">'.$oldfile.'</span></td>'. 10355: '<td>'.$size.'</td>'. 10356: '<td>'.$mtime.'</td>'. 10357: '<td><label><input type="checkbox" name="del_upload_dep" '. 10358: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'. 10359: &embedded_file_element('upload_embedded',$delidx, 10360: $oldfile,\%mapping,$allfiles, 10361: $codebase,'delete').'</td>'. 10362: &end_data_table_row()."\n"; 10363: $numunused ++; 10364: $delidx ++; 10365: } 10366: if ($upload_output) { 10367: $upload_output = &start_data_table(). 10368: $upload_output. 10369: &end_data_table()."\n"; 10370: } 10371: if ($modify_output) { 10372: $modify_output = &start_data_table(). 10373: &start_data_table_header_row(). 10374: '<th>'.&mt('File').'</th>'. 10375: '<th>'.&mt('Size (KB)').'</th>'. 10376: '<th>'.&mt('Modified').'</th>'. 10377: '<th>'.&mt('Upload replacement?').'</th>'. 10378: &end_data_table_header_row(). 10379: $modify_output. 10380: &end_data_table()."\n"; 10381: } 10382: if ($delete_output) { 10383: $delete_output = &start_data_table(). 10384: &start_data_table_header_row(). 10385: '<th>'.&mt('File').'</th>'. 10386: '<th>'.&mt('Size (KB)').'</th>'. 10387: '<th>'.&mt('Modified').'</th>'. 10388: '<th>'.&mt('Delete?').'</th>'. 10389: &end_data_table_header_row(). 10390: $delete_output. 10391: &end_data_table()."\n"; 10392: } 10393: my $applies = 0; 10394: if ($numremref) { 10395: $applies ++; 10396: } 10397: if ($numinvalid) { 10398: $applies ++; 10399: } 10400: if ($numexisting) { 10401: $applies ++; 10402: } 10403: if ($counter || $numunused) { 10404: $output = '<form name="upload_embedded" action="'.$actionurl.'"'. 10405: ' method="post" enctype="multipart/form-data">'."\n". 10406: $state.'<h3>'.$heading.'</h3>'; 10407: if ($actionurl eq '/adm/dependencies') { 10408: if ($numnew) { 10409: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'. 10410: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n". 10411: $upload_output.'<br />'."\n"; 10412: } 10413: if ($numexisting) { 10414: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'. 10415: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n". 10416: $modify_output.'<br />'."\n"; 10417: $buttontext = &mt('Save changes'); 10418: } 10419: if ($numunused) { 10420: $output .= '<h4>'.&mt('Unused files').'</h4>'. 10421: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n". 10422: $delete_output.'<br />'."\n"; 10423: $buttontext = &mt('Save changes'); 10424: } 10425: } else { 10426: $output .= $upload_output.'<br />'."\n"; 10427: } 10428: $output .= '<input type ="hidden" name="number_embedded_items" value="'. 10429: $counter.'" />'."\n"; 10430: if ($actionurl eq '/adm/dependencies') { 10431: $output .= '<input type ="hidden" name="number_newemb_items" value="'. 10432: $numnew.'" />'."\n"; 10433: } elsif ($actionurl eq '') { 10434: $output .= '<input type="hidden" name="phase" value="three" />'; 10435: } 10436: } elsif ($applies) { 10437: $output = '<b>'.&mt('Referenced files').'</b>:<br />'; 10438: if ($applies > 1) { 10439: $output .= 10440: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>'; 10441: if ($numremref) { 10442: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n"; 10443: } 10444: if ($numinvalid) { 10445: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n"; 10446: } 10447: if ($numexisting) { 10448: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n"; 10449: } 10450: $output .= '</ul><br />'; 10451: } elsif ($numremref) { 10452: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>'; 10453: } elsif ($numinvalid) { 10454: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>'; 10455: } elsif ($numexisting) { 10456: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>'; 10457: } 10458: $output .= $upload_output.'<br />'; 10459: } 10460: my ($pathchange_output,$chgcount); 10461: $chgcount = $counter; 10462: if (keys(%pathchanges) > 0) { 10463: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) { 10464: if ($counter) { 10465: $output .= &embedded_file_element('pathchange',$chgcount, 10466: $embed_file,\%mapping, 10467: $allfiles,$codebase,'change'); 10468: } else { 10469: $pathchange_output .= 10470: &start_data_table_row(). 10471: '<td><input type ="checkbox" name="namechange" value="'. 10472: $chgcount.'" checked="checked" /></td>'. 10473: '<td>'.$mapping{$embed_file}.'</td>'. 10474: '<td>'.$embed_file. 10475: &embedded_file_element('pathchange',$numpathchg,$embed_file, 10476: \%mapping,$allfiles,$codebase,'change'). 10477: '</td>'.&end_data_table_row(); 10478: } 10479: $numpathchg ++; 10480: $chgcount ++; 10481: } 10482: } 10483: if (($counter) || ($numunused)) { 10484: if ($numpathchg) { 10485: $output .= '<input type ="hidden" name="number_pathchange_items" value="'. 10486: $numpathchg.'" />'."\n"; 10487: } 10488: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 10489: ($actionurl eq '/adm/imsimport')) { 10490: $output .= '<input type="hidden" name="phase" value="three" />'."\n"; 10491: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') { 10492: $output .= '<input type="hidden" name="action" value="upload_embedded" />'; 10493: } elsif ($actionurl eq '/adm/dependencies') { 10494: $output .= '<input type="hidden" name="action" value="process_changes" />'; 10495: } 10496: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n"; 10497: } elsif ($numpathchg) { 10498: my %pathchange = (); 10499: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output); 10500: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 10501: $output .= '<p>'.&mt('or').'</p>'; 10502: } 10503: } 10504: return ($output,$counter,$numpathchg); 10505: } 10506: 10507: =pod 10508: 10509: =item * clean_path($name) 10510: 10511: Performs clean-up of directories, subdirectories and filename in an 10512: embedded object, referenced in an HTML file which is being uploaded 10513: to a course or portfolio, where 10514: "Upload embedded images/multimedia files if HTML file" checkbox was 10515: checked. 10516: 10517: Clean-up is similar to replacements in lonnet::clean_filename() 10518: except each / between sub-directory and next level is preserved. 10519: 10520: =cut 10521: 10522: sub clean_path { 10523: my ($embed_file) = @_; 10524: $embed_file =~s{^/+}{}; 10525: my @contents; 10526: if ($embed_file =~ m{/}) { 10527: @contents = split(/\//,$embed_file); 10528: } else { 10529: @contents = ($embed_file); 10530: } 10531: my $lastidx = scalar(@contents)-1; 10532: for (my $i=0; $i<=$lastidx; $i++) { 10533: $contents[$i]=~s{\\}{/}g; 10534: $contents[$i]=~s/\s+/\_/g; 10535: $contents[$i]=~s{[^/\w\.\-]}{}g; 10536: if ($i == $lastidx) { 10537: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g; 10538: } 10539: } 10540: if ($lastidx > 0) { 10541: return join('/',@contents); 10542: } else { 10543: return $contents[0]; 10544: } 10545: } 10546: 10547: sub embedded_file_element { 10548: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_; 10549: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') && 10550: (ref($codebase) eq 'HASH')); 10551: my $output; 10552: if (($context eq 'upload_embedded') && ($type ne 'delete')) { 10553: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n"; 10554: } 10555: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'. 10556: &escape($embed_file).'" />'; 10557: unless (($context eq 'upload_embedded') && 10558: ($mapping->{$embed_file} eq $embed_file)) { 10559: $output .=' 10560: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />'; 10561: } 10562: my $attrib; 10563: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') { 10564: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}})); 10565: } 10566: $output .= 10567: "\n\t\t". 10568: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'. 10569: $attrib.'" />'; 10570: if (exists($codebase->{$mapping->{$embed_file}})) { 10571: $output .= 10572: "\n\t\t". 10573: '<input name="codebase_'.$num.'" type="hidden" value="'. 10574: &escape($codebase->{$mapping->{$embed_file}}).'" />'; 10575: } 10576: return $output; 10577: } 10578: 10579: sub get_dependency_details { 10580: my ($currfile,$currsubfile,$embed_file) = @_; 10581: my ($size,$mtime,$showsize,$showmtime); 10582: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) { 10583: if ($embed_file =~ m{/}) { 10584: my ($path,$fname) = split(/\//,$embed_file); 10585: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') { 10586: ($size,$mtime) = @{$currsubfile->{$path}{$fname}}; 10587: } 10588: } else { 10589: if (ref($currfile->{$embed_file}) eq 'ARRAY') { 10590: ($size,$mtime) = @{$currfile->{$embed_file}}; 10591: } 10592: } 10593: $showsize = $size/1024.0; 10594: $showsize = sprintf("%.1f",$showsize); 10595: if ($mtime > 0) { 10596: $showmtime = &Apache::lonlocal::locallocaltime($mtime); 10597: } 10598: } 10599: return ($showsize,$showmtime); 10600: } 10601: 10602: sub ask_embedded_js { 10603: return <<"END"; 10604: <script type="text/javascript""> 10605: // <![CDATA[ 10606: function toggleBrowse(counter) { 10607: var chkboxid = document.getElementById('mod_upload_dep_'+counter); 10608: var fileid = document.getElementById('embedded_item_'+counter); 10609: var uploaddivid = document.getElementById('moduploaddep_'+counter); 10610: if (chkboxid.checked == true) { 10611: uploaddivid.style.display='block'; 10612: } else { 10613: uploaddivid.style.display='none'; 10614: fileid.value = ''; 10615: } 10616: } 10617: // ]]> 10618: </script> 10619: 10620: END 10621: } 10622: 10623: sub upload_embedded { 10624: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota, 10625: $current_disk_usage,$hiddenstate,$actionurl) = @_; 10626: my (%pathchange,$output,$modifyform,$footer,$returnflag); 10627: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) { 10628: next if (!exists($env{'form.embedded_item_'.$i.'.filename'})); 10629: my $orig_uploaded_filename = 10630: $env{'form.embedded_item_'.$i.'.filename'}; 10631: foreach my $type ('orig','ref','attrib','codebase') { 10632: if ($env{'form.embedded_'.$type.'_'.$i} ne '') { 10633: $env{'form.embedded_'.$type.'_'.$i} = 10634: &unescape($env{'form.embedded_'.$type.'_'.$i}); 10635: } 10636: } 10637: my ($path,$fname) = 10638: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)}); 10639: # no path, whole string is fname 10640: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} }; 10641: $fname = &Apache::lonnet::clean_filename($fname); 10642: # See if there is anything left 10643: next if ($fname eq ''); 10644: 10645: # Check if file already exists as a file or directory. 10646: my ($state,$msg); 10647: if ($context eq 'portfolio') { 10648: my $port_path = $dirpath; 10649: if ($group ne '') { 10650: $port_path = "groups/$group/$port_path"; 10651: } 10652: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path, 10653: $fname,$group,'embedded_item_'.$i, 10654: $dir_root,$port_path,$disk_quota, 10655: $current_disk_usage,$uname,$udom); 10656: if ($state eq 'will_exceed_quota' 10657: || $state eq 'file_locked') { 10658: $output .= $msg; 10659: next; 10660: } 10661: } elsif (($context eq 'author') || ($context eq 'testbank')) { 10662: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i); 10663: if ($state eq 'exists') { 10664: $output .= $msg; 10665: next; 10666: } 10667: } 10668: # Check if extension is valid 10669: if (($fname =~ /\.(\w+)$/) && 10670: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) { 10671: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1) 10672: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />'; 10673: next; 10674: } elsif (($fname =~ /\.(\w+)$/) && 10675: (!defined(&Apache::loncommon::fileembstyle($1)))) { 10676: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />'; 10677: next; 10678: } elsif ($fname=~/\.(\d+)\.(\w+)$/) { 10679: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />'; 10680: next; 10681: } 10682: $env{'form.embedded_item_'.$i.'.filename'}=$fname; 10683: my $subdir = $path; 10684: $subdir =~ s{/+$}{}; 10685: if ($context eq 'portfolio') { 10686: my $result; 10687: if ($state eq 'existingfile') { 10688: $result= 10689: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile', 10690: $dirpath.$env{'form.currentpath'}.$subdir); 10691: } else { 10692: $result= 10693: &Apache::lonnet::userfileupload('embedded_item_'.$i,'', 10694: $dirpath. 10695: $env{'form.currentpath'}.$subdir); 10696: if ($result !~ m|^/uploaded/|) { 10697: $output .= '<span class="LC_error">' 10698: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].' 10699: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}) 10700: .'</span><br />'; 10701: next; 10702: } else { 10703: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'. 10704: $path.$fname.'</span>').'<br />'; 10705: } 10706: } 10707: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) { 10708: my $extendedsubdir = $dirpath.'/'.$subdir; 10709: $extendedsubdir =~ s{/+$}{}; 10710: my $result = 10711: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir); 10712: if ($result !~ m|^/uploaded/|) { 10713: $output .= '<span class="LC_error">' 10714: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].' 10715: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}) 10716: .'</span><br />'; 10717: next; 10718: } else { 10719: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'. 10720: $path.$fname.'</span>').'<br />'; 10721: if ($context eq 'syllabus') { 10722: &Apache::lonnet::make_public_indefinitely($result); 10723: } 10724: } 10725: } else { 10726: # Save the file 10727: my $target = $env{'form.embedded_item_'.$i}; 10728: my $fullpath = $dir_root.$dirpath.'/'.$path; 10729: my $dest = $fullpath.$fname; 10730: my $url = $url_root.$dirpath.'/'.$path.$fname; 10731: my @parts=split(/\//,"$dirpath/$path"); 10732: my $count; 10733: my $filepath = $dir_root; 10734: foreach my $subdir (@parts) { 10735: $filepath .= "/$subdir"; 10736: if (!-e $filepath) { 10737: mkdir($filepath,0770); 10738: } 10739: } 10740: my $fh; 10741: if (!open($fh,'>'.$dest)) { 10742: &Apache::lonnet::logthis('Failed to create '.$dest); 10743: $output .= '<span class="LC_error">'. 10744: &mt('An error occurred while trying to upload [_1] for embedded element [_2].', 10745: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}). 10746: '</span><br />'; 10747: } else { 10748: if (!print $fh $env{'form.embedded_item_'.$i}) { 10749: &Apache::lonnet::logthis('Failed to write to '.$dest); 10750: $output .= '<span class="LC_error">'. 10751: &mt('An error occurred while writing the file [_1] for embedded element [_2].', 10752: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}). 10753: '</span><br />'; 10754: } else { 10755: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'. 10756: $url.'</span>').'<br />'; 10757: unless ($context eq 'testbank') { 10758: $footer .= &mt('View embedded file: [_1]', 10759: '<a href="'.$url.'">'.$fname.'</a>').'<br />'; 10760: } 10761: } 10762: close($fh); 10763: } 10764: } 10765: if ($env{'form.embedded_ref_'.$i}) { 10766: $pathchange{$i} = 1; 10767: } 10768: } 10769: if ($output) { 10770: $output = '<p>'.$output.'</p>'; 10771: } 10772: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange); 10773: $returnflag = 'ok'; 10774: my $numpathchgs = scalar(keys(%pathchange)); 10775: if ($numpathchgs > 0) { 10776: if ($context eq 'portfolio') { 10777: $output .= '<p>'.&mt('or').'</p>'; 10778: } elsif ($context eq 'testbank') { 10779: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).', 10780: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>'; 10781: $returnflag = 'modify_orightml'; 10782: } 10783: } 10784: return ($output.$footer,$returnflag,$numpathchgs); 10785: } 10786: 10787: sub modify_html_form { 10788: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_; 10789: my $end = 0; 10790: my $modifyform; 10791: if ($context eq 'upload_embedded') { 10792: return unless (ref($pathchange) eq 'HASH'); 10793: if ($env{'form.number_embedded_items'}) { 10794: $end += $env{'form.number_embedded_items'}; 10795: } 10796: if ($env{'form.number_pathchange_items'}) { 10797: $end += $env{'form.number_pathchange_items'}; 10798: } 10799: if ($end) { 10800: for (my $i=0; $i<$end; $i++) { 10801: if ($i < $env{'form.number_embedded_items'}) { 10802: next unless($pathchange->{$i}); 10803: } 10804: $modifyform .= 10805: &start_data_table_row(). 10806: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '. 10807: 'checked="checked" /></td>'. 10808: '<td>'.$env{'form.embedded_ref_'.$i}. 10809: '<input type="hidden" name="embedded_ref_'.$i.'" value="'. 10810: &escape($env{'form.embedded_ref_'.$i}).'" />'. 10811: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'. 10812: &escape($env{'form.embedded_codebase_'.$i}).'" />'. 10813: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'. 10814: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'. 10815: '<td>'.$env{'form.embedded_orig_'.$i}. 10816: '<input type="hidden" name="embedded_orig_'.$i.'" value="'. 10817: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'. 10818: &end_data_table_row(); 10819: } 10820: } 10821: } else { 10822: $modifyform = $pathchgtable; 10823: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) { 10824: $hiddenstate .= '<input type="hidden" name="phase" value="four" />'; 10825: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 10826: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />'; 10827: } 10828: } 10829: if ($modifyform) { 10830: if ($actionurl eq '/adm/dependencies') { 10831: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />'; 10832: } 10833: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n". 10834: '<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". 10835: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n". 10836: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n". 10837: '</ol></p>'."\n".'<p>'. 10838: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n". 10839: '<form method="post" name="refchanger" action="'.$actionurl.'">'. 10840: &start_data_table()."\n". 10841: &start_data_table_header_row(). 10842: '<th>'.&mt('Change?').'</th>'. 10843: '<th>'.&mt('Current reference').'</th>'. 10844: '<th>'.&mt('Required reference').'</th>'. 10845: &end_data_table_header_row()."\n". 10846: $modifyform. 10847: &end_data_table().'<br />'."\n".$hiddenstate. 10848: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'. 10849: '</form>'."\n"; 10850: } 10851: return; 10852: } 10853: 10854: sub modify_html_refs { 10855: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_; 10856: my $container; 10857: if ($context eq 'portfolio') { 10858: $container = $env{'form.container'}; 10859: } elsif ($context eq 'coursedoc') { 10860: $container = $env{'form.primaryurl'}; 10861: } elsif ($context eq 'manage_dependencies') { 10862: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'}); 10863: $container = "/$container"; 10864: } elsif ($context eq 'syllabus') { 10865: $container = $url; 10866: } else { 10867: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'}; 10868: } 10869: my (%allfiles,%codebase,$output,$content); 10870: my @changes = &get_env_multiple('form.namechange'); 10871: unless ((@changes > 0) || ($context eq 'syllabus')) { 10872: if (wantarray) { 10873: return ('',0,0); 10874: } else { 10875: return; 10876: } 10877: } 10878: if (($context eq 'portfolio') || ($context eq 'coursedoc') || 10879: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) { 10880: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) { 10881: if (wantarray) { 10882: return ('',0,0); 10883: } else { 10884: return; 10885: } 10886: } 10887: $content = &Apache::lonnet::getfile($container); 10888: if ($content eq '-1') { 10889: if (wantarray) { 10890: return ('',0,0); 10891: } else { 10892: return; 10893: } 10894: } 10895: } else { 10896: unless ($container =~ /^\Q$dir_root\E/) { 10897: if (wantarray) { 10898: return ('',0,0); 10899: } else { 10900: return; 10901: } 10902: } 10903: if (open(my $fh,"<$container")) { 10904: $content = join('', <$fh>); 10905: close($fh); 10906: } else { 10907: if (wantarray) { 10908: return ('',0,0); 10909: } else { 10910: return; 10911: } 10912: } 10913: } 10914: my ($count,$codebasecount) = (0,0); 10915: my $mm = new File::MMagic; 10916: my $mime_type = $mm->checktype_contents($content); 10917: if ($mime_type eq 'text/html') { 10918: my $parse_result = 10919: &Apache::lonnet::extract_embedded_items($container,\%allfiles, 10920: \%codebase,\$content); 10921: if ($parse_result eq 'ok') { 10922: foreach my $i (@changes) { 10923: my $orig = &unescape($env{'form.embedded_orig_'.$i}); 10924: my $ref = &unescape($env{'form.embedded_ref_'.$i}); 10925: if ($allfiles{$ref}) { 10926: my $newname = $orig; 10927: my ($attrib_regexp,$codebase); 10928: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i}); 10929: if ($attrib_regexp =~ /:/) { 10930: $attrib_regexp =~ s/\:/|/g; 10931: } 10932: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) { 10933: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi); 10934: $count += $numchg; 10935: $allfiles{$newname} = $allfiles{$ref}; 10936: delete($allfiles{$ref}); 10937: } 10938: if ($env{'form.embedded_codebase_'.$i} ne '') { 10939: $codebase = &unescape($env{'form.embedded_codebase_'.$i}); 10940: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs 10941: $codebasecount ++; 10942: } 10943: } 10944: } 10945: my $skiprewrites; 10946: if ($count || $codebasecount) { 10947: my $saveresult; 10948: if (($context eq 'portfolio') || ($context eq 'coursedoc') || 10949: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) { 10950: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult); 10951: if ($url eq $container) { 10952: my ($fname) = ($container =~ m{/([^/]+)$}); 10953: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].', 10954: $count,'<span class="LC_filename">'. 10955: $fname.'</span>').'</p>'; 10956: } else { 10957: $output = '<p class="LC_error">'. 10958: &mt('Error: update failed for: [_1].', 10959: '<span class="LC_filename">'. 10960: $container.'</span>').'</p>'; 10961: } 10962: if ($context eq 'syllabus') { 10963: unless ($saveresult eq 'ok') { 10964: $skiprewrites = 1; 10965: } 10966: } 10967: } else { 10968: if (open(my $fh,">$container")) { 10969: print $fh $content; 10970: close($fh); 10971: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].', 10972: $count,'<span class="LC_filename">'. 10973: $container.'</span>').'</p>'; 10974: } else { 10975: $output = '<p class="LC_error">'. 10976: &mt('Error: could not update [_1].', 10977: '<span class="LC_filename">'. 10978: $container.'</span>').'</p>'; 10979: } 10980: } 10981: } 10982: if (($context eq 'syllabus') && (!$skiprewrites)) { 10983: my ($actionurl,$state); 10984: $actionurl = "/public/$udom/$uname/syllabus"; 10985: my ($ignore,$num,$numpathchanges,$existing,$mapping) = 10986: &ask_for_embedded_content($actionurl,$state,\%allfiles, 10987: \%codebase, 10988: {'context' => 'rewrites', 10989: 'ignore_remote_references' => 1,}); 10990: if (ref($mapping) eq 'HASH') { 10991: my $rewrites = 0; 10992: foreach my $key (keys(%{$mapping})) { 10993: next if ($key =~ m{^https?://}); 10994: my $ref = $mapping->{$key}; 10995: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key"; 10996: my $attrib; 10997: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') { 10998: $attrib = join('|',@{$allfiles{$mapping->{$key}}}); 10999: } 11000: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) { 11001: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi); 11002: $rewrites += $numchg; 11003: } 11004: } 11005: if ($rewrites) { 11006: my $saveresult; 11007: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult); 11008: if ($url eq $container) { 11009: my ($fname) = ($container =~ m{/([^/]+)$}); 11010: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].', 11011: $count,'<span class="LC_filename">'. 11012: $fname.'</span>').'</p>'; 11013: } else { 11014: $output .= '<p class="LC_error">'. 11015: &mt('Error: could not update links in [_1].', 11016: '<span class="LC_filename">'. 11017: $container.'</span>').'</p>'; 11018: 11019: } 11020: } 11021: } 11022: } 11023: } else { 11024: &logthis('Failed to parse '.$container. 11025: ' to modify references: '.$parse_result); 11026: } 11027: } 11028: if (wantarray) { 11029: return ($output,$count,$codebasecount); 11030: } else { 11031: return $output; 11032: } 11033: } 11034: 11035: sub check_for_existing { 11036: my ($path,$fname,$element) = @_; 11037: my ($state,$msg); 11038: if (-d $path.'/'.$fname) { 11039: $state = 'exists'; 11040: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path); 11041: } elsif (-e $path.'/'.$fname) { 11042: $state = 'exists'; 11043: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path); 11044: } 11045: if ($state eq 'exists') { 11046: $msg = '<span class="LC_error">'.$msg.'</span><br />'; 11047: } 11048: return ($state,$msg); 11049: } 11050: 11051: sub check_for_upload { 11052: my ($path,$fname,$group,$element,$portfolio_root,$port_path, 11053: $disk_quota,$current_disk_usage,$uname,$udom) = @_; 11054: my $filesize = length($env{'form.'.$element}); 11055: if (!$filesize) { 11056: my $msg = '<span class="LC_error">'. 11057: &mt('Unable to upload [_1]. (size = [_2] bytes)', 11058: '<span class="LC_filename">'.$fname.'</span>', 11059: $filesize).'<br />'. 11060: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'. 11061: '</span>'; 11062: return ('zero_bytes',$msg); 11063: } 11064: $filesize = $filesize/1000; #express in k (1024?) 11065: my $getpropath = 1; 11066: my ($dirlistref,$listerror) = 11067: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath); 11068: my $found_file = 0; 11069: my $locked_file = 0; 11070: my @lockers; 11071: my $navmap; 11072: if ($env{'request.course.id'}) { 11073: $navmap = Apache::lonnavmaps::navmap->new(); 11074: } 11075: if (ref($dirlistref) eq 'ARRAY') { 11076: foreach my $line (@{$dirlistref}) { 11077: my ($file_name,$rest)=split(/\&/,$line,2); 11078: if ($file_name eq $fname){ 11079: $file_name = $path.$file_name; 11080: if ($group ne '') { 11081: $file_name = $group.$file_name; 11082: } 11083: $found_file = 1; 11084: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') { 11085: foreach my $lock (@lockers) { 11086: if (ref($lock) eq 'ARRAY') { 11087: my ($symb,$crsid) = @{$lock}; 11088: if ($crsid eq $env{'request.course.id'}) { 11089: if (ref($navmap)) { 11090: my $res = $navmap->getBySymb($symb); 11091: foreach my $part (@{$res->parts()}) { 11092: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part); 11093: unless (($slot_status == $res->RESERVED) || 11094: ($slot_status == $res->RESERVED_LOCATION)) { 11095: $locked_file = 1; 11096: } 11097: } 11098: } else { 11099: $locked_file = 1; 11100: } 11101: } else { 11102: $locked_file = 1; 11103: } 11104: } 11105: } 11106: } else { 11107: my @info = split(/\&/,$rest); 11108: my $currsize = $info[6]/1000; 11109: if ($currsize < $filesize) { 11110: my $extra = $filesize - $currsize; 11111: if (($current_disk_usage + $extra) > $disk_quota) { 11112: my $msg = '<p class="LC_warning">'. 11113: &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.', 11114: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'. 11115: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.', 11116: $disk_quota,$current_disk_usage).'</p>'; 11117: return ('will_exceed_quota',$msg); 11118: } 11119: } 11120: } 11121: } 11122: } 11123: } 11124: if (($current_disk_usage + $filesize) > $disk_quota){ 11125: my $msg = '<p class="LC_warning">'. 11126: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'. 11127: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>'; 11128: return ('will_exceed_quota',$msg); 11129: } elsif ($found_file) { 11130: if ($locked_file) { 11131: my $msg = '<p class="LC_warning">'; 11132: $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>'); 11133: $msg .= '</p>'; 11134: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>'); 11135: return ('file_locked',$msg); 11136: } else { 11137: my $msg = '<p class="LC_error">'; 11138: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'}); 11139: $msg .= '</p>'; 11140: return ('existingfile',$msg); 11141: } 11142: } 11143: } 11144: 11145: sub check_for_traversal { 11146: my ($path,$url,$toplevel) = @_; 11147: my @parts=split(/\//,$path); 11148: my $cleanpath; 11149: my $fullpath = $url; 11150: for (my $i=0;$i<@parts;$i++) { 11151: next if ($parts[$i] eq '.'); 11152: if ($parts[$i] eq '..') { 11153: $fullpath =~ s{([^/]+/)$}{}; 11154: } else { 11155: $fullpath .= $parts[$i].'/'; 11156: } 11157: } 11158: if ($fullpath =~ /^\Q$url\E(.*)$/) { 11159: $cleanpath = $1; 11160: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) { 11161: my $curr_toprel = $1; 11162: my @parts = split(/\//,$curr_toprel); 11163: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/); 11164: my @urlparts = split(/\//,$url_toprel); 11165: my $doubledots; 11166: my $startdiff = -1; 11167: for (my $i=0; $i<@urlparts; $i++) { 11168: if ($startdiff == -1) { 11169: unless ($urlparts[$i] eq $parts[$i]) { 11170: $startdiff = $i; 11171: $doubledots .= '../'; 11172: } 11173: } else { 11174: $doubledots .= '../'; 11175: } 11176: } 11177: if ($startdiff > -1) { 11178: $cleanpath = $doubledots; 11179: for (my $i=$startdiff; $i<@parts; $i++) { 11180: $cleanpath .= $parts[$i].'/'; 11181: } 11182: } 11183: } 11184: $cleanpath =~ s{(/)$}{}; 11185: return $cleanpath; 11186: } 11187: 11188: sub is_archive_file { 11189: my ($mimetype) = @_; 11190: if (($mimetype eq 'application/octet-stream') || 11191: ($mimetype eq 'application/x-stuffit') || 11192: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) { 11193: return 1; 11194: } 11195: return; 11196: } 11197: 11198: sub decompress_form { 11199: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_; 11200: my %lt = &Apache::lonlocal::texthash ( 11201: this => 'This file is an archive file.', 11202: camt => 'This file is a Camtasia archive file.', 11203: itsc => 'Its contents are as follows:', 11204: youm => 'You may wish to extract its contents.', 11205: extr => 'Extract contents', 11206: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.', 11207: proa => 'Process automatically?', 11208: yes => 'Yes', 11209: no => 'No', 11210: fold => 'Title for folder containing movie', 11211: movi => 'Title for page containing embedded movie', 11212: ); 11213: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl); 11214: my ($is_camtasia,$topdir,%toplevel,@paths); 11215: my $info = &list_archive_contents($fileloc,\@paths); 11216: if (@paths) { 11217: foreach my $path (@paths) { 11218: $path =~ s{^/}{}; 11219: if ($path =~ m{^([^/]+)/$}) { 11220: $topdir = $1; 11221: } 11222: if ($path =~ m{^([^/]+)/}) { 11223: $toplevel{$1} = $path; 11224: } else { 11225: $toplevel{$path} = $path; 11226: } 11227: } 11228: } 11229: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) { 11230: my @camtasia6 = ("$topdir/","$topdir/index.html", 11231: "$topdir/media/", 11232: "$topdir/media/$topdir.mp4", 11233: "$topdir/media/FirstFrame.png", 11234: "$topdir/media/player.swf", 11235: "$topdir/media/swfobject.js", 11236: "$topdir/media/expressInstall.swf"); 11237: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html", 11238: "$topdir/$topdir.mp4", 11239: "$topdir/$topdir\_config.xml", 11240: "$topdir/$topdir\_controller.swf", 11241: "$topdir/$topdir\_embed.css", 11242: "$topdir/$topdir\_First_Frame.png", 11243: "$topdir/$topdir\_player.html", 11244: "$topdir/$topdir\_Thumbnails.png", 11245: "$topdir/playerProductInstall.swf", 11246: "$topdir/scripts/", 11247: "$topdir/scripts/config_xml.js", 11248: "$topdir/scripts/handlebars.js", 11249: "$topdir/scripts/jquery-1.7.1.min.js", 11250: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js", 11251: "$topdir/scripts/modernizr.js", 11252: "$topdir/scripts/player-min.js", 11253: "$topdir/scripts/swfobject.js", 11254: "$topdir/skins/", 11255: "$topdir/skins/configuration_express.xml", 11256: "$topdir/skins/express_show/", 11257: "$topdir/skins/express_show/player-min.css", 11258: "$topdir/skins/express_show/spritesheet.png"); 11259: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html", 11260: "$topdir/$topdir.mp4", 11261: "$topdir/$topdir\_config.xml", 11262: "$topdir/$topdir\_controller.swf", 11263: "$topdir/$topdir\_embed.css", 11264: "$topdir/$topdir\_First_Frame.png", 11265: "$topdir/$topdir\_player.html", 11266: "$topdir/$topdir\_Thumbnails.png", 11267: "$topdir/playerProductInstall.swf", 11268: "$topdir/scripts/", 11269: "$topdir/scripts/config_xml.js", 11270: "$topdir/scripts/techsmith-smart-player.min.js", 11271: "$topdir/skins/", 11272: "$topdir/skins/configuration_express.xml", 11273: "$topdir/skins/express_show/", 11274: "$topdir/skins/express_show/spritesheet.min.css", 11275: "$topdir/skins/express_show/spritesheet.png", 11276: "$topdir/skins/express_show/techsmith-smart-player.min.css"); 11277: my @diffs = &compare_arrays(\@paths,\@camtasia6); 11278: if (@diffs == 0) { 11279: $is_camtasia = 6; 11280: } else { 11281: @diffs = &compare_arrays(\@paths,\@camtasia8_1); 11282: if (@diffs == 0) { 11283: $is_camtasia = 8; 11284: } else { 11285: @diffs = &compare_arrays(\@paths,\@camtasia8_4); 11286: if (@diffs == 0) { 11287: $is_camtasia = 8; 11288: } 11289: } 11290: } 11291: } 11292: my $output; 11293: if ($is_camtasia) { 11294: $output = <<"ENDCAM"; 11295: <script type="text/javascript" language="Javascript"> 11296: // <![CDATA[ 11297: 11298: function camtasiaToggle() { 11299: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) { 11300: if (document.uploaded_decompress.autoextract_camtasia[i].checked) { 11301: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) { 11302: document.getElementById('camtasia_titles').style.display='block'; 11303: } else { 11304: document.getElementById('camtasia_titles').style.display='none'; 11305: } 11306: } 11307: } 11308: return; 11309: } 11310: 11311: // ]]> 11312: </script> 11313: <p>$lt{'camt'}</p> 11314: ENDCAM 11315: } else { 11316: $output = '<p>'.$lt{'this'}; 11317: if ($info eq '') { 11318: $output .= ' '.$lt{'youm'}.'</p>'."\n"; 11319: } else { 11320: $output .= ' '.$lt{'itsc'}.'</p>'."\n". 11321: '<div><pre>'.$info.'</pre></div>'; 11322: } 11323: } 11324: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n"; 11325: my $duplicates; 11326: my $num = 0; 11327: if (ref($dirlist) eq 'ARRAY') { 11328: foreach my $item (@{$dirlist}) { 11329: if (ref($item) eq 'ARRAY') { 11330: if (exists($toplevel{$item->[0]})) { 11331: $duplicates .= 11332: &start_data_table_row(). 11333: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '. 11334: 'value="0" checked="checked" />'.&mt('No').'</label>'. 11335: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '. 11336: 'value="1" />'.&mt('Yes').'</label>'. 11337: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n". 11338: '<td>'.$item->[0].'</td>'; 11339: if ($item->[2]) { 11340: $duplicates .= '<td>'.&mt('Directory').'</td>'; 11341: } else { 11342: $duplicates .= '<td>'.&mt('File').'</td>'; 11343: } 11344: $duplicates .= '<td>'.$item->[3].'</td>'. 11345: '<td>'. 11346: &Apache::lonlocal::locallocaltime($item->[4]). 11347: '</td>'. 11348: &end_data_table_row(); 11349: $num ++; 11350: } 11351: } 11352: } 11353: } 11354: my $itemcount; 11355: if (@paths > 0) { 11356: $itemcount = scalar(@paths); 11357: } else { 11358: $itemcount = 1; 11359: } 11360: if ($is_camtasia) { 11361: $output .= $lt{'auto'}.'<br />'. 11362: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'. 11363: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'. 11364: $lt{'yes'}.'</label> <label>'. 11365: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'. 11366: $lt{'no'}.'</label></span><br />'. 11367: '<div id="camtasia_titles" style="display:block">'. 11368: &Apache::lonhtmlcommon::start_pick_box(). 11369: &Apache::lonhtmlcommon::row_title($lt{'fold'}). 11370: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n". 11371: &Apache::lonhtmlcommon::row_closure(). 11372: &Apache::lonhtmlcommon::row_title($lt{'movi'}). 11373: '<input type="textbox" name="camtasia_moviename" value="" />'."\n". 11374: &Apache::lonhtmlcommon::row_closure(1). 11375: &Apache::lonhtmlcommon::end_pick_box(). 11376: '</div>'; 11377: } 11378: $output .= 11379: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'. 11380: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'. 11381: "\n"; 11382: if ($duplicates ne '') { 11383: $output .= '<p><span class="LC_warning">'. 11384: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'. 11385: &start_data_table(). 11386: &start_data_table_header_row(). 11387: '<th>'.&mt('Overwrite?').'</th>'. 11388: '<th>'.&mt('Name').'</th>'. 11389: '<th>'.&mt('Type').'</th>'. 11390: '<th>'.&mt('Size').'</th>'. 11391: '<th>'.&mt('Last modified').'</th>'. 11392: &end_data_table_header_row(). 11393: $duplicates. 11394: &end_data_table(). 11395: '</p>'; 11396: } 11397: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n"; 11398: if (ref($hiddenelements) eq 'HASH') { 11399: foreach my $hidden (sort(keys(%{$hiddenelements}))) { 11400: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n"; 11401: } 11402: } 11403: $output .= <<"END"; 11404: <br /> 11405: <input type="submit" name="decompress" value="$lt{'extr'}" /> 11406: </form> 11407: $noextract 11408: END 11409: return $output; 11410: } 11411: 11412: sub decompression_utility { 11413: my ($program) = @_; 11414: my @utilities = ('tar','gunzip','bunzip2','unzip'); 11415: my $location; 11416: if (grep(/^\Q$program\E$/,@utilities)) { 11417: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/', 11418: '/usr/sbin/') { 11419: if (-x $dir.$program) { 11420: $location = $dir.$program; 11421: last; 11422: } 11423: } 11424: } 11425: return $location; 11426: } 11427: 11428: sub list_archive_contents { 11429: my ($file,$pathsref) = @_; 11430: my (@cmd,$output); 11431: my $needsregexp; 11432: if ($file =~ /\.zip$/) { 11433: @cmd = (&decompression_utility('unzip'),"-l"); 11434: $needsregexp = 1; 11435: } elsif (($file =~ m/\.tar\.gz$/) || 11436: ($file =~ /\.tgz$/)) { 11437: @cmd = (&decompression_utility('tar'),"-ztf"); 11438: } elsif ($file =~ /\.tar\.bz2$/) { 11439: @cmd = (&decompression_utility('tar'),"-jtf"); 11440: } elsif ($file =~ m|\.tar$|) { 11441: @cmd = (&decompression_utility('tar'),"-tf"); 11442: } 11443: if (@cmd) { 11444: undef($!); 11445: undef($@); 11446: if (open(my $fh,"-|", @cmd, $file)) { 11447: while (my $line = <$fh>) { 11448: $output .= $line; 11449: chomp($line); 11450: my $item; 11451: if ($needsregexp) { 11452: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 11453: } else { 11454: $item = $line; 11455: } 11456: if ($item ne '') { 11457: unless (grep(/^\Q$item\E$/,@{$pathsref})) { 11458: push(@{$pathsref},$item); 11459: } 11460: } 11461: } 11462: close($fh); 11463: } 11464: } 11465: return $output; 11466: } 11467: 11468: sub decompress_uploaded_file { 11469: my ($file,$dir) = @_; 11470: &Apache::lonnet::appenv({'cgi.file' => $file}); 11471: &Apache::lonnet::appenv({'cgi.dir' => $dir}); 11472: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl'); 11473: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$}); 11474: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'}; 11475: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1); 11476: my $decompressed = $env{'cgi.decompressed'}; 11477: &Apache::lonnet::delenv('cgi.file'); 11478: &Apache::lonnet::delenv('cgi.dir'); 11479: &Apache::lonnet::delenv('cgi.decompressed'); 11480: return ($decompressed,$result); 11481: } 11482: 11483: sub process_decompression { 11484: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_; 11485: my ($dir,$error,$warning,$output); 11486: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) { 11487: $error = &mt('Filename not a supported archive file type.'). 11488: '<br />'.&mt('Filename should end with one of: [_1].', 11489: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz'); 11490: } else { 11491: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom); 11492: if ($docuhome eq 'no_host') { 11493: $error = &mt('Could not determine home server for course.'); 11494: } else { 11495: my @ids=&Apache::lonnet::current_machine_ids(); 11496: my $currdir = "$dir_root/$destination"; 11497: if (grep(/^\Q$docuhome\E$/,@ids)) { 11498: $dir = &LONCAPA::propath($docudom,$docuname). 11499: "$dir_root/$destination"; 11500: } else { 11501: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}. 11502: "$dir_root/$docudom/$docuname/$destination"; 11503: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') { 11504: $error = &mt('Archive file not found.'); 11505: } 11506: } 11507: my (@to_overwrite,@to_skip); 11508: if ($env{'form.archive_overwrite_total'} > 0) { 11509: my $total = $env{'form.archive_overwrite_total'}; 11510: for (my $i=0; $i<$total; $i++) { 11511: if ($env{'form.archive_overwrite_'.$i} == 1) { 11512: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i}); 11513: } elsif ($env{'form.archive_overwrite_'.$i} == 0) { 11514: push(@to_skip,$env{'form.archive_overwrite_name_'.$i}); 11515: } 11516: } 11517: } 11518: my $numskip = scalar(@to_skip); 11519: if (($numskip > 0) && 11520: ($numskip == $env{'form.archive_itemcount'})) { 11521: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.'); 11522: } elsif ($dir eq '') { 11523: $error = &mt('Directory containing archive file unavailable.'); 11524: } elsif (!$error) { 11525: my ($decompressed,$display); 11526: if ($numskip > 0) { 11527: my $tempdir = time.'_'.$$.int(rand(10000)); 11528: mkdir("$dir/$tempdir",0755); 11529: system("mv $dir/$file $dir/$tempdir/$file"); 11530: ($decompressed,$display) = 11531: &decompress_uploaded_file($file,"$dir/$tempdir"); 11532: foreach my $item (@to_skip) { 11533: if (($item ne '') && ($item !~ /\.\./)) { 11534: if (-f "$dir/$tempdir/$item") { 11535: unlink("$dir/$tempdir/$item"); 11536: } elsif (-d "$dir/$tempdir/$item") { 11537: system("rm -rf $dir/$tempdir/$item"); 11538: } 11539: } 11540: } 11541: system("mv $dir/$tempdir/* $dir"); 11542: rmdir("$dir/$tempdir"); 11543: } else { 11544: ($decompressed,$display) = 11545: &decompress_uploaded_file($file,$dir); 11546: } 11547: if ($decompressed eq 'ok') { 11548: $output = '<p class="LC_info">'. 11549: &mt('Files extracted successfully from archive.'). 11550: '</p>'."\n"; 11551: my ($warning,$result,@contents); 11552: my ($newdirlistref,$newlisterror) = 11553: &Apache::lonnet::dirlist($currdir,$docudom, 11554: $docuname,1); 11555: my (%is_dir,%changes,@newitems); 11556: my $dirptr = 16384; 11557: if (ref($newdirlistref) eq 'ARRAY') { 11558: foreach my $dir_line (@{$newdirlistref}) { 11559: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5); 11560: unless (($item =~ /^\.+$/) || ($item eq $file) || 11561: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) { 11562: push(@newitems,$item); 11563: if ($dirptr&$testdir) { 11564: $is_dir{$item} = 1; 11565: } 11566: $changes{$item} = 1; 11567: } 11568: } 11569: } 11570: if (keys(%changes) > 0) { 11571: foreach my $item (sort(@newitems)) { 11572: if ($changes{$item}) { 11573: push(@contents,$item); 11574: } 11575: } 11576: } 11577: if (@contents > 0) { 11578: my $wantform; 11579: unless ($env{'form.autoextract_camtasia'}) { 11580: $wantform = 1; 11581: } 11582: my (%children,%parent,%dirorder,%titles); 11583: my ($count,$datatable) = &get_extracted($docudom,$docuname, 11584: $currdir,\%is_dir, 11585: \%children,\%parent, 11586: \@contents,\%dirorder, 11587: \%titles,$wantform); 11588: if ($datatable ne '') { 11589: $output .= &archive_options_form('decompressed',$datatable, 11590: $count,$hiddenelem); 11591: my $startcount = 6; 11592: $output .= &archive_javascript($startcount,$count, 11593: \%titles,\%children); 11594: } 11595: if ($env{'form.autoextract_camtasia'}) { 11596: my $version = $env{'form.autoextract_camtasia'}; 11597: my %displayed; 11598: my $total = 1; 11599: $env{'form.archive_directory'} = []; 11600: foreach my $i (sort { $a <=> $b } keys(%dirorder)) { 11601: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}}); 11602: $path =~ s{/$}{}; 11603: my $item; 11604: if ($path ne '') { 11605: $item = "$path/$titles{$i}"; 11606: } else { 11607: $item = $titles{$i}; 11608: } 11609: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item"; 11610: if ($item eq $contents[0]) { 11611: push(@{$env{'form.archive_directory'}},$i); 11612: $env{'form.archive_'.$i} = 'display'; 11613: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'}; 11614: $displayed{'folder'} = $i; 11615: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) || 11616: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 11617: $env{'form.archive_'.$i} = 'display'; 11618: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'}; 11619: $displayed{'web'} = $i; 11620: } else { 11621: if ((($item eq "$contents[0]/media") && ($version == 6)) || 11622: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") || 11623: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) { 11624: push(@{$env{'form.archive_directory'}},$i); 11625: } 11626: $env{'form.archive_'.$i} = 'dependency'; 11627: } 11628: $total ++; 11629: } 11630: for (my $i=1; $i<$total; $i++) { 11631: next if ($i == $displayed{'web'}); 11632: next if ($i == $displayed{'folder'}); 11633: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'}; 11634: } 11635: $env{'form.phase'} = 'decompress_cleanup'; 11636: $env{'form.archivedelete'} = 1; 11637: $env{'form.archive_count'} = $total-1; 11638: $output .= 11639: &process_extracted_files('coursedocs',$docudom, 11640: $docuname,$destination, 11641: $dir_root,$hiddenelem); 11642: } 11643: } else { 11644: $warning = &mt('No new items extracted from archive file.'); 11645: } 11646: } else { 11647: $output = $display; 11648: $error = &mt('An error occurred during extraction from the archive file.'); 11649: } 11650: } 11651: } 11652: } 11653: if ($error) { 11654: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'. 11655: $error.'</p>'."\n"; 11656: } 11657: if ($warning) { 11658: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n"; 11659: } 11660: return $output; 11661: } 11662: 11663: sub get_extracted { 11664: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder, 11665: $titles,$wantform) = @_; 11666: my $count = 0; 11667: my $depth = 0; 11668: my $datatable; 11669: my @hierarchy; 11670: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') && 11671: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') && 11672: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH')); 11673: foreach my $item (@{$contents}) { 11674: $count ++; 11675: @{$dirorder->{$count}} = @hierarchy; 11676: $titles->{$count} = $item; 11677: &archive_hierarchy($depth,$count,$parent,$children); 11678: if ($wantform) { 11679: $datatable .= &archive_row($is_dir->{$item},$item, 11680: $currdir,$depth,$count); 11681: } 11682: if ($is_dir->{$item}) { 11683: $depth ++; 11684: push(@hierarchy,$count); 11685: $parent->{$depth} = $count; 11686: $datatable .= 11687: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname, 11688: \$depth,\$count,\@hierarchy,$dirorder, 11689: $children,$parent,$titles,$wantform); 11690: $depth --; 11691: pop(@hierarchy); 11692: } 11693: } 11694: return ($count,$datatable); 11695: } 11696: 11697: sub recurse_extracted_archive { 11698: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder, 11699: $children,$parent,$titles,$wantform) = @_; 11700: my $result=''; 11701: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') && 11702: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') && 11703: (ref($dirorder) eq 'HASH')) { 11704: return $result; 11705: } 11706: my $dirptr = 16384; 11707: my ($newdirlistref,$newlisterror) = 11708: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1); 11709: if (ref($newdirlistref) eq 'ARRAY') { 11710: foreach my $dir_line (@{$newdirlistref}) { 11711: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5); 11712: unless ($item =~ /^\.+$/) { 11713: $$count ++; 11714: @{$dirorder->{$$count}} = @{$hierarchy}; 11715: $titles->{$$count} = $item; 11716: &archive_hierarchy($$depth,$$count,$parent,$children); 11717: 11718: my $is_dir; 11719: if ($dirptr&$testdir) { 11720: $is_dir = 1; 11721: } 11722: if ($wantform) { 11723: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count); 11724: } 11725: if ($is_dir) { 11726: $$depth ++; 11727: push(@{$hierarchy},$$count); 11728: $parent->{$$depth} = $$count; 11729: $result .= 11730: &recurse_extracted_archive("$currdir/$item",$docudom, 11731: $docuname,$depth,$count, 11732: $hierarchy,$dirorder,$children, 11733: $parent,$titles,$wantform); 11734: $$depth --; 11735: pop(@{$hierarchy}); 11736: } 11737: } 11738: } 11739: } 11740: return $result; 11741: } 11742: 11743: sub archive_hierarchy { 11744: my ($depth,$count,$parent,$children) =@_; 11745: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) { 11746: if (exists($parent->{$depth})) { 11747: $children->{$parent->{$depth}} .= $count.':'; 11748: } 11749: } 11750: return; 11751: } 11752: 11753: sub archive_row { 11754: my ($is_dir,$item,$currdir,$depth,$count) = @_; 11755: my ($name) = ($item =~ m{([^/]+)$}); 11756: my %choices = &Apache::lonlocal::texthash ( 11757: 'display' => 'Add as file', 11758: 'dependency' => 'Include as dependency', 11759: 'discard' => 'Discard', 11760: ); 11761: if ($is_dir) { 11762: $choices{'display'} = &mt('Add as folder'); 11763: } 11764: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n"; 11765: my $offset = 0; 11766: foreach my $action ('display','dependency','discard') { 11767: $offset ++; 11768: if ($action ne 'display') { 11769: $offset ++; 11770: } 11771: $output .= '<td><span class="LC_nobreak">'. 11772: '<label><input type="radio" name="archive_'.$count. 11773: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"'; 11774: my $text = $choices{$action}; 11775: if ($is_dir) { 11776: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"'; 11777: if ($action eq 'display') { 11778: $text = &mt('Add as folder'); 11779: } 11780: } else { 11781: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"'; 11782: 11783: } 11784: $output .= ' /> '.$choices{$action}.'</label></span>'; 11785: if ($action eq 'dependency') { 11786: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n". 11787: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '. 11788: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n". 11789: '<option value=""></option>'."\n". 11790: '</select>'."\n". 11791: '</div>'; 11792: } elsif ($action eq 'display') { 11793: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n". 11794: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n". 11795: '</div>'; 11796: } 11797: $output .= '</td>'; 11798: } 11799: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'. 11800: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2); 11801: for (my $i=0; $i<$depth; $i++) { 11802: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n"; 11803: } 11804: if ($is_dir) { 11805: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n". 11806: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n"; 11807: } else { 11808: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n"; 11809: } 11810: $output .= ' '.$name.'</td>'."\n". 11811: &end_data_table_row(); 11812: return $output; 11813: } 11814: 11815: sub archive_options_form { 11816: my ($form,$display,$count,$hiddenelem) = @_; 11817: my %lt = &Apache::lonlocal::texthash( 11818: perm => 'Permanently remove archive file?', 11819: hows => 'How should each extracted item be incorporated in the course?', 11820: cont => 'Content actions for all', 11821: addf => 'Add as folder/file', 11822: incd => 'Include as dependency for a displayed file', 11823: disc => 'Discard', 11824: no => 'No', 11825: yes => 'Yes', 11826: save => 'Save', 11827: ); 11828: my $output = <<"END"; 11829: <form name="$form" method="post" action=""> 11830: <p><span class="LC_nobreak">$lt{'perm'} 11831: <label> 11832: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'} 11833: </label> 11834: 11835: <label> 11836: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label> 11837: </span> 11838: </p> 11839: <input type="hidden" name="phase" value="decompress_cleanup" /> 11840: <br />$lt{'hows'} 11841: <div class="LC_columnSection"> 11842: <fieldset> 11843: <legend>$lt{'cont'}</legend> 11844: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 11845: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" /> 11846: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" /> 11847: </fieldset> 11848: </div> 11849: END 11850: return $output. 11851: &start_data_table()."\n". 11852: $display."\n". 11853: &end_data_table()."\n". 11854: '<input type="hidden" name="archive_count" value="'.$count.'" />'. 11855: $hiddenelem. 11856: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'. 11857: '</form>'; 11858: } 11859: 11860: sub archive_javascript { 11861: my ($startcount,$numitems,$titles,$children) = @_; 11862: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH')); 11863: my $maintitle = $env{'form.comment'}; 11864: my $scripttag = <<START; 11865: <script type="text/javascript"> 11866: // <![CDATA[ 11867: 11868: function checkAll(form,prefix) { 11869: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$"); 11870: for (var i=0; i < form.elements.length; i++) { 11871: var id = form.elements[i].id; 11872: if ((id != '') && (id != undefined)) { 11873: if (idstr.test(id)) { 11874: if (form.elements[i].type == 'radio') { 11875: form.elements[i].checked = true; 11876: var nostart = i-$startcount; 11877: var offset = nostart%7; 11878: var count = (nostart-offset)/7; 11879: dependencyCheck(form,count,offset); 11880: } 11881: } 11882: } 11883: } 11884: } 11885: 11886: function propagateCheck(form,count) { 11887: if (count > 0) { 11888: var startelement = $startcount + ((count-1) * 7); 11889: for (var j=1; j<6; j++) { 11890: if ((j != 2) && (j != 4)) { 11891: var item = startelement + j; 11892: if (form.elements[item].type == 'radio') { 11893: if (form.elements[item].checked) { 11894: containerCheck(form,count,j); 11895: break; 11896: } 11897: } 11898: } 11899: } 11900: } 11901: } 11902: 11903: numitems = $numitems 11904: var titles = new Array(numitems); 11905: var parents = new Array(numitems); 11906: for (var i=0; i<numitems; i++) { 11907: parents[i] = new Array; 11908: } 11909: var maintitle = '$maintitle'; 11910: 11911: START 11912: 11913: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) { 11914: my @contents = split(/:/,$children->{$container}); 11915: for (my $i=0; $i<@contents; $i ++) { 11916: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n"; 11917: } 11918: } 11919: 11920: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) { 11921: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n"; 11922: } 11923: 11924: $scripttag .= <<END; 11925: 11926: function containerCheck(form,count,offset) { 11927: if (count > 0) { 11928: dependencyCheck(form,count,offset); 11929: var item = (offset+$startcount)+7*(count-1); 11930: form.elements[item].checked = true; 11931: if(Object.prototype.toString.call(parents[count]) === '[object Array]') { 11932: if (parents[count].length > 0) { 11933: for (var j=0; j<parents[count].length; j++) { 11934: containerCheck(form,parents[count][j],offset); 11935: } 11936: } 11937: } 11938: } 11939: } 11940: 11941: function dependencyCheck(form,count,offset) { 11942: if (count > 0) { 11943: var chosen = (offset+$startcount)+7*(count-1); 11944: var depitem = $startcount + ((count-1) * 7) + 4; 11945: var currtype = form.elements[depitem].type; 11946: if (form.elements[chosen].value == 'dependency') { 11947: document.getElementById('arc_depon_'+count).style.display='block'; 11948: form.elements[depitem].options.length = 0; 11949: form.elements[depitem].options[0] = new Option('Select','',true,true); 11950: for (var i=1; i<=numitems; i++) { 11951: if (i == count) { 11952: continue; 11953: } 11954: var startelement = $startcount + (i-1) * 7; 11955: for (var j=1; j<6; j++) { 11956: if ((j != 2) && (j!= 4)) { 11957: var item = startelement + j; 11958: if (form.elements[item].type == 'radio') { 11959: if (form.elements[item].checked) { 11960: if (form.elements[item].value == 'display') { 11961: var n = form.elements[depitem].options.length; 11962: form.elements[depitem].options[n] = new Option(titles[i],i,false,false); 11963: } 11964: } 11965: } 11966: } 11967: } 11968: } 11969: } else { 11970: document.getElementById('arc_depon_'+count).style.display='none'; 11971: form.elements[depitem].options.length = 0; 11972: form.elements[depitem].options[0] = new Option('Select','',true,true); 11973: } 11974: titleCheck(form,count,offset); 11975: } 11976: } 11977: 11978: function propagateSelect(form,count,offset) { 11979: if (count > 0) { 11980: var item = (1+offset+$startcount)+7*(count-1); 11981: var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 11982: if (Object.prototype.toString.call(parents[count]) === '[object Array]') { 11983: if (parents[count].length > 0) { 11984: for (var j=0; j<parents[count].length; j++) { 11985: containerSelect(form,parents[count][j],offset,picked); 11986: } 11987: } 11988: } 11989: } 11990: } 11991: 11992: function containerSelect(form,count,offset,picked) { 11993: if (count > 0) { 11994: var item = (offset+$startcount)+7*(count-1); 11995: if (form.elements[item].type == 'radio') { 11996: if (form.elements[item].value == 'dependency') { 11997: if (form.elements[item+1].type == 'select-one') { 11998: for (var i=0; i<form.elements[item+1].options.length; i++) { 11999: if (form.elements[item+1].options[i].value == picked) { 12000: form.elements[item+1].selectedIndex = i; 12001: break; 12002: } 12003: } 12004: } 12005: if (Object.prototype.toString.call(parents[count]) === '[object Array]') { 12006: if (parents[count].length > 0) { 12007: for (var j=0; j<parents[count].length; j++) { 12008: containerSelect(form,parents[count][j],offset,picked); 12009: } 12010: } 12011: } 12012: } 12013: } 12014: } 12015: } 12016: 12017: function titleCheck(form,count,offset) { 12018: if (count > 0) { 12019: var chosen = (offset+$startcount)+7*(count-1); 12020: var depitem = $startcount + ((count-1) * 7) + 2; 12021: var currtype = form.elements[depitem].type; 12022: if (form.elements[chosen].value == 'display') { 12023: document.getElementById('arc_title_'+count).style.display='block'; 12024: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) { 12025: document.getElementById('archive_title_'+count).value=maintitle; 12026: } 12027: } else { 12028: document.getElementById('arc_title_'+count).style.display='none'; 12029: if (currtype == 'text') { 12030: document.getElementById('archive_title_'+count).value=''; 12031: } 12032: } 12033: } 12034: return; 12035: } 12036: 12037: // ]]> 12038: </script> 12039: END 12040: return $scripttag; 12041: } 12042: 12043: sub process_extracted_files { 12044: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_; 12045: my $numitems = $env{'form.archive_count'}; 12046: return unless ($numitems); 12047: my @ids=&Apache::lonnet::current_machine_ids(); 12048: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir, 12049: %folders,%containers,%mapinner,%prompttofetch); 12050: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom); 12051: if (grep(/^\Q$docuhome\E$/,@ids)) { 12052: $prefix = &LONCAPA::propath($docudom,$docuname); 12053: $pathtocheck = "$dir_root/$destination"; 12054: $dir = $dir_root; 12055: $ishome = 1; 12056: } else { 12057: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'}; 12058: $pathtocheck = "$dir_root/$docudom/$docuname/$destination"; 12059: $dir = "$dir_root/$docudom/$docuname"; 12060: } 12061: my $currdir = "$dir_root/$destination"; 12062: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/}); 12063: if ($env{'form.folderpath'}) { 12064: my @items = split('&',$env{'form.folderpath'}); 12065: $folders{'0'} = $items[-2]; 12066: if ($env{'form.folderpath'} =~ /\:1$/) { 12067: $containers{'0'}='page'; 12068: } else { 12069: $containers{'0'}='sequence'; 12070: } 12071: } 12072: my @archdirs = &get_env_multiple('form.archive_directory'); 12073: if ($numitems) { 12074: for (my $i=1; $i<=$numitems; $i++) { 12075: my $path = $env{'form.archive_content_'.$i}; 12076: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) { 12077: my $item = $1; 12078: $toplevelitems{$item} = $i; 12079: if (grep(/^\Q$i\E$/,@archdirs)) { 12080: $is_dir{$item} = 1; 12081: } 12082: } 12083: } 12084: } 12085: my ($output,%children,%parent,%titles,%dirorder,$result); 12086: if (keys(%toplevelitems) > 0) { 12087: my @contents = sort(keys(%toplevelitems)); 12088: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children, 12089: \%parent,\@contents,\%dirorder,\%titles); 12090: } 12091: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid); 12092: if ($numitems) { 12093: for (my $i=1; $i<=$numitems; $i++) { 12094: next if ($env{'form.archive_'.$i} eq 'dependency'); 12095: my $path = $env{'form.archive_content_'.$i}; 12096: if ($path =~ /^\Q$pathtocheck\E/) { 12097: if ($env{'form.archive_'.$i} eq 'discard') { 12098: if ($prefix ne '' && $path ne '') { 12099: if (-e $prefix.$path) { 12100: if ((@archdirs > 0) && 12101: (grep(/^\Q$i\E$/,@archdirs))) { 12102: $todeletedir{$prefix.$path} = 1; 12103: } else { 12104: $todelete{$prefix.$path} = 1; 12105: } 12106: } 12107: } 12108: } elsif ($env{'form.archive_'.$i} eq 'display') { 12109: my ($docstitle,$title,$url,$outer); 12110: ($title) = ($path =~ m{/([^/]+)$}); 12111: $docstitle = $env{'form.archive_title_'.$i}; 12112: if ($docstitle eq '') { 12113: $docstitle = $title; 12114: } 12115: $outer = 0; 12116: if (ref($dirorder{$i}) eq 'ARRAY') { 12117: if (@{$dirorder{$i}} > 0) { 12118: foreach my $item (reverse(@{$dirorder{$i}})) { 12119: if ($env{'form.archive_'.$item} eq 'display') { 12120: $outer = $item; 12121: last; 12122: } 12123: } 12124: } 12125: } 12126: my ($errtext,$fatal) = 12127: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname. 12128: '/'.$folders{$outer}.'.'. 12129: $containers{$outer}); 12130: next if ($fatal); 12131: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) { 12132: if ($context eq 'coursedocs') { 12133: $mapinner{$i} = time; 12134: $folders{$i} = 'default_'.$mapinner{$i}; 12135: $containers{$i} = 'sequence'; 12136: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'. 12137: $folders{$i}.'.'.$containers{$i}; 12138: my $newidx = &LONCAPA::map::getresidx(); 12139: $LONCAPA::map::resources[$newidx]= 12140: $docstitle.':'.$url.':false:normal:res'; 12141: push(@LONCAPA::map::order,$newidx); 12142: my ($outtext,$errtext) = 12143: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'. 12144: $docuname.'/'.$folders{$outer}. 12145: '.'.$containers{$outer},1,1); 12146: $newseqid{$i} = $newidx; 12147: unless ($errtext) { 12148: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n"; 12149: } 12150: } 12151: } else { 12152: if ($context eq 'coursedocs') { 12153: my $newidx=&LONCAPA::map::getresidx(); 12154: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'. 12155: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'. 12156: $title; 12157: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") { 12158: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755); 12159: } 12160: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") { 12161: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx"); 12162: } 12163: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") { 12164: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title"); 12165: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx"; 12166: unless ($ishome) { 12167: my $fetch = "$newdest{$i}/$title"; 12168: $fetch =~ s/^\Q$prefix$dir\E//; 12169: $prompttofetch{$fetch} = 1; 12170: } 12171: } 12172: $LONCAPA::map::resources[$newidx]= 12173: $docstitle.':'.$url.':false:normal:res'; 12174: push(@LONCAPA::map::order, $newidx); 12175: my ($outtext,$errtext)= 12176: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'. 12177: $docuname.'/'.$folders{$outer}. 12178: '.'.$containers{$outer},1,1); 12179: unless ($errtext) { 12180: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") { 12181: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n"; 12182: } 12183: } 12184: } 12185: } 12186: } 12187: } else { 12188: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 12189: } 12190: } 12191: for (my $i=1; $i<=$numitems; $i++) { 12192: next unless ($env{'form.archive_'.$i} eq 'dependency'); 12193: my $path = $env{'form.archive_content_'.$i}; 12194: if ($path =~ /^\Q$pathtocheck\E/) { 12195: my ($title) = ($path =~ m{/([^/]+)$}); 12196: $referrer{$i} = $env{'form.archive_dependent_on_'.$i}; 12197: if ($env{'form.archive_'.$referrer{$i}} eq 'display') { 12198: if (ref($dirorder{$i}) eq 'ARRAY') { 12199: my ($itemidx,$fullpath,$relpath); 12200: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') { 12201: my $container = $dirorder{$referrer{$i}}->[-1]; 12202: for (my $j=0; $j<@{$dirorder{$i}}; $j++) { 12203: if ($dirorder{$i}->[$j] eq $container) { 12204: $itemidx = $j; 12205: } 12206: } 12207: } 12208: if ($itemidx eq '') { 12209: $itemidx = 0; 12210: } 12211: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) { 12212: if ($mapinner{$referrer{$i}}) { 12213: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}"; 12214: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { 12215: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { 12216: unless (defined($newseqid{$dirorder{$i}->[$j]})) { 12217: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; 12218: $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; 12219: if (!-e $fullpath) { 12220: mkdir($fullpath,0755); 12221: } 12222: } 12223: } else { 12224: last; 12225: } 12226: } 12227: } 12228: } elsif ($newdest{$referrer{$i}}) { 12229: $fullpath = $newdest{$referrer{$i}}; 12230: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { 12231: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') { 12232: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]}; 12233: last; 12234: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { 12235: unless (defined($newseqid{$dirorder{$i}->[$j]})) { 12236: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; 12237: $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; 12238: if (!-e $fullpath) { 12239: mkdir($fullpath,0755); 12240: } 12241: } 12242: } else { 12243: last; 12244: } 12245: } 12246: } 12247: if ($fullpath ne '') { 12248: if (-e "$prefix$path") { 12249: system("mv $prefix$path $fullpath/$title"); 12250: } 12251: if (-e "$fullpath/$title") { 12252: my $showpath; 12253: if ($relpath ne '') { 12254: $showpath = "$relpath/$title"; 12255: } else { 12256: $showpath = "/$title"; 12257: } 12258: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n"; 12259: } 12260: unless ($ishome) { 12261: my $fetch = "$fullpath/$title"; 12262: $fetch =~ s/^\Q$prefix$dir\E//; 12263: $prompttofetch{$fetch} = 1; 12264: } 12265: } 12266: } 12267: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') { 12268: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.', 12269: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />'; 12270: } 12271: } else { 12272: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 12273: } 12274: } 12275: if (keys(%todelete)) { 12276: foreach my $key (keys(%todelete)) { 12277: unlink($key); 12278: } 12279: } 12280: if (keys(%todeletedir)) { 12281: foreach my $key (keys(%todeletedir)) { 12282: rmdir($key); 12283: } 12284: } 12285: foreach my $dir (sort(keys(%is_dir))) { 12286: if (($pathtocheck ne '') && ($dir ne '')) { 12287: &cleanup_empty_dirs($prefix."$pathtocheck/$dir"); 12288: } 12289: } 12290: if ($result ne '') { 12291: $output .= '<ul>'."\n". 12292: $result."\n". 12293: '</ul>'; 12294: } 12295: unless ($ishome) { 12296: my $replicationfail; 12297: foreach my $item (keys(%prompttofetch)) { 12298: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome); 12299: unless ($fetchresult eq 'ok') { 12300: $replicationfail .= '<li>'.$item.'</li>'."\n"; 12301: } 12302: } 12303: if ($replicationfail) { 12304: $output .= '<p class="LC_error">'. 12305: &mt('Course home server failed to retrieve:').'<ul>'. 12306: $replicationfail. 12307: '</ul></p>'; 12308: } 12309: } 12310: } else { 12311: $warning = &mt('No items found in archive.'); 12312: } 12313: if ($error) { 12314: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'. 12315: $error.'</p>'."\n"; 12316: } 12317: if ($warning) { 12318: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n"; 12319: } 12320: return $output; 12321: } 12322: 12323: sub cleanup_empty_dirs { 12324: my ($path) = @_; 12325: if (($path ne '') && (-d $path)) { 12326: if (opendir(my $dirh,$path)) { 12327: my @dircontents = grep(!/^\./,readdir($dirh)); 12328: my $numitems = 0; 12329: foreach my $item (@dircontents) { 12330: if (-d "$path/$item") { 12331: &cleanup_empty_dirs("$path/$item"); 12332: if (-e "$path/$item") { 12333: $numitems ++; 12334: } 12335: } else { 12336: $numitems ++; 12337: } 12338: } 12339: if ($numitems == 0) { 12340: rmdir($path); 12341: } 12342: closedir($dirh); 12343: } 12344: } 12345: return; 12346: } 12347: 12348: =pod 12349: 12350: =item * &get_folder_hierarchy() 12351: 12352: Provides hierarchy of names of folders/sub-folders containing the current 12353: item, 12354: 12355: Inputs: 3 12356: - $navmap - navmaps object 12357: 12358: - $map - url for map (either the trigger itself, or map containing 12359: the resource, which is the trigger). 12360: 12361: - $showitem - 1 => show title for map itself; 0 => do not show. 12362: 12363: Outputs: 1 @pathitems - array of folder/subfolder names. 12364: 12365: =cut 12366: 12367: sub get_folder_hierarchy { 12368: my ($navmap,$map,$showitem) = @_; 12369: my @pathitems; 12370: if (ref($navmap)) { 12371: my $mapres = $navmap->getResourceByUrl($map); 12372: if (ref($mapres)) { 12373: my $pcslist = $mapres->map_hierarchy(); 12374: if ($pcslist ne '') { 12375: my @pcs = split(/,/,$pcslist); 12376: foreach my $pc (@pcs) { 12377: if ($pc == 1) { 12378: push(@pathitems,&mt('Main Content')); 12379: } else { 12380: my $res = $navmap->getByMapPc($pc); 12381: if (ref($res)) { 12382: my $title = $res->compTitle(); 12383: $title =~ s/\W+/_/g; 12384: if ($title ne '') { 12385: push(@pathitems,$title); 12386: } 12387: } 12388: } 12389: } 12390: } 12391: if ($showitem) { 12392: if ($mapres->{ID} eq '0.0') { 12393: push(@pathitems,&mt('Main Content')); 12394: } else { 12395: my $maptitle = $mapres->compTitle(); 12396: $maptitle =~ s/\W+/_/g; 12397: if ($maptitle ne '') { 12398: push(@pathitems,$maptitle); 12399: } 12400: } 12401: } 12402: } 12403: } 12404: return @pathitems; 12405: } 12406: 12407: =pod 12408: 12409: =item * &get_turnedin_filepath() 12410: 12411: Determines path in a user's portfolio file for storage of files uploaded 12412: to a specific essayresponse or dropbox item. 12413: 12414: Inputs: 3 required + 1 optional. 12415: $symb is symb for resource, $uname and $udom are for current user (required). 12416: $caller is optional (can be "submission", if routine is called when storing 12417: an upoaded file when "Submit Answer" button was pressed). 12418: 12419: Returns array containing $path and $multiresp. 12420: $path is path in portfolio. $multiresp is 1 if this resource contains more 12421: than one file upload item. Callers of routine should append partid as a 12422: subdirectory to $path in cases where $multiresp is 1. 12423: 12424: Called by: homework/essayresponse.pm and homework/structuretags.pm 12425: 12426: =cut 12427: 12428: sub get_turnedin_filepath { 12429: my ($symb,$uname,$udom,$caller) = @_; 12430: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb); 12431: my $turnindir; 12432: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir'); 12433: $turnindir = $userhash{'turnindir'}; 12434: my ($path,$multiresp); 12435: if ($turnindir eq '') { 12436: if ($caller eq 'submission') { 12437: $turnindir = &mt('turned in'); 12438: $turnindir =~ s/\W+/_/g; 12439: my %newhash = ( 12440: 'turnindir' => $turnindir, 12441: ); 12442: &Apache::lonnet::put('environment',\%newhash,$udom,$uname); 12443: } 12444: } 12445: if ($turnindir ne '') { 12446: $path = '/'.$turnindir.'/'; 12447: my ($multipart,$turnin,@pathitems); 12448: my $navmap = Apache::lonnavmaps::navmap->new(); 12449: if (defined($navmap)) { 12450: my $mapres = $navmap->getResourceByUrl($map); 12451: if (ref($mapres)) { 12452: my $pcslist = $mapres->map_hierarchy(); 12453: if ($pcslist ne '') { 12454: foreach my $pc (split(/,/,$pcslist)) { 12455: my $res = $navmap->getByMapPc($pc); 12456: if (ref($res)) { 12457: my $title = $res->compTitle(); 12458: $title =~ s/\W+/_/g; 12459: if ($title ne '') { 12460: if (($pc > 1) && (length($title) > 12)) { 12461: $title = substr($title,0,12); 12462: } 12463: push(@pathitems,$title); 12464: } 12465: } 12466: } 12467: } 12468: my $maptitle = $mapres->compTitle(); 12469: $maptitle =~ s/\W+/_/g; 12470: if ($maptitle ne '') { 12471: if (length($maptitle) > 12) { 12472: $maptitle = substr($maptitle,0,12); 12473: } 12474: push(@pathitems,$maptitle); 12475: } 12476: unless ($env{'request.state'} eq 'construct') { 12477: my $res = $navmap->getBySymb($symb); 12478: if (ref($res)) { 12479: my $partlist = $res->parts(); 12480: my $totaluploads = 0; 12481: if (ref($partlist) eq 'ARRAY') { 12482: foreach my $part (@{$partlist}) { 12483: my @types = $res->responseType($part); 12484: my @ids = $res->responseIds($part); 12485: for (my $i=0; $i < scalar(@ids); $i++) { 12486: if ($types[$i] eq 'essay') { 12487: my $partid = $part.'_'.$ids[$i]; 12488: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') { 12489: $totaluploads ++; 12490: } 12491: } 12492: } 12493: } 12494: if ($totaluploads > 1) { 12495: $multiresp = 1; 12496: } 12497: } 12498: } 12499: } 12500: } else { 12501: return; 12502: } 12503: } else { 12504: return; 12505: } 12506: my $restitle=&Apache::lonnet::gettitle($symb); 12507: $restitle =~ s/\W+/_/g; 12508: if ($restitle eq '') { 12509: $restitle = ($resurl =~ m{/[^/]+$}); 12510: if ($restitle eq '') { 12511: $restitle = time; 12512: } 12513: } 12514: if (length($restitle) > 12) { 12515: $restitle = substr($restitle,0,12); 12516: } 12517: push(@pathitems,$restitle); 12518: $path .= join('/',@pathitems); 12519: } 12520: return ($path,$multiresp); 12521: } 12522: 12523: =pod 12524: 12525: =back 12526: 12527: =head1 CSV Upload/Handling functions 12528: 12529: =over 4 12530: 12531: =item * &upfile_store($r) 12532: 12533: Store uploaded file, $r should be the HTTP Request object, 12534: needs $env{'form.upfile'} 12535: returns $datatoken to be put into hidden field 12536: 12537: =cut 12538: 12539: sub upfile_store { 12540: my $r=shift; 12541: $env{'form.upfile'}=~s/\r/\n/gs; 12542: $env{'form.upfile'}=~s/\f/\n/gs; 12543: $env{'form.upfile'}=~s/\n+/\n/gs; 12544: $env{'form.upfile'}=~s/\n+$//gs; 12545: 12546: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}. 12547: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$; 12548: { 12549: my $datafile = $r->dir_config('lonDaemons'). 12550: '/tmp/'.$datatoken.'.tmp'; 12551: if ( open(my $fh,">$datafile") ) { 12552: print $fh $env{'form.upfile'}; 12553: close($fh); 12554: } 12555: } 12556: return $datatoken; 12557: } 12558: 12559: =pod 12560: 12561: =item * &load_tmp_file($r) 12562: 12563: Load uploaded file from tmp, $r should be the HTTP Request object, 12564: needs $env{'form.datatoken'}, 12565: sets $env{'form.upfile'} to the contents of the file 12566: 12567: =cut 12568: 12569: sub load_tmp_file { 12570: my $r=shift; 12571: my @studentdata=(); 12572: { 12573: my $studentfile = $r->dir_config('lonDaemons'). 12574: '/tmp/'.$env{'form.datatoken'}.'.tmp'; 12575: if ( open(my $fh,"<$studentfile") ) { 12576: @studentdata=<$fh>; 12577: close($fh); 12578: } 12579: } 12580: $env{'form.upfile'}=join('',@studentdata); 12581: } 12582: 12583: =pod 12584: 12585: =item * &upfile_record_sep() 12586: 12587: Separate uploaded file into records 12588: returns array of records, 12589: needs $env{'form.upfile'} and $env{'form.upfiletype'} 12590: 12591: =cut 12592: 12593: sub upfile_record_sep { 12594: if ($env{'form.upfiletype'} eq 'xml') { 12595: } else { 12596: my @records; 12597: foreach my $line (split(/\n/,$env{'form.upfile'})) { 12598: if ($line=~/^\s*$/) { next; } 12599: push(@records,$line); 12600: } 12601: return @records; 12602: } 12603: } 12604: 12605: =pod 12606: 12607: =item * &record_sep($record) 12608: 12609: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'} 12610: 12611: =cut 12612: 12613: sub takeleft { 12614: my $index=shift; 12615: return substr('0000'.$index,-4,4); 12616: } 12617: 12618: sub record_sep { 12619: my $record=shift; 12620: my %components=(); 12621: if ($env{'form.upfiletype'} eq 'xml') { 12622: } elsif ($env{'form.upfiletype'} eq 'space') { 12623: my $i=0; 12624: foreach my $field (split(/\s+/,$record)) { 12625: $field=~s/^(\"|\')//; 12626: $field=~s/(\"|\')$//; 12627: $components{&takeleft($i)}=$field; 12628: $i++; 12629: } 12630: } elsif ($env{'form.upfiletype'} eq 'tab') { 12631: my $i=0; 12632: foreach my $field (split(/\t/,$record)) { 12633: $field=~s/^(\"|\')//; 12634: $field=~s/(\"|\')$//; 12635: $components{&takeleft($i)}=$field; 12636: $i++; 12637: } 12638: } else { 12639: my $separator=','; 12640: if ($env{'form.upfiletype'} eq 'semisv') { 12641: $separator=';'; 12642: } 12643: my $i=0; 12644: # the character we are looking for to indicate the end of a quote or a record 12645: my $looking_for=$separator; 12646: # do not add the characters to the fields 12647: my $ignore=0; 12648: # we just encountered a separator (or the beginning of the record) 12649: my $just_found_separator=1; 12650: # store the field we are working on here 12651: my $field=''; 12652: # work our way through all characters in record 12653: foreach my $character ($record=~/(.)/g) { 12654: if ($character eq $looking_for) { 12655: if ($character ne $separator) { 12656: # Found the end of a quote, again looking for separator 12657: $looking_for=$separator; 12658: $ignore=1; 12659: } else { 12660: # Found a separator, store away what we got 12661: $components{&takeleft($i)}=$field; 12662: $i++; 12663: $just_found_separator=1; 12664: $ignore=0; 12665: $field=''; 12666: } 12667: next; 12668: } 12669: # single or double quotation marks after a separator indicate beginning of a quote 12670: # we are now looking for the end of the quote and need to ignore separators 12671: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) { 12672: $looking_for=$character; 12673: next; 12674: } 12675: # ignore would be true after we reached the end of a quote 12676: if ($ignore) { next; } 12677: if (($just_found_separator) && ($character=~/\s/)) { next; } 12678: $field.=$character; 12679: $just_found_separator=0; 12680: } 12681: # catch the very last entry, since we never encountered the separator 12682: $components{&takeleft($i)}=$field; 12683: } 12684: return %components; 12685: } 12686: 12687: ###################################################### 12688: ###################################################### 12689: 12690: =pod 12691: 12692: =item * &upfile_select_html() 12693: 12694: Return HTML code to select a file from the users machine and specify 12695: the file type. 12696: 12697: =cut 12698: 12699: ###################################################### 12700: ###################################################### 12701: sub upfile_select_html { 12702: my %Types = ( 12703: csv => &mt('CSV (comma separated values, spreadsheet)'), 12704: semisv => &mt('Semicolon separated values'), 12705: space => &mt('Space separated'), 12706: tab => &mt('Tabulator separated'), 12707: # xml => &mt('HTML/XML'), 12708: ); 12709: my $Str = '<input type="file" name="upfile" size="50" />'. 12710: '<br />'.&mt('Type').': <select name="upfiletype">'; 12711: foreach my $type (sort(keys(%Types))) { 12712: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n"; 12713: } 12714: $Str .= "</select>\n"; 12715: return $Str; 12716: } 12717: 12718: sub get_samples { 12719: my ($records,$toget) = @_; 12720: my @samples=({}); 12721: my $got=0; 12722: foreach my $rec (@$records) { 12723: my %temp = &record_sep($rec); 12724: if (! grep(/\S/, values(%temp))) { next; } 12725: if (%temp) { 12726: $samples[$got]=\%temp; 12727: $got++; 12728: if ($got == $toget) { last; } 12729: } 12730: } 12731: return \@samples; 12732: } 12733: 12734: ###################################################### 12735: ###################################################### 12736: 12737: =pod 12738: 12739: =item * &csv_print_samples($r,$records) 12740: 12741: Prints a table of sample values from each column uploaded $r is an 12742: Apache Request ref, $records is an arrayref from 12743: &Apache::loncommon::upfile_record_sep 12744: 12745: =cut 12746: 12747: ###################################################### 12748: ###################################################### 12749: sub csv_print_samples { 12750: my ($r,$records) = @_; 12751: my $samples = &get_samples($records,5); 12752: 12753: $r->print(&mt('Samples').'<br />'.&start_data_table(). 12754: &start_data_table_header_row()); 12755: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 12756: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); } 12757: $r->print(&end_data_table_header_row()); 12758: foreach my $hash (@$samples) { 12759: $r->print(&start_data_table_row()); 12760: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 12761: $r->print('<td>'); 12762: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); } 12763: $r->print('</td>'); 12764: } 12765: $r->print(&end_data_table_row()); 12766: } 12767: $r->print(&end_data_table().'<br />'."\n"); 12768: } 12769: 12770: ###################################################### 12771: ###################################################### 12772: 12773: =pod 12774: 12775: =item * &csv_print_select_table($r,$records,$d) 12776: 12777: Prints a table to create associations between values and table columns. 12778: 12779: $r is an Apache Request ref, 12780: $records is an arrayref from &Apache::loncommon::upfile_record_sep, 12781: $d is an array of 2 element arrays (internal name, displayed name,defaultcol) 12782: 12783: =cut 12784: 12785: ###################################################### 12786: ###################################################### 12787: sub csv_print_select_table { 12788: my ($r,$records,$d) = @_; 12789: my $i=0; 12790: my $samples = &get_samples($records,1); 12791: $r->print(&mt('Associate columns with student attributes.')."\n". 12792: &start_data_table().&start_data_table_header_row(). 12793: '<th>'.&mt('Attribute').'</th>'. 12794: '<th>'.&mt('Column').'</th>'. 12795: &end_data_table_header_row()."\n"); 12796: foreach my $array_ref (@$d) { 12797: my ($value,$display,$defaultcol)=@{ $array_ref }; 12798: $r->print(&start_data_table_row().'<td>'.$display.'</td>'); 12799: 12800: $r->print('<td><select name="f'.$i.'"'. 12801: ' onchange="javascript:flip(this.form,'.$i.');">'); 12802: $r->print('<option value="none"></option>'); 12803: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 12804: $r->print('<option value="'.$sample.'"'. 12805: ($sample eq $defaultcol ? ' selected="selected" ' : ''). 12806: '>'.&mt('Column [_1]',($sample+1)).'</option>'); 12807: } 12808: $r->print('</select></td>'.&end_data_table_row()."\n"); 12809: $i++; 12810: } 12811: $r->print(&end_data_table()); 12812: $i--; 12813: return $i; 12814: } 12815: 12816: ###################################################### 12817: ###################################################### 12818: 12819: =pod 12820: 12821: =item * &csv_samples_select_table($r,$records,$d) 12822: 12823: Prints a table of sample values from the upload and can make associate samples to internal names. 12824: 12825: $r is an Apache Request ref, 12826: $records is an arrayref from &Apache::loncommon::upfile_record_sep, 12827: $d is an array of 2 element arrays (internal name, displayed name) 12828: 12829: =cut 12830: 12831: ###################################################### 12832: ###################################################### 12833: sub csv_samples_select_table { 12834: my ($r,$records,$d) = @_; 12835: my $i=0; 12836: # 12837: my $max_samples = 5; 12838: my $samples = &get_samples($records,$max_samples); 12839: $r->print(&start_data_table(). 12840: &start_data_table_header_row().'<th>'. 12841: &mt('Field').'</th><th>'.&mt('Samples').'</th>'. 12842: &end_data_table_header_row()); 12843: 12844: foreach my $key (sort(keys(%{ $samples->[0] }))) { 12845: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'. 12846: ' onchange="javascript:flip(this.form,'.$i.');">'); 12847: foreach my $option (@$d) { 12848: my ($value,$display,$defaultcol)=@{ $option }; 12849: $r->print('<option value="'.$value.'"'. 12850: ($i eq $defaultcol ? ' selected="selected" ':'').'>'. 12851: $display.'</option>'); 12852: } 12853: $r->print('</select></td><td>'); 12854: foreach my $line (0..($max_samples-1)) { 12855: if (defined($samples->[$line]{$key})) { 12856: $r->print($samples->[$line]{$key}."<br />\n"); 12857: } 12858: } 12859: $r->print('</td>'.&end_data_table_row()); 12860: $i++; 12861: } 12862: $r->print(&end_data_table()); 12863: $i--; 12864: return($i); 12865: } 12866: 12867: ###################################################### 12868: ###################################################### 12869: 12870: =pod 12871: 12872: =item * &clean_excel_name($name) 12873: 12874: Returns a replacement for $name which does not contain any illegal characters. 12875: 12876: =cut 12877: 12878: ###################################################### 12879: ###################################################### 12880: sub clean_excel_name { 12881: my ($name) = @_; 12882: $name =~ s/[:\*\?\/\\]//g; 12883: if (length($name) > 31) { 12884: $name = substr($name,0,31); 12885: } 12886: return $name; 12887: } 12888: 12889: =pod 12890: 12891: =item * &check_if_partid_hidden($id,$symb,$udom,$uname) 12892: 12893: Returns either 1 or undef 12894: 12895: 1 if the part is to be hidden, undef if it is to be shown 12896: 12897: Arguments are: 12898: 12899: $id the id of the part to be checked 12900: $symb, optional the symb of the resource to check 12901: $udom, optional the domain of the user to check for 12902: $uname, optional the username of the user to check for 12903: 12904: =cut 12905: 12906: sub check_if_partid_hidden { 12907: my ($id,$symb,$udom,$uname) = @_; 12908: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts', 12909: $symb,$udom,$uname); 12910: my $truth=1; 12911: #if the string starts with !, then the list is the list to show not hide 12912: if ($hiddenparts=~s/^\s*!//) { $truth=undef; } 12913: my @hiddenlist=split(/,/,$hiddenparts); 12914: foreach my $checkid (@hiddenlist) { 12915: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; } 12916: } 12917: return !$truth; 12918: } 12919: 12920: 12921: ############################################################ 12922: ############################################################ 12923: 12924: =pod 12925: 12926: =back 12927: 12928: =head1 cgi-bin script and graphing routines 12929: 12930: =over 4 12931: 12932: =item * &get_cgi_id() 12933: 12934: Inputs: none 12935: 12936: Returns an id which can be used to pass environment variables 12937: to various cgi-bin scripts. These environment variables will 12938: be removed from the users environment after a given time by 12939: the routine &Apache::lonnet::transfer_profile_to_env. 12940: 12941: =cut 12942: 12943: ############################################################ 12944: ############################################################ 12945: my $uniq=0; 12946: sub get_cgi_id { 12947: $uniq=($uniq+1)%100000; 12948: return (time.'_'.$$.'_'.$uniq); 12949: } 12950: 12951: ############################################################ 12952: ############################################################ 12953: 12954: =pod 12955: 12956: =item * &DrawBarGraph() 12957: 12958: Facilitates the plotting of data in a (stacked) bar graph. 12959: Puts plot definition data into the users environment in order for 12960: graph.png to plot it. Returns an <img> tag for the plot. 12961: The bars on the plot are labeled '1','2',...,'n'. 12962: 12963: Inputs: 12964: 12965: =over 4 12966: 12967: =item $Title: string, the title of the plot 12968: 12969: =item $xlabel: string, text describing the X-axis of the plot 12970: 12971: =item $ylabel: string, text describing the Y-axis of the plot 12972: 12973: =item $Max: scalar, the maximum Y value to use in the plot 12974: If $Max is < any data point, the graph will not be rendered. 12975: 12976: =item $colors: array ref holding the colors to be used for the data sets when 12977: they are plotted. If undefined, default values will be used. 12978: 12979: =item $labels: array ref holding the labels to use on the x-axis for the bars. 12980: 12981: =item @Values: An array of array references. Each array reference holds data 12982: to be plotted in a stacked bar chart. 12983: 12984: =item If the final element of @Values is a hash reference the key/value 12985: pairs will be added to the graph definition. 12986: 12987: =back 12988: 12989: Returns: 12990: 12991: An <img> tag which references graph.png and the appropriate identifying 12992: information for the plot. 12993: 12994: =cut 12995: 12996: ############################################################ 12997: ############################################################ 12998: sub DrawBarGraph { 12999: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_; 13000: # 13001: if (! defined($colors)) { 13002: $colors = ['#33ff00', 13003: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933', 13004: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66', 13005: ]; 13006: } 13007: my $extra_settings = {}; 13008: if (ref($Values[-1]) eq 'HASH') { 13009: $extra_settings = pop(@Values); 13010: } 13011: # 13012: my $identifier = &get_cgi_id(); 13013: my $id = 'cgi.'.$identifier; 13014: if (! @Values || ref($Values[0]) ne 'ARRAY') { 13015: return ''; 13016: } 13017: # 13018: my @Labels; 13019: if (defined($labels)) { 13020: @Labels = @$labels; 13021: } else { 13022: for (my $i=0;$i<@{$Values[0]};$i++) { 13023: push (@Labels,$i+1); 13024: } 13025: } 13026: # 13027: my $NumBars = scalar(@{$Values[0]}); 13028: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); } 13029: my %ValuesHash; 13030: my $NumSets=1; 13031: foreach my $array (@Values) { 13032: next if (! ref($array)); 13033: $ValuesHash{$id.'.data.'.$NumSets++} = 13034: join(',',@$array); 13035: } 13036: # 13037: my ($height,$width,$xskip,$bar_width) = (200,120,1,15); 13038: if ($NumBars < 3) { 13039: $width = 120+$NumBars*32; 13040: $xskip = 1; 13041: $bar_width = 30; 13042: } elsif ($NumBars < 5) { 13043: $width = 120+$NumBars*20; 13044: $xskip = 1; 13045: $bar_width = 20; 13046: } elsif ($NumBars < 10) { 13047: $width = 120+$NumBars*15; 13048: $xskip = 1; 13049: $bar_width = 15; 13050: } elsif ($NumBars <= 25) { 13051: $width = 120+$NumBars*11; 13052: $xskip = 5; 13053: $bar_width = 8; 13054: } elsif ($NumBars <= 50) { 13055: $width = 120+$NumBars*8; 13056: $xskip = 5; 13057: $bar_width = 4; 13058: } else { 13059: $width = 120+$NumBars*8; 13060: $xskip = 5; 13061: $bar_width = 4; 13062: } 13063: # 13064: $Max = 1 if ($Max < 1); 13065: if ( int($Max) < $Max ) { 13066: $Max++; 13067: $Max = int($Max); 13068: } 13069: $Title = '' if (! defined($Title)); 13070: $xlabel = '' if (! defined($xlabel)); 13071: $ylabel = '' if (! defined($ylabel)); 13072: $ValuesHash{$id.'.title'} = &escape($Title); 13073: $ValuesHash{$id.'.xlabel'} = &escape($xlabel); 13074: $ValuesHash{$id.'.ylabel'} = &escape($ylabel); 13075: $ValuesHash{$id.'.y_max_value'} = $Max; 13076: $ValuesHash{$id.'.NumBars'} = $NumBars; 13077: $ValuesHash{$id.'.NumSets'} = $NumSets; 13078: $ValuesHash{$id.'.PlotType'} = 'bar'; 13079: $ValuesHash{$id.'.Colors'} = join(',',@{$colors}); 13080: $ValuesHash{$id.'.height'} = $height; 13081: $ValuesHash{$id.'.width'} = $width; 13082: $ValuesHash{$id.'.xskip'} = $xskip; 13083: $ValuesHash{$id.'.bar_width'} = $bar_width; 13084: $ValuesHash{$id.'.labels'} = join(',',@Labels); 13085: # 13086: # Deal with other parameters 13087: while (my ($key,$value) = each(%$extra_settings)) { 13088: $ValuesHash{$id.'.'.$key} = $value; 13089: } 13090: # 13091: &Apache::lonnet::appenv(\%ValuesHash); 13092: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />'; 13093: } 13094: 13095: ############################################################ 13096: ############################################################ 13097: 13098: =pod 13099: 13100: =item * &DrawXYGraph() 13101: 13102: Facilitates the plotting of data in an XY graph. 13103: Puts plot definition data into the users environment in order for 13104: graph.png to plot it. Returns an <img> tag for the plot. 13105: 13106: Inputs: 13107: 13108: =over 4 13109: 13110: =item $Title: string, the title of the plot 13111: 13112: =item $xlabel: string, text describing the X-axis of the plot 13113: 13114: =item $ylabel: string, text describing the Y-axis of the plot 13115: 13116: =item $Max: scalar, the maximum Y value to use in the plot 13117: If $Max is < any data point, the graph will not be rendered. 13118: 13119: =item $colors: Array ref containing the hex color codes for the data to be 13120: plotted in. If undefined, default values will be used. 13121: 13122: =item $Xlabels: Array ref containing the labels to be used for the X-axis. 13123: 13124: =item $Ydata: Array ref containing Array refs. 13125: Each of the contained arrays will be plotted as a separate curve. 13126: 13127: =item %Values: hash indicating or overriding any default values which are 13128: passed to graph.png. 13129: Possible values are: width, xskip, x_ticks, x_tick_offset, among others. 13130: 13131: =back 13132: 13133: Returns: 13134: 13135: An <img> tag which references graph.png and the appropriate identifying 13136: information for the plot. 13137: 13138: =cut 13139: 13140: ############################################################ 13141: ############################################################ 13142: sub DrawXYGraph { 13143: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_; 13144: # 13145: # Create the identifier for the graph 13146: my $identifier = &get_cgi_id(); 13147: my $id = 'cgi.'.$identifier; 13148: # 13149: $Title = '' if (! defined($Title)); 13150: $xlabel = '' if (! defined($xlabel)); 13151: $ylabel = '' if (! defined($ylabel)); 13152: my %ValuesHash = 13153: ( 13154: $id.'.title' => &escape($Title), 13155: $id.'.xlabel' => &escape($xlabel), 13156: $id.'.ylabel' => &escape($ylabel), 13157: $id.'.y_max_value'=> $Max, 13158: $id.'.labels' => join(',',@$Xlabels), 13159: $id.'.PlotType' => 'XY', 13160: ); 13161: # 13162: if (defined($colors) && ref($colors) eq 'ARRAY') { 13163: $ValuesHash{$id.'.Colors'} = join(',',@{$colors}); 13164: } 13165: # 13166: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') { 13167: return ''; 13168: } 13169: my $NumSets=1; 13170: foreach my $array (@{$Ydata}){ 13171: next if (! ref($array)); 13172: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array); 13173: } 13174: $ValuesHash{$id.'.NumSets'} = $NumSets-1; 13175: # 13176: # Deal with other parameters 13177: while (my ($key,$value) = each(%Values)) { 13178: $ValuesHash{$id.'.'.$key} = $value; 13179: } 13180: # 13181: &Apache::lonnet::appenv(\%ValuesHash); 13182: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />'; 13183: } 13184: 13185: ############################################################ 13186: ############################################################ 13187: 13188: =pod 13189: 13190: =item * &DrawXYYGraph() 13191: 13192: Facilitates the plotting of data in an XY graph with two Y axes. 13193: Puts plot definition data into the users environment in order for 13194: graph.png to plot it. Returns an <img> tag for the plot. 13195: 13196: Inputs: 13197: 13198: =over 4 13199: 13200: =item $Title: string, the title of the plot 13201: 13202: =item $xlabel: string, text describing the X-axis of the plot 13203: 13204: =item $ylabel: string, text describing the Y-axis of the plot 13205: 13206: =item $colors: Array ref containing the hex color codes for the data to be 13207: plotted in. If undefined, default values will be used. 13208: 13209: =item $Xlabels: Array ref containing the labels to be used for the X-axis. 13210: 13211: =item $Ydata1: The first data set 13212: 13213: =item $Min1: The minimum value of the left Y-axis 13214: 13215: =item $Max1: The maximum value of the left Y-axis 13216: 13217: =item $Ydata2: The second data set 13218: 13219: =item $Min2: The minimum value of the right Y-axis 13220: 13221: =item $Max2: The maximum value of the left Y-axis 13222: 13223: =item %Values: hash indicating or overriding any default values which are 13224: passed to graph.png. 13225: Possible values are: width, xskip, x_ticks, x_tick_offset, among others. 13226: 13227: =back 13228: 13229: Returns: 13230: 13231: An <img> tag which references graph.png and the appropriate identifying 13232: information for the plot. 13233: 13234: =cut 13235: 13236: ############################################################ 13237: ############################################################ 13238: sub DrawXYYGraph { 13239: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1, 13240: $Ydata2,$Min2,$Max2,%Values)=@_; 13241: # 13242: # Create the identifier for the graph 13243: my $identifier = &get_cgi_id(); 13244: my $id = 'cgi.'.$identifier; 13245: # 13246: $Title = '' if (! defined($Title)); 13247: $xlabel = '' if (! defined($xlabel)); 13248: $ylabel = '' if (! defined($ylabel)); 13249: my %ValuesHash = 13250: ( 13251: $id.'.title' => &escape($Title), 13252: $id.'.xlabel' => &escape($xlabel), 13253: $id.'.ylabel' => &escape($ylabel), 13254: $id.'.labels' => join(',',@$Xlabels), 13255: $id.'.PlotType' => 'XY', 13256: $id.'.NumSets' => 2, 13257: $id.'.two_axes' => 1, 13258: $id.'.y1_max_value' => $Max1, 13259: $id.'.y1_min_value' => $Min1, 13260: $id.'.y2_max_value' => $Max2, 13261: $id.'.y2_min_value' => $Min2, 13262: ); 13263: # 13264: if (defined($colors) && ref($colors) eq 'ARRAY') { 13265: $ValuesHash{$id.'.Colors'} = join(',',@{$colors}); 13266: } 13267: # 13268: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' || 13269: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){ 13270: return ''; 13271: } 13272: my $NumSets=1; 13273: foreach my $array ($Ydata1,$Ydata2){ 13274: next if (! ref($array)); 13275: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array); 13276: } 13277: # 13278: # Deal with other parameters 13279: while (my ($key,$value) = each(%Values)) { 13280: $ValuesHash{$id.'.'.$key} = $value; 13281: } 13282: # 13283: &Apache::lonnet::appenv(\%ValuesHash); 13284: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />'; 13285: } 13286: 13287: ############################################################ 13288: ############################################################ 13289: 13290: =pod 13291: 13292: =back 13293: 13294: =head1 Statistics helper routines? 13295: 13296: Bad place for them but what the hell. 13297: 13298: =over 4 13299: 13300: =item * &chartlink() 13301: 13302: Returns a link to the chart for a specific student. 13303: 13304: Inputs: 13305: 13306: =over 4 13307: 13308: =item $linktext: The text of the link 13309: 13310: =item $sname: The students username 13311: 13312: =item $sdomain: The students domain 13313: 13314: =back 13315: 13316: =back 13317: 13318: =cut 13319: 13320: ############################################################ 13321: ############################################################ 13322: sub chartlink { 13323: my ($linktext, $sname, $sdomain) = @_; 13324: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'. 13325: '&SelectedStudent='.&escape($sname.':'.$sdomain). 13326: '&chartoutputmode='.HTML::Entities::encode('html, with all links'). 13327: '">'.$linktext.'</a>'; 13328: } 13329: 13330: ####################################################### 13331: ####################################################### 13332: 13333: =pod 13334: 13335: =head1 Course Environment Routines 13336: 13337: =over 4 13338: 13339: =item * &restore_course_settings() 13340: 13341: =item * &store_course_settings() 13342: 13343: Restores/Store indicated form parameters from the course environment. 13344: Will not overwrite existing values of the form parameters. 13345: 13346: Inputs: 13347: a scalar describing the data (e.g. 'chart', 'problem_analysis') 13348: 13349: a hash ref describing the data to be stored. For example: 13350: 13351: %Save_Parameters = ('Status' => 'scalar', 13352: 'chartoutputmode' => 'scalar', 13353: 'chartoutputdata' => 'scalar', 13354: 'Section' => 'array', 13355: 'Group' => 'array', 13356: 'StudentData' => 'array', 13357: 'Maps' => 'array'); 13358: 13359: Returns: both routines return nothing 13360: 13361: =back 13362: 13363: =cut 13364: 13365: ####################################################### 13366: ####################################################### 13367: sub store_course_settings { 13368: return &store_settings($env{'request.course.id'},@_); 13369: } 13370: 13371: sub store_settings { 13372: # save to the environment 13373: # appenv the same items, just to be safe 13374: my $udom = $env{'user.domain'}; 13375: my $uname = $env{'user.name'}; 13376: my ($context,$prefix,$Settings) = @_; 13377: my %SaveHash; 13378: my %AppHash; 13379: while (my ($setting,$type) = each(%$Settings)) { 13380: my $basename = join('.','internal',$context,$prefix,$setting); 13381: my $envname = 'environment.'.$basename; 13382: if (exists($env{'form.'.$setting})) { 13383: # Save this value away 13384: if ($type eq 'scalar' && 13385: (! exists($env{$envname}) || 13386: $env{$envname} ne $env{'form.'.$setting})) { 13387: $SaveHash{$basename} = $env{'form.'.$setting}; 13388: $AppHash{$envname} = $env{'form.'.$setting}; 13389: } elsif ($type eq 'array') { 13390: my $stored_form; 13391: if (ref($env{'form.'.$setting})) { 13392: $stored_form = join(',', 13393: map { 13394: &escape($_); 13395: } sort(@{$env{'form.'.$setting}})); 13396: } else { 13397: $stored_form = 13398: &escape($env{'form.'.$setting}); 13399: } 13400: # Determine if the array contents are the same. 13401: if ($stored_form ne $env{$envname}) { 13402: $SaveHash{$basename} = $stored_form; 13403: $AppHash{$envname} = $stored_form; 13404: } 13405: } 13406: } 13407: } 13408: my $put_result = &Apache::lonnet::put('environment',\%SaveHash, 13409: $udom,$uname); 13410: if ($put_result !~ /^(ok|delayed)/) { 13411: &Apache::lonnet::logthis('unable to save form parameters, '. 13412: 'got error:'.$put_result); 13413: } 13414: # Make sure these settings stick around in this session, too 13415: &Apache::lonnet::appenv(\%AppHash); 13416: return; 13417: } 13418: 13419: sub restore_course_settings { 13420: return &restore_settings($env{'request.course.id'},@_); 13421: } 13422: 13423: sub restore_settings { 13424: my ($context,$prefix,$Settings) = @_; 13425: while (my ($setting,$type) = each(%$Settings)) { 13426: next if (exists($env{'form.'.$setting})); 13427: my $envname = 'environment.internal.'.$context.'.'.$prefix. 13428: '.'.$setting; 13429: if (exists($env{$envname})) { 13430: if ($type eq 'scalar') { 13431: $env{'form.'.$setting} = $env{$envname}; 13432: } elsif ($type eq 'array') { 13433: $env{'form.'.$setting} = [ 13434: map { 13435: &unescape($_); 13436: } split(',',$env{$envname}) 13437: ]; 13438: } 13439: } 13440: } 13441: } 13442: 13443: ####################################################### 13444: ####################################################### 13445: 13446: =pod 13447: 13448: =head1 Domain E-mail Routines 13449: 13450: =over 4 13451: 13452: =item * &build_recipient_list() 13453: 13454: Build recipient lists for following types of e-mail: 13455: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors 13456: (d) Help requests, (e) Course requests needing approval, (f) loncapa 13457: module change checking, student/employee ID conflict checks, as 13458: generated by lonerrorhandler.pm, CHECKRPMS, loncron, 13459: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively. 13460: 13461: Inputs: 13462: defmail (scalar - email address of default recipient), 13463: mailing type (scalar: errormail, packagesmail, helpdeskmail, 13464: requestsmail, updatesmail, or idconflictsmail). 13465: 13466: defdom (domain for which to retrieve configuration settings), 13467: 13468: origmail (scalar - email address of recipient from loncapa.conf, 13469: i.e., predates configuration by DC via domainprefs.pm 13470: 13471: Returns: comma separated list of addresses to which to send e-mail. 13472: 13473: =back 13474: 13475: =cut 13476: 13477: ############################################################ 13478: ############################################################ 13479: sub build_recipient_list { 13480: my ($defmail,$mailing,$defdom,$origmail) = @_; 13481: my @recipients; 13482: my $otheremails; 13483: my %domconfig = 13484: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom); 13485: if (ref($domconfig{'contacts'}) eq 'HASH') { 13486: if (exists($domconfig{'contacts'}{$mailing})) { 13487: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') { 13488: my @contacts = ('adminemail','supportemail'); 13489: foreach my $item (@contacts) { 13490: if ($domconfig{'contacts'}{$mailing}{$item}) { 13491: my $addr = $domconfig{'contacts'}{$item}; 13492: if (!grep(/^\Q$addr\E$/,@recipients)) { 13493: push(@recipients,$addr); 13494: } 13495: } 13496: $otheremails = $domconfig{'contacts'}{$mailing}{'others'}; 13497: } 13498: } 13499: } elsif ($origmail ne '') { 13500: push(@recipients,$origmail); 13501: } 13502: } elsif ($origmail ne '') { 13503: push(@recipients,$origmail); 13504: } 13505: if (defined($defmail)) { 13506: if ($defmail ne '') { 13507: push(@recipients,$defmail); 13508: } 13509: } 13510: if ($otheremails) { 13511: my @others; 13512: if ($otheremails =~ /,/) { 13513: @others = split(/,/,$otheremails); 13514: } else { 13515: push(@others,$otheremails); 13516: } 13517: foreach my $addr (@others) { 13518: if (!grep(/^\Q$addr\E$/,@recipients)) { 13519: push(@recipients,$addr); 13520: } 13521: } 13522: } 13523: my $recipientlist = join(',',@recipients); 13524: return $recipientlist; 13525: } 13526: 13527: ############################################################ 13528: ############################################################ 13529: 13530: =pod 13531: 13532: =head1 Course Catalog Routines 13533: 13534: =over 4 13535: 13536: =item * &gather_categories() 13537: 13538: Converts category definitions - keys of categories hash stored in 13539: coursecategories in configuration.db on the primary library server in a 13540: domain - to an array. Also generates javascript and idx hash used to 13541: generate Domain Coordinator interface for editing Course Categories. 13542: 13543: Inputs: 13544: 13545: categories (reference to hash of category definitions). 13546: 13547: cats (reference to array of arrays/hashes which encapsulates hierarchy of 13548: categories and subcategories). 13549: 13550: idx (reference to hash of counters used in Domain Coordinator interface for 13551: editing Course Categories). 13552: 13553: jsarray (reference to array of categories used to create Javascript arrays for 13554: Domain Coordinator interface for editing Course Categories). 13555: 13556: Returns: nothing 13557: 13558: Side effects: populates cats, idx and jsarray. 13559: 13560: =cut 13561: 13562: sub gather_categories { 13563: my ($categories,$cats,$idx,$jsarray) = @_; 13564: my %counters; 13565: my $num = 0; 13566: foreach my $item (keys(%{$categories})) { 13567: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item); 13568: if ($container eq '' && $depth == 0) { 13569: $cats->[$depth][$categories->{$item}] = $cat; 13570: } else { 13571: $cats->[$depth]{$container}[$categories->{$item}] = $cat; 13572: } 13573: my ($escitem,$tail) = split(/:/,$item,2); 13574: if ($counters{$tail} eq '') { 13575: $counters{$tail} = $num; 13576: $num ++; 13577: } 13578: if (ref($idx) eq 'HASH') { 13579: $idx->{$item} = $counters{$tail}; 13580: } 13581: if (ref($jsarray) eq 'ARRAY') { 13582: push(@{$jsarray->[$counters{$tail}]},$item); 13583: } 13584: } 13585: return; 13586: } 13587: 13588: =pod 13589: 13590: =item * &extract_categories() 13591: 13592: Used to generate breadcrumb trails for course categories. 13593: 13594: Inputs: 13595: 13596: categories (reference to hash of category definitions). 13597: 13598: cats (reference to array of arrays/hashes which encapsulates hierarchy of 13599: categories and subcategories). 13600: 13601: trails (reference to array of breacrumb trails for each category). 13602: 13603: allitems (reference to hash - key is category key 13604: (format: escaped(name):escaped(parent category):depth in hierarchy). 13605: 13606: idx (reference to hash of counters used in Domain Coordinator interface for 13607: editing Course Categories). 13608: 13609: jsarray (reference to array of categories used to create Javascript arrays for 13610: Domain Coordinator interface for editing Course Categories). 13611: 13612: subcats (reference to hash of arrays containing all subcategories within each 13613: category, -recursive) 13614: 13615: Returns: nothing 13616: 13617: Side effects: populates trails and allitems hash references. 13618: 13619: =cut 13620: 13621: sub extract_categories { 13622: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_; 13623: if (ref($categories) eq 'HASH') { 13624: &gather_categories($categories,$cats,$idx,$jsarray); 13625: if (ref($cats->[0]) eq 'ARRAY') { 13626: for (my $i=0; $i<@{$cats->[0]}; $i++) { 13627: my $name = $cats->[0][$i]; 13628: my $item = &escape($name).'::0'; 13629: my $trailstr; 13630: if ($name eq 'instcode') { 13631: $trailstr = &mt('Official courses (with institutional codes)'); 13632: } elsif ($name eq 'communities') { 13633: $trailstr = &mt('Communities'); 13634: } else { 13635: $trailstr = $name; 13636: } 13637: if ($allitems->{$item} eq '') { 13638: push(@{$trails},$trailstr); 13639: $allitems->{$item} = scalar(@{$trails})-1; 13640: } 13641: my @parents = ($name); 13642: if (ref($cats->[1]{$name}) eq 'ARRAY') { 13643: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) { 13644: my $category = $cats->[1]{$name}[$j]; 13645: if (ref($subcats) eq 'HASH') { 13646: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1'); 13647: } 13648: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats); 13649: } 13650: } else { 13651: if (ref($subcats) eq 'HASH') { 13652: $subcats->{$item} = []; 13653: } 13654: } 13655: } 13656: } 13657: } 13658: return; 13659: } 13660: 13661: =pod 13662: 13663: =item * &recurse_categories() 13664: 13665: Recursively used to generate breadcrumb trails for course categories. 13666: 13667: Inputs: 13668: 13669: cats (reference to array of arrays/hashes which encapsulates hierarchy of 13670: categories and subcategories). 13671: 13672: depth (current depth in hierarchy of categories and sub-categories - 0 indexed). 13673: 13674: category (current course category, for which breadcrumb trail is being generated). 13675: 13676: trails (reference to array of breadcrumb trails for each category). 13677: 13678: allitems (reference to hash - key is category key 13679: (format: escaped(name):escaped(parent category):depth in hierarchy). 13680: 13681: parents (array containing containers directories for current category, 13682: back to top level). 13683: 13684: Returns: nothing 13685: 13686: Side effects: populates trails and allitems hash references 13687: 13688: =cut 13689: 13690: sub recurse_categories { 13691: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_; 13692: my $shallower = $depth - 1; 13693: if (ref($cats->[$depth]{$category}) eq 'ARRAY') { 13694: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) { 13695: my $name = $cats->[$depth]{$category}[$k]; 13696: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower; 13697: my $trailstr = join(' -> ',(@{$parents},$category)); 13698: if ($allitems->{$item} eq '') { 13699: push(@{$trails},$trailstr); 13700: $allitems->{$item} = scalar(@{$trails})-1; 13701: } 13702: my $deeper = $depth+1; 13703: push(@{$parents},$category); 13704: if (ref($subcats) eq 'HASH') { 13705: my $subcat = &escape($name).':'.$category.':'.$depth; 13706: for (my $j=@{$parents}; $j>=0; $j--) { 13707: my $higher; 13708: if ($j > 0) { 13709: $higher = &escape($parents->[$j]).':'. 13710: &escape($parents->[$j-1]).':'.$j; 13711: } else { 13712: $higher = &escape($parents->[$j]).'::'.$j; 13713: } 13714: push(@{$subcats->{$higher}},$subcat); 13715: } 13716: } 13717: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents, 13718: $subcats); 13719: pop(@{$parents}); 13720: } 13721: } else { 13722: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower; 13723: my $trailstr = join(' -> ',(@{$parents},$category)); 13724: if ($allitems->{$item} eq '') { 13725: push(@{$trails},$trailstr); 13726: $allitems->{$item} = scalar(@{$trails})-1; 13727: } 13728: } 13729: return; 13730: } 13731: 13732: =pod 13733: 13734: =item * &assign_categories_table() 13735: 13736: Create a datatable for display of hierarchical categories in a domain, 13737: with checkboxes to allow a course to be categorized. 13738: 13739: Inputs: 13740: 13741: cathash - reference to hash of categories defined for the domain (from 13742: configuration.db) 13743: 13744: currcat - scalar with an & separated list of categories assigned to a course. 13745: 13746: type - scalar contains course type (Course or Community). 13747: 13748: Returns: $output (markup to be displayed) 13749: 13750: =cut 13751: 13752: sub assign_categories_table { 13753: my ($cathash,$currcat,$type) = @_; 13754: my $output; 13755: if (ref($cathash) eq 'HASH') { 13756: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth); 13757: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray); 13758: $maxdepth = scalar(@cats); 13759: if (@cats > 0) { 13760: my $itemcount = 0; 13761: if (ref($cats[0]) eq 'ARRAY') { 13762: my @currcategories; 13763: if ($currcat ne '') { 13764: @currcategories = split('&',$currcat); 13765: } 13766: my $table; 13767: for (my $i=0; $i<@{$cats[0]}; $i++) { 13768: my $parent = $cats[0][$i]; 13769: next if ($parent eq 'instcode'); 13770: if ($type eq 'Community') { 13771: next unless ($parent eq 'communities'); 13772: } else { 13773: next if ($parent eq 'communities'); 13774: } 13775: my $css_class = $itemcount%2?' class="LC_odd_row"':''; 13776: my $item = &escape($parent).'::0'; 13777: my $checked = ''; 13778: if (@currcategories > 0) { 13779: if (grep(/^\Q$item\E$/,@currcategories)) { 13780: $checked = ' checked="checked"'; 13781: } 13782: } 13783: my $parent_title = $parent; 13784: if ($parent eq 'communities') { 13785: $parent_title = &mt('Communities'); 13786: } 13787: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'. 13788: '<input type="checkbox" name="usecategory" value="'. 13789: $item.'"'.$checked.' />'.$parent_title.'</span>'. 13790: '<input type="hidden" name="catname" value="'.$parent.'" /></td>'; 13791: my $depth = 1; 13792: push(@path,$parent); 13793: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories); 13794: pop(@path); 13795: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>'; 13796: $itemcount ++; 13797: } 13798: if ($itemcount) { 13799: $output = &Apache::loncommon::start_data_table(). 13800: $table. 13801: &Apache::loncommon::end_data_table(); 13802: } 13803: } 13804: } 13805: } 13806: return $output; 13807: } 13808: 13809: =pod 13810: 13811: =item * &assign_category_rows() 13812: 13813: Create a datatable row for display of nested categories in a domain, 13814: with checkboxes to allow a course to be categorized,called recursively. 13815: 13816: Inputs: 13817: 13818: itemcount - track row number for alternating colors 13819: 13820: cats - reference to array of arrays/hashes which encapsulates hierarchy of 13821: categories and subcategories. 13822: 13823: depth - current depth in hierarchy of categories and sub-categories - 0 indexed. 13824: 13825: parent - parent of current category item 13826: 13827: path - Array containing all categories back up through the hierarchy from the 13828: current category to the top level. 13829: 13830: currcategories - reference to array of current categories assigned to the course 13831: 13832: Returns: $output (markup to be displayed). 13833: 13834: =cut 13835: 13836: sub assign_category_rows { 13837: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_; 13838: my ($text,$name,$item,$chgstr); 13839: if (ref($cats) eq 'ARRAY') { 13840: my $maxdepth = scalar(@{$cats}); 13841: if (ref($cats->[$depth]) eq 'HASH') { 13842: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') { 13843: my $numchildren = @{$cats->[$depth]{$parent}}; 13844: my $css_class = $itemcount%2?' class="LC_odd_row"':''; 13845: $text .= '<td><table class="LC_data_table">'; 13846: for (my $j=0; $j<$numchildren; $j++) { 13847: $name = $cats->[$depth]{$parent}[$j]; 13848: $item = &escape($name).':'.&escape($parent).':'.$depth; 13849: my $deeper = $depth+1; 13850: my $checked = ''; 13851: if (ref($currcategories) eq 'ARRAY') { 13852: if (@{$currcategories} > 0) { 13853: if (grep(/^\Q$item\E$/,@{$currcategories})) { 13854: $checked = ' checked="checked"'; 13855: } 13856: } 13857: } 13858: $text .= '<tr><td><span class="LC_nobreak"><label>'. 13859: '<input type="checkbox" name="usecategory" value="'. 13860: $item.'"'.$checked.' />'.$name.'</label></span>'. 13861: '<input type="hidden" name="catname" value="'.$name.'" />'. 13862: '</td><td>'; 13863: if (ref($path) eq 'ARRAY') { 13864: push(@{$path},$name); 13865: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories); 13866: pop(@{$path}); 13867: } 13868: $text .= '</td></tr>'; 13869: } 13870: $text .= '</table></td>'; 13871: } 13872: } 13873: } 13874: return $text; 13875: } 13876: 13877: =pod 13878: 13879: =back 13880: 13881: =cut 13882: 13883: ############################################################ 13884: ############################################################ 13885: 13886: 13887: sub commit_customrole { 13888: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_; 13889: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url. 13890: ($start?', '.&mt('starting').' '.localtime($start):''). 13891: ($end?', ending '.localtime($end):'').': <b>'. 13892: &Apache::lonnet::assigncustomrole( 13893: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context). 13894: '</b><br />'; 13895: return $output; 13896: } 13897: 13898: sub commit_standardrole { 13899: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_; 13900: my ($output,$logmsg,$linefeed); 13901: if ($context eq 'auto') { 13902: $linefeed = "\n"; 13903: } else { 13904: $linefeed = "<br />\n"; 13905: } 13906: if ($three eq 'st') { 13907: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end, 13908: $one,$two,$sec,$context,$credits); 13909: if (($result =~ /^error/) || ($result eq 'not_in_class') || 13910: ($result eq 'unknown_course') || ($result eq 'refused')) { 13911: $output = $logmsg.' '.&mt('Error: ').$result."\n"; 13912: } else { 13913: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url. 13914: ($start?', '.&mt('starting').' '.localtime($start):''). 13915: ($end?', '.&mt('ending').' '.localtime($end):'').': '; 13916: if ($context eq 'auto') { 13917: $output .= $result.$linefeed.&mt('Add to classlist').': ok'; 13918: } else { 13919: $output .= '<b>'.$result.'</b>'.$linefeed. 13920: &mt('Add to classlist').': <b>ok</b>'; 13921: } 13922: $output .= $linefeed; 13923: } 13924: } else { 13925: $output = &mt('Assigning').' '.$three.' in '.$url. 13926: ($start?', '.&mt('starting').' '.localtime($start):''). 13927: ($end?', '.&mt('ending').' '.localtime($end):'').': '; 13928: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context); 13929: if ($context eq 'auto') { 13930: $output .= $result.$linefeed; 13931: } else { 13932: $output .= '<b>'.$result.'</b>'.$linefeed; 13933: } 13934: } 13935: return $output; 13936: } 13937: 13938: sub commit_studentrole { 13939: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context, 13940: $credits) = @_; 13941: my ($result,$linefeed,$oldsecurl,$newsecurl); 13942: if ($context eq 'auto') { 13943: $linefeed = "\n"; 13944: } else { 13945: $linefeed = '<br />'."\n"; 13946: } 13947: if (defined($one) && defined($two)) { 13948: my $cid=$one.'_'.$two; 13949: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid); 13950: my $secchange = 0; 13951: my $expire_role_result; 13952: my $modify_section_result; 13953: if ($oldsec ne '-1') { 13954: if ($oldsec ne $sec) { 13955: $secchange = 1; 13956: my $now = time; 13957: my $uurl='/'.$cid; 13958: $uurl=~s/\_/\//g; 13959: if ($oldsec) { 13960: $uurl.='/'.$oldsec; 13961: } 13962: $oldsecurl = $uurl; 13963: $expire_role_result = 13964: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context); 13965: if ($env{'request.course.sec'} ne '') { 13966: if ($expire_role_result eq 'refused') { 13967: my @roles = ('st'); 13968: my @statuses = ('previous'); 13969: my @roledoms = ($one); 13970: my $withsec = 1; 13971: my %roleshash = 13972: &Apache::lonnet::get_my_roles($uname,$udom,'userroles', 13973: \@statuses,\@roles,\@roledoms,$withsec); 13974: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) { 13975: my ($oldstart,$oldend) = 13976: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec}); 13977: if ($oldend > 0 && $oldend <= $now) { 13978: $expire_role_result = 'ok'; 13979: } 13980: } 13981: } 13982: } 13983: $result = $expire_role_result; 13984: } 13985: } 13986: if (($expire_role_result eq 'ok') || ($secchange == 0)) { 13987: $modify_section_result = 13988: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef, 13989: undef,undef,undef,$sec, 13990: $end,$start,'','',$cid, 13991: '',$context,$credits); 13992: if ($modify_section_result =~ /^ok/) { 13993: if ($secchange == 1) { 13994: if ($sec eq '') { 13995: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed; 13996: } else { 13997: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed; 13998: } 13999: } elsif ($oldsec eq '-1') { 14000: if ($sec eq '') { 14001: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed; 14002: } else { 14003: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed; 14004: } 14005: } else { 14006: if ($sec eq '') { 14007: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed; 14008: } else { 14009: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed; 14010: } 14011: } 14012: } else { 14013: if ($secchange) { 14014: $$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; 14015: } else { 14016: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed; 14017: } 14018: } 14019: $result = $modify_section_result; 14020: } elsif ($secchange == 1) { 14021: if ($oldsec eq '') { 14022: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed; 14023: } else { 14024: $$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; 14025: } 14026: if ($expire_role_result eq 'refused') { 14027: my $newsecurl = '/'.$cid; 14028: $newsecurl =~ s/\_/\//g; 14029: if ($sec ne '') { 14030: $newsecurl.='/'.$sec; 14031: } 14032: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) { 14033: if ($sec eq '') { 14034: $$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; 14035: } else { 14036: $$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; 14037: } 14038: } 14039: } 14040: } 14041: } else { 14042: $$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; 14043: $result = "error: incomplete course id\n"; 14044: } 14045: return $result; 14046: } 14047: 14048: sub show_role_extent { 14049: my ($scope,$context,$role) = @_; 14050: $scope =~ s{^/}{}; 14051: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1); 14052: push(@courseroles,'co'); 14053: my @authorroles = &Apache::lonuserutils::roles_by_context('author'); 14054: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) { 14055: $scope =~ s{/}{_}; 14056: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>'; 14057: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) { 14058: my ($audom,$auname) = split(/\//,$scope); 14059: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'. 14060: &Apache::loncommon::plainname($auname,$audom).'</span>'); 14061: } else { 14062: $scope =~ s{/$}{}; 14063: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'. 14064: &Apache::lonnet::domain($scope,'description').'</span>'); 14065: } 14066: } 14067: 14068: ############################################################ 14069: ############################################################ 14070: 14071: sub check_clone { 14072: my ($args,$linefeed) = @_; 14073: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'}; 14074: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid); 14075: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom); 14076: my $clonemsg; 14077: my $can_clone = 0; 14078: my $lctype = lc($args->{'crstype'}); 14079: if ($lctype ne 'community') { 14080: $lctype = 'course'; 14081: } 14082: if ($clonehome eq 'no_host') { 14083: if ($args->{'crstype'} eq 'Community') { 14084: $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'}); 14085: } else { 14086: $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'}); 14087: } 14088: } else { 14089: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1}); 14090: if ($args->{'crstype'} eq 'Community') { 14091: if ($clonedesc{'type'} ne 'Community') { 14092: $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'}); 14093: return ($can_clone, $clonemsg, $cloneid, $clonehome); 14094: } 14095: } 14096: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 14097: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) { 14098: $can_clone = 1; 14099: } else { 14100: my %clonehash = &Apache::lonnet::get('environment',['cloners'], 14101: $args->{'clonedomain'},$args->{'clonecourse'}); 14102: my @cloners = split(/,/,$clonehash{'cloners'}); 14103: if (grep(/^\*$/,@cloners)) { 14104: $can_clone = 1; 14105: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) { 14106: $can_clone = 1; 14107: } else { 14108: my $ccrole = 'cc'; 14109: if ($args->{'crstype'} eq 'Community') { 14110: $ccrole = 'co'; 14111: } 14112: my %roleshash = 14113: &Apache::lonnet::get_my_roles($args->{'ccuname'}, 14114: $args->{'ccdomain'}, 14115: 'userroles',['active'],[$ccrole], 14116: [$args->{'clonedomain'}]); 14117: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) { 14118: $can_clone = 1; 14119: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) { 14120: $can_clone = 1; 14121: } else { 14122: if ($args->{'crstype'} eq 'Community') { 14123: $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'}); 14124: } else { 14125: $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'}); 14126: } 14127: } 14128: } 14129: } 14130: } 14131: return ($can_clone, $clonemsg, $cloneid, $clonehome); 14132: } 14133: 14134: sub construct_course { 14135: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_; 14136: my $outcome; 14137: my $linefeed = '<br />'."\n"; 14138: if ($context eq 'auto') { 14139: $linefeed = "\n"; 14140: } 14141: 14142: # 14143: # Are we cloning? 14144: # 14145: my ($can_clone, $clonemsg, $cloneid, $clonehome); 14146: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) { 14147: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed); 14148: if ($context ne 'auto') { 14149: if ($clonemsg ne '') { 14150: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>'; 14151: } 14152: } 14153: $outcome .= $clonemsg.$linefeed; 14154: 14155: if (!$can_clone) { 14156: return (0,$outcome); 14157: } 14158: } 14159: 14160: # 14161: # Open course 14162: # 14163: my $crstype = lc($args->{'crstype'}); 14164: my %cenv=(); 14165: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'}, 14166: $args->{'cdescr'}, 14167: $args->{'curl'}, 14168: $args->{'course_home'}, 14169: $args->{'nonstandard'}, 14170: $args->{'crscode'}, 14171: $args->{'ccuname'}.':'. 14172: $args->{'ccdomain'}, 14173: $args->{'crstype'}, 14174: $cnum,$context,$category); 14175: 14176: # Note: The testing routines depend on this being output; see 14177: # Utils::Course. This needs to at least be output as a comment 14178: # if anyone ever decides to not show this, and Utils::Course::new 14179: # will need to be suitably modified. 14180: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed; 14181: if ($$courseid =~ /^error:/) { 14182: return (0,$outcome); 14183: } 14184: 14185: # 14186: # Check if created correctly 14187: # 14188: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid); 14189: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom); 14190: if ($crsuhome eq 'no_host') { 14191: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed; 14192: return (0,$outcome); 14193: } 14194: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed; 14195: 14196: # 14197: # Do the cloning 14198: # 14199: if ($can_clone && $cloneid) { 14200: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome); 14201: if ($context ne 'auto') { 14202: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>'; 14203: } 14204: $outcome .= $clonemsg.$linefeed; 14205: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum); 14206: # Copy all files 14207: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'}); 14208: # Restore URL 14209: $cenv{'url'}=$oldcenv{'url'}; 14210: # Restore title 14211: $cenv{'description'}=$oldcenv{'description'}; 14212: # Restore creation date, creator and creation context. 14213: $cenv{'internal.created'}=$oldcenv{'internal.created'}; 14214: $cenv{'internal.creator'}=$oldcenv{'internal.creator'}; 14215: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'}; 14216: # Mark as cloned 14217: $cenv{'clonedfrom'}=$cloneid; 14218: # Need to clone grading mode 14219: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum); 14220: $cenv{'grading'}=$newenv{'grading'}; 14221: # Do not clone these environment entries 14222: &Apache::lonnet::del('environment', 14223: ['default_enrollment_start_date', 14224: 'default_enrollment_end_date', 14225: 'question.email', 14226: 'policy.email', 14227: 'comment.email', 14228: 'pch.users.denied', 14229: 'plc.users.denied', 14230: 'hidefromcat', 14231: 'checkforpriv', 14232: 'categories', 14233: 'internal.uniquecode'], 14234: $$crsudom,$$crsunum); 14235: if ($args->{'textbook'}) { 14236: $cenv{'internal.textbook'} = $args->{'textbook'}; 14237: } 14238: } 14239: 14240: # 14241: # Set environment (will override cloned, if existing) 14242: # 14243: my @sections = (); 14244: my @xlists = (); 14245: if ($args->{'crstype'}) { 14246: $cenv{'type'}=$args->{'crstype'}; 14247: } 14248: if ($args->{'crsid'}) { 14249: $cenv{'courseid'}=$args->{'crsid'}; 14250: } 14251: if ($args->{'crscode'}) { 14252: $cenv{'internal.coursecode'}=$args->{'crscode'}; 14253: } 14254: if ($args->{'crsquota'} ne '') { 14255: $cenv{'internal.coursequota'}=$args->{'crsquota'}; 14256: } else { 14257: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20; 14258: } 14259: if ($args->{'ccuname'}) { 14260: $cenv{'internal.courseowner'} = $args->{'ccuname'}. 14261: ':'.$args->{'ccdomain'}; 14262: } else { 14263: $cenv{'internal.courseowner'} = $args->{'curruser'}; 14264: } 14265: if ($args->{'defaultcredits'}) { 14266: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'}; 14267: } 14268: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner. 14269: if ($args->{'crssections'}) { 14270: $cenv{'internal.sectionnums'} = ''; 14271: if ($args->{'crssections'} =~ m/,/) { 14272: @sections = split/,/,$args->{'crssections'}; 14273: } else { 14274: $sections[0] = $args->{'crssections'}; 14275: } 14276: if (@sections > 0) { 14277: foreach my $item (@sections) { 14278: my ($sec,$gp) = split/:/,$item; 14279: my $class = $args->{'crscode'}.$sec; 14280: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'}); 14281: $cenv{'internal.sectionnums'} .= $item.','; 14282: unless ($addcheck eq 'ok') { 14283: push @badclasses, $class; 14284: } 14285: } 14286: $cenv{'internal.sectionnums'} =~ s/,$//; 14287: } 14288: } 14289: # do not hide course coordinator from staff listing, 14290: # even if privileged 14291: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'}; 14292: # add course coordinator's domain to domains to check for privileged users 14293: # if different to course domain 14294: if ($$crsudom ne $args->{'ccdomain'}) { 14295: $cenv{'checkforpriv'} = $args->{'ccdomain'}; 14296: } 14297: # add crosslistings 14298: if ($args->{'crsxlist'}) { 14299: $cenv{'internal.crosslistings'}=''; 14300: if ($args->{'crsxlist'} =~ m/,/) { 14301: @xlists = split/,/,$args->{'crsxlist'}; 14302: } else { 14303: $xlists[0] = $args->{'crsxlist'}; 14304: } 14305: if (@xlists > 0) { 14306: foreach my $item (@xlists) { 14307: my ($xl,$gp) = split/:/,$item; 14308: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'}); 14309: $cenv{'internal.crosslistings'} .= $item.','; 14310: unless ($addcheck eq 'ok') { 14311: push @badclasses, $xl; 14312: } 14313: } 14314: $cenv{'internal.crosslistings'} =~ s/,$//; 14315: } 14316: } 14317: if ($args->{'autoadds'}) { 14318: $cenv{'internal.autoadds'}=$args->{'autoadds'}; 14319: } 14320: if ($args->{'autodrops'}) { 14321: $cenv{'internal.autodrops'}=$args->{'autodrops'}; 14322: } 14323: # check for notification of enrollment changes 14324: my @notified = (); 14325: if ($args->{'notify_owner'}) { 14326: if ($args->{'ccuname'} ne '') { 14327: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'}); 14328: } 14329: } 14330: if ($args->{'notify_dc'}) { 14331: if ($uname ne '') { 14332: push(@notified,$uname.':'.$udom); 14333: } 14334: } 14335: if (@notified > 0) { 14336: my $notifylist; 14337: if (@notified > 1) { 14338: $notifylist = join(',',@notified); 14339: } else { 14340: $notifylist = $notified[0]; 14341: } 14342: $cenv{'internal.notifylist'} = $notifylist; 14343: } 14344: if (@badclasses > 0) { 14345: my %lt=&Apache::lonlocal::texthash( 14346: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course. However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course', 14347: 'dnhr' => 'does not have rights to access enrollment in these classes', 14348: 'adby' => 'as determined by the policies of your institution on access to official classlists' 14349: ); 14350: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}. 14351: ' ('.$lt{'adby'}.')'; 14352: if ($context eq 'auto') { 14353: $outcome .= $badclass_msg.$linefeed; 14354: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n"; 14355: foreach my $item (@badclasses) { 14356: if ($context eq 'auto') { 14357: $outcome .= " - $item\n"; 14358: } else { 14359: $outcome .= "<li>$item</li>\n"; 14360: } 14361: } 14362: if ($context eq 'auto') { 14363: $outcome .= $linefeed; 14364: } else { 14365: $outcome .= "</ul><br /><br /></div>\n"; 14366: } 14367: } 14368: } 14369: if ($args->{'no_end_date'}) { 14370: $args->{'endaccess'} = 0; 14371: } 14372: $cenv{'internal.autostart'}=$args->{'enrollstart'}; 14373: $cenv{'internal.autoend'}=$args->{'enrollend'}; 14374: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'}; 14375: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'}; 14376: if ($args->{'showphotos'}) { 14377: $cenv{'internal.showphotos'}=$args->{'showphotos'}; 14378: } 14379: $cenv{'internal.authtype'} = $args->{'authtype'}; 14380: $cenv{'internal.autharg'} = $args->{'autharg'}; 14381: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) { 14382: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') { 14383: 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'); 14384: if ($context eq 'auto') { 14385: $outcome .= $krb_msg; 14386: } else { 14387: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>'; 14388: } 14389: $outcome .= $linefeed; 14390: } 14391: } 14392: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) { 14393: if ($args->{'setpolicy'}) { 14394: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'}; 14395: } 14396: if ($args->{'setcontent'}) { 14397: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'}; 14398: } 14399: } 14400: if ($args->{'reshome'}) { 14401: $cenv{'reshome'}=$args->{'reshome'}.'/'; 14402: $cenv{'reshome'}=~s/\/+$/\//; 14403: } 14404: # 14405: # course has keyed access 14406: # 14407: if ($args->{'setkeys'}) { 14408: $cenv{'keyaccess'}='yes'; 14409: } 14410: # if specified, key authority is not course, but user 14411: # only active if keyaccess is yes 14412: if ($args->{'keyauth'}) { 14413: my ($user,$domain) = split(':',$args->{'keyauth'}); 14414: $user = &LONCAPA::clean_username($user); 14415: $domain = &LONCAPA::clean_username($domain); 14416: if ($user ne '' && $domain ne '') { 14417: $cenv{'keyauth'}=$user.':'.$domain; 14418: } 14419: } 14420: 14421: # 14422: # generate and store uniquecode (available to course requester), if course should have one. 14423: # 14424: if ($args->{'uniquecode'}) { 14425: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum); 14426: if ($code) { 14427: $cenv{'internal.uniquecode'} = $code; 14428: my %crsinfo = 14429: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.'); 14430: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') { 14431: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code; 14432: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime'); 14433: } 14434: if (ref($coderef)) { 14435: $$coderef = $code; 14436: } 14437: } 14438: } 14439: 14440: if ($args->{'disresdis'}) { 14441: $cenv{'pch.roles.denied'}='st'; 14442: } 14443: if ($args->{'disablechat'}) { 14444: $cenv{'plc.roles.denied'}='st'; 14445: } 14446: 14447: # Record we've not yet viewed the Course Initialization Helper for this 14448: # course 14449: $cenv{'course.helper.not.run'} = 1; 14450: # 14451: # Use new Randomseed 14452: # 14453: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();; 14454: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();; 14455: # 14456: # The encryption code and receipt prefix for this course 14457: # 14458: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999)); 14459: $cenv{'internal.encpref'}=100+int(9*rand(99)); 14460: # 14461: # By default, use standard grading 14462: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; } 14463: 14464: $outcome .= $linefeed.&mt('Setting environment').': '. 14465: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed; 14466: # 14467: # Open all assignments 14468: # 14469: if ($args->{'openall'}) { 14470: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate'; 14471: my %storecontent = ($storeunder => time, 14472: $storeunder.'.type' => 'date_start'); 14473: 14474: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput 14475: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed; 14476: } 14477: # 14478: # Set first page 14479: # 14480: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank') 14481: || ($cloneid)) { 14482: use LONCAPA::map; 14483: $outcome .= &mt('Setting first resource').': '; 14484: 14485: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence'; 14486: my ($errtext,$fatal)=&LONCAPA::map::mapread($map); 14487: 14488: $outcome .= ($fatal?$errtext:'read ok').' - '; 14489: my $title; my $url; 14490: if ($args->{'firstres'} eq 'syl') { 14491: $title=&mt('Syllabus'); 14492: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus'; 14493: } else { 14494: $title=&mt('Table of Contents'); 14495: $url='/adm/navmaps'; 14496: } 14497: 14498: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res'; 14499: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1); 14500: 14501: if ($errtext) { $fatal=2; } 14502: $outcome .= ($fatal?$errtext:'write ok').$linefeed; 14503: } 14504: 14505: return (1,$outcome); 14506: } 14507: 14508: sub make_unique_code { 14509: my ($cdom,$cnum) = @_; 14510: # get lock on uniquecodes db 14511: my $lockhash = { 14512: $cnum."\0".'uniquecodes' => $env{'user.name'}. 14513: ':'.$env{'user.domain'}, 14514: }; 14515: my $tries = 0; 14516: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom); 14517: my ($code,$error); 14518: 14519: while (($gotlock ne 'ok') && ($tries<3)) { 14520: $tries ++; 14521: sleep 1; 14522: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom); 14523: } 14524: if ($gotlock eq 'ok') { 14525: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom); 14526: my $gotcode; 14527: my $attempts = 0; 14528: while ((!$gotcode) && ($attempts < 100)) { 14529: $code = &generate_code(); 14530: if (!exists($currcodes{$code})) { 14531: $gotcode = 1; 14532: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') { 14533: $error = 'nostore'; 14534: } 14535: } 14536: $attempts ++; 14537: } 14538: my @del_lock = ($cnum."\0".'uniquecodes'); 14539: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom); 14540: } else { 14541: $error = 'nolock'; 14542: } 14543: return ($code,$error); 14544: } 14545: 14546: sub generate_code { 14547: my $code; 14548: my @letts = qw(B C D G H J K M N P Q R S T V W X Z); 14549: for (my $i=0; $i<6; $i++) { 14550: my $lettnum = int (rand 2); 14551: my $item = ''; 14552: if ($lettnum) { 14553: $item = $letts[int( rand(18) )]; 14554: } else { 14555: $item = 1+int( rand(8) ); 14556: } 14557: $code .= $item; 14558: } 14559: return $code; 14560: } 14561: 14562: ############################################################ 14563: ############################################################ 14564: 14565: #SD 14566: # only Community and Course, or anything else? 14567: sub course_type { 14568: my ($cid) = @_; 14569: if (!defined($cid)) { 14570: $cid = $env{'request.course.id'}; 14571: } 14572: if (defined($env{'course.'.$cid.'.type'})) { 14573: return $env{'course.'.$cid.'.type'}; 14574: } else { 14575: return 'Course'; 14576: } 14577: } 14578: 14579: sub group_term { 14580: my $crstype = &course_type(); 14581: my %names = ( 14582: 'Course' => 'group', 14583: 'Community' => 'group', 14584: ); 14585: return $names{$crstype}; 14586: } 14587: 14588: sub course_types { 14589: my @types = ('official','unofficial','community','textbook'); 14590: my %typename = ( 14591: official => 'Official course', 14592: unofficial => 'Unofficial course', 14593: community => 'Community', 14594: textbook => 'Textbook course', 14595: ); 14596: return (\@types,\%typename); 14597: } 14598: 14599: sub icon { 14600: my ($file)=@_; 14601: my $curfext = lc((split(/\./,$file))[-1]); 14602: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif'; 14603: my $embstyle = &Apache::loncommon::fileembstyle($curfext); 14604: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) { 14605: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'. 14606: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'. 14607: $curfext.".gif") { 14608: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'. 14609: $curfext.".gif"; 14610: } 14611: } 14612: return &lonhttpdurl($iconname); 14613: } 14614: 14615: sub lonhttpdurl { 14616: # 14617: # Had been used for "small fry" static images on separate port 8080. 14618: # Modify here if lightweight http functionality desired again. 14619: # Currently eliminated due to increasing firewall issues. 14620: # 14621: my ($url)=@_; 14622: return $url; 14623: } 14624: 14625: sub connection_aborted { 14626: my ($r)=@_; 14627: $r->print(" ");$r->rflush(); 14628: my $c = $r->connection; 14629: return $c->aborted(); 14630: } 14631: 14632: # Escapes strings that may have embedded 's that will be put into 14633: # strings as 'strings'. 14634: sub escape_single { 14635: my ($input) = @_; 14636: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)> 14637: $input =~ s/\'/\\\'/g; # Esacpe the 's.... 14638: return $input; 14639: } 14640: 14641: # Same as escape_single, but escape's "'s This 14642: # can be used for "strings" 14643: sub escape_double { 14644: my ($input) = @_; 14645: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)> 14646: $input =~ s/\"/\\\"/g; # Esacpe the "s.... 14647: return $input; 14648: } 14649: 14650: # Escapes the last element of a full URL. 14651: sub escape_url { 14652: my ($url) = @_; 14653: my @urlslices = split(/\//, $url,-1); 14654: my $lastitem = &escape(pop(@urlslices)); 14655: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem; 14656: } 14657: 14658: sub compare_arrays { 14659: my ($arrayref1,$arrayref2) = @_; 14660: my (@difference,%count); 14661: @difference = (); 14662: %count = (); 14663: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) { 14664: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; } 14665: foreach my $element (keys(%count)) { 14666: if ($count{$element} == 1) { 14667: push(@difference,$element); 14668: } 14669: } 14670: } 14671: return @difference; 14672: } 14673: 14674: # -------------------------------------------------------- Initialize user login 14675: sub init_user_environment { 14676: my ($r, $username, $domain, $authhost, $form, $args) = @_; 14677: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'}; 14678: 14679: my $public=($username eq 'public' && $domain eq 'public'); 14680: 14681: # See if old ID present, if so, remove 14682: 14683: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv); 14684: my $now=time; 14685: 14686: if ($public) { 14687: my $max_public=100; 14688: my $oldest; 14689: my $oldest_time=0; 14690: for(my $next=1;$next<=$max_public;$next++) { 14691: if (-e $lonids."/publicuser_$next.id") { 14692: my $mtime=(stat($lonids."/publicuser_$next.id"))[9]; 14693: if ($mtime<$oldest_time || !$oldest_time) { 14694: $oldest_time=$mtime; 14695: $oldest=$next; 14696: } 14697: } else { 14698: $cookie="publicuser_$next"; 14699: last; 14700: } 14701: } 14702: if (!$cookie) { $cookie="publicuser_$oldest"; } 14703: } else { 14704: # if this isn't a robot, kill any existing non-robot sessions 14705: if (!$args->{'robot'}) { 14706: opendir(DIR,$lonids); 14707: while ($filename=readdir(DIR)) { 14708: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) { 14709: unlink($lonids.'/'.$filename); 14710: } 14711: } 14712: closedir(DIR); 14713: # If there is a undeleted lockfile for the user's paste buffer remove it. 14714: my $namespace = 'nohist_courseeditor'; 14715: my $lockingkey = 'paste'."\0".'locked_num'; 14716: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey], 14717: $domain,$username); 14718: if (exists($lockhash{$lockingkey})) { 14719: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username); 14720: unless ($delresult eq 'ok') { 14721: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult"); 14722: } 14723: } 14724: } 14725: # Give them a new cookie 14726: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'} 14727: : $now.$$.int(rand(10000))); 14728: $cookie="$username\_$id\_$domain\_$authhost"; 14729: 14730: # Initialize roles 14731: 14732: ($userroles,$firstaccenv,$timerintenv) = 14733: &Apache::lonnet::rolesinit($domain,$username,$authhost); 14734: } 14735: # ------------------------------------ Check browser type and MathML capability 14736: 14737: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode, 14738: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r); 14739: 14740: # ------------------------------------------------------------- Get environment 14741: 14742: my %userenv = &Apache::lonnet::dump('environment',$domain,$username); 14743: my ($tmp) = keys(%userenv); 14744: if ($tmp !~ /^(con_lost|error|no_such_host)/i) { 14745: } else { 14746: undef(%userenv); 14747: } 14748: if (($userenv{'interface'}) && (!$form->{'interface'})) { 14749: $form->{'interface'}=$userenv{'interface'}; 14750: } 14751: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; } 14752: 14753: # --------------- Do not trust query string to be put directly into environment 14754: foreach my $option ('interface','localpath','localres') { 14755: $form->{$option}=~s/[\n\r\=]//gs; 14756: } 14757: # --------------------------------------------------------- Write first profile 14758: 14759: { 14760: my %initial_env = 14761: ("user.name" => $username, 14762: "user.domain" => $domain, 14763: "user.home" => $authhost, 14764: "browser.type" => $clientbrowser, 14765: "browser.version" => $clientversion, 14766: "browser.mathml" => $clientmathml, 14767: "browser.unicode" => $clientunicode, 14768: "browser.os" => $clientos, 14769: "browser.mobile" => $clientmobile, 14770: "browser.info" => $clientinfo, 14771: "browser.osversion" => $clientosversion, 14772: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'}, 14773: "request.course.fn" => '', 14774: "request.course.uri" => '', 14775: "request.course.sec" => '', 14776: "request.role" => 'cm', 14777: "request.role.adv" => $env{'user.adv'}, 14778: "request.host" => $ENV{'REMOTE_ADDR'},); 14779: 14780: if ($form->{'localpath'}) { 14781: $initial_env{"browser.localpath"} = $form->{'localpath'}; 14782: $initial_env{"browser.localres"} = $form->{'localres'}; 14783: } 14784: 14785: if ($form->{'interface'}) { 14786: $form->{'interface'}=~s/\W//gs; 14787: $initial_env{"browser.interface"} = $form->{'interface'}; 14788: $env{'browser.interface'}=$form->{'interface'}; 14789: } 14790: 14791: if ($form->{'iptoken'}) { 14792: my $lonhost = $r->dir_config('lonHostID'); 14793: $initial_env{"user.noloadbalance"} = $lonhost; 14794: $env{'user.noloadbalance'} = $lonhost; 14795: } 14796: 14797: my %is_adv = ( is_adv => $env{'user.adv'} ); 14798: my %domdef; 14799: unless ($domain eq 'public') { 14800: %domdef = &Apache::lonnet::get_domain_defaults($domain); 14801: } 14802: 14803: foreach my $tool ('aboutme','blog','webdav','portfolio') { 14804: $userenv{'availabletools.'.$tool} = 14805: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload', 14806: undef,\%userenv,\%domdef,\%is_adv); 14807: } 14808: 14809: foreach my $crstype ('official','unofficial','community','textbook') { 14810: $userenv{'canrequest.'.$crstype} = 14811: &Apache::lonnet::usertools_access($username,$domain,$crstype, 14812: 'reload','requestcourses', 14813: \%userenv,\%domdef,\%is_adv); 14814: } 14815: 14816: $userenv{'canrequest.author'} = 14817: &Apache::lonnet::usertools_access($username,$domain,'requestauthor', 14818: 'reload','requestauthor', 14819: \%userenv,\%domdef,\%is_adv); 14820: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'], 14821: $domain,$username); 14822: my $reqstatus = $reqauthor{'author_status'}; 14823: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 14824: if (ref($reqauthor{'author'}) eq 'HASH') { 14825: $userenv{'requestauthorqueued'} = $reqstatus.':'. 14826: $reqauthor{'author'}{'timestamp'}; 14827: } 14828: } 14829: 14830: $env{'user.environment'} = "$lonids/$cookie.id"; 14831: 14832: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id", 14833: &GDBM_WRCREAT(),0640)) { 14834: &_add_to_env(\%disk_env,\%initial_env); 14835: &_add_to_env(\%disk_env,\%userenv,'environment.'); 14836: &_add_to_env(\%disk_env,$userroles); 14837: if (ref($firstaccenv) eq 'HASH') { 14838: &_add_to_env(\%disk_env,$firstaccenv); 14839: } 14840: if (ref($timerintenv) eq 'HASH') { 14841: &_add_to_env(\%disk_env,$timerintenv); 14842: } 14843: if (ref($args->{'extra_env'})) { 14844: &_add_to_env(\%disk_env,$args->{'extra_env'}); 14845: } 14846: untie(%disk_env); 14847: } else { 14848: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ". 14849: 'Could not create environment storage in lonauth: '.$!.'</span>'); 14850: return 'error: '.$!; 14851: } 14852: } 14853: $env{'request.role'}='cm'; 14854: $env{'request.role.adv'}=$env{'user.adv'}; 14855: $env{'browser.type'}=$clientbrowser; 14856: 14857: return $cookie; 14858: 14859: } 14860: 14861: sub _add_to_env { 14862: my ($idf,$env_data,$prefix) = @_; 14863: if (ref($env_data) eq 'HASH') { 14864: while (my ($key,$value) = each(%$env_data)) { 14865: $idf->{$prefix.$key} = $value; 14866: $env{$prefix.$key} = $value; 14867: } 14868: } 14869: } 14870: 14871: # --- Get the symbolic name of a problem and the url 14872: sub get_symb { 14873: my ($request,$silent) = @_; 14874: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--; 14875: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url))); 14876: if ($symb eq '') { 14877: if (!$silent) { 14878: if (ref($request)) { 14879: $request->print("Unable to handle ambiguous references:$url:."); 14880: } 14881: return (); 14882: } 14883: } 14884: &Apache::lonenc::check_decrypt(\$symb); 14885: return ($symb); 14886: } 14887: 14888: # --------------------------------------------------------------Get annotation 14889: 14890: sub get_annotation { 14891: my ($symb,$enc) = @_; 14892: 14893: my $key = $symb; 14894: if (!$enc) { 14895: $key = 14896: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]); 14897: } 14898: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]); 14899: return $annotation{$key}; 14900: } 14901: 14902: sub clean_symb { 14903: my ($symb,$delete_enc) = @_; 14904: 14905: &Apache::lonenc::check_decrypt(\$symb); 14906: my $enc = $env{'request.enc'}; 14907: if ($delete_enc) { 14908: delete($env{'request.enc'}); 14909: } 14910: 14911: return ($symb,$enc); 14912: } 14913: 14914: ############################################################ 14915: ############################################################ 14916: 14917: =pod 14918: 14919: =head1 Routines for building display used to search for courses 14920: 14921: 14922: =over 4 14923: 14924: =item * &build_filters() 14925: 14926: Create markup for a table used to set filters to use when selecting 14927: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm 14928: and quotacheck.pl 14929: 14930: 14931: Inputs: 14932: 14933: filterlist - anonymous array of fields to include as potential filters 14934: 14935: crstype - course type 14936: 14937: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used 14938: to pop-open a course selector (will contain "extra element"). 14939: 14940: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1 14941: 14942: filter - anonymous hash of criteria and their values 14943: 14944: action - form action 14945: 14946: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number) 14947: 14948: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm) 14949: 14950: cloneruname - username of owner of new course who wants to clone 14951: 14952: clonerudom - domain of owner of new course who wants to clone 14953: 14954: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 14955: 14956: codetitlesref - reference to array of titles of components in institutional codes (official courses) 14957: 14958: codedom - domain 14959: 14960: formname - value of form element named "form". 14961: 14962: fixeddom - domain, if fixed. 14963: 14964: prevphase - value to assign to form element named "phase" when going back to the previous screen 14965: 14966: cnameelement - name of form element in form on opener page which will receive title of selected course 14967: 14968: cnumelement - name of form element in form on opener page which will receive courseID of selected course 14969: 14970: cdomelement - name of form element in form on opener page which will receive domain of selected course 14971: 14972: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file 14973: 14974: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course 14975: 14976: clonewarning - warning message about missing information for intended course owner when DC creates a course 14977: 14978: 14979: Returns: $output - HTML for display of search criteria, and hidden form elements. 14980: 14981: 14982: Side Effects: None 14983: 14984: =cut 14985: 14986: # ---------------------------------------------- search for courses based on last activity etc. 14987: 14988: sub build_filters { 14989: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action, 14990: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement, 14991: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase, 14992: $cnameelement,$cnumelement,$cdomelement,$setroles, 14993: $clonetext,$clonewarning) = @_; 14994: my ($list,$jscript); 14995: my $onchange = 'javascript:updateFilters(this)'; 14996: my ($domainselectform,$sincefilterform,$createdfilterform, 14997: $ownerdomselectform,$persondomselectform,$instcodeform, 14998: $typeselectform,$instcodetitle); 14999: if ($formname eq '') { 15000: $formname = $caller; 15001: } 15002: foreach my $item (@{$filterlist}) { 15003: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') || 15004: ($item eq 'sincefilter') || ($item eq 'createdfilter')) { 15005: if ($item eq 'domainfilter') { 15006: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item}); 15007: } elsif ($item eq 'coursefilter') { 15008: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item}); 15009: } elsif ($item eq 'ownerfilter') { 15010: $filter->{$item} = &LONCAPA::clean_username($filter->{$item}); 15011: } elsif ($item eq 'ownerdomfilter') { 15012: $filter->{'ownerdomfilter'} = 15013: &LONCAPA::clean_domain($filter->{$item}); 15014: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'}, 15015: 'ownerdomfilter',1); 15016: } elsif ($item eq 'personfilter') { 15017: $filter->{$item} = &LONCAPA::clean_username($filter->{$item}); 15018: } elsif ($item eq 'persondomfilter') { 15019: $persondomselectform = &select_dom_form($filter->{'persondomfilter'}, 15020: 'persondomfilter',1); 15021: } else { 15022: $filter->{$item} =~ s/\W//g; 15023: } 15024: if (!$filter->{$item}) { 15025: $filter->{$item} = ''; 15026: } 15027: } 15028: if ($item eq 'domainfilter') { 15029: my $allow_blank = 1; 15030: if ($formname eq 'portform') { 15031: $allow_blank=0; 15032: } elsif ($formname eq 'studentform') { 15033: $allow_blank=0; 15034: } 15035: if ($fixeddom) { 15036: $domainselectform = '<input type="hidden" name="domainfilter"'. 15037: ' value="'.$codedom.'" />'. 15038: &Apache::lonnet::domain($codedom,'description'); 15039: } else { 15040: $domainselectform = &select_dom_form($filter->{$item}, 15041: 'domainfilter', 15042: $allow_blank,'',$onchange); 15043: } 15044: } else { 15045: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"'); 15046: } 15047: } 15048: 15049: # last course activity filter and selection 15050: $sincefilterform = &timebased_select_form('sincefilter',$filter); 15051: 15052: # course created filter and selection 15053: if (exists($filter->{'createdfilter'})) { 15054: $createdfilterform = &timebased_select_form('createdfilter',$filter); 15055: } 15056: 15057: my %lt = &Apache::lonlocal::texthash( 15058: 'cac' => "$crstype Activity", 15059: 'ccr' => "$crstype Created", 15060: 'cde' => "$crstype Title", 15061: 'cdo' => "$crstype Domain", 15062: 'ins' => 'Institutional Code', 15063: 'inc' => 'Institutional Categorization', 15064: 'cow' => "$crstype Owner/Co-owner", 15065: 'cop' => "$crstype Personnel Includes", 15066: 'cog' => 'Type', 15067: ); 15068: 15069: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) { 15070: my $typeval = 'Course'; 15071: if ($crstype eq 'Community') { 15072: $typeval = 'Community'; 15073: } 15074: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />'; 15075: } else { 15076: $typeselectform = '<select name="type" size="1"'; 15077: if ($onchange) { 15078: $typeselectform .= ' onchange="'.$onchange.'"'; 15079: } 15080: $typeselectform .= '>'."\n"; 15081: foreach my $posstype ('Course','Community') { 15082: $typeselectform.='<option value="'.$posstype.'"'. 15083: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n"; 15084: } 15085: $typeselectform.="</select>"; 15086: } 15087: 15088: my ($cloneableonlyform,$cloneabletitle); 15089: if (exists($filter->{'cloneableonly'})) { 15090: my $cloneableon = ''; 15091: my $cloneableoff = ' checked="checked"'; 15092: if ($filter->{'cloneableonly'}) { 15093: $cloneableon = $cloneableoff; 15094: $cloneableoff = ''; 15095: } 15096: $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/> '.&mt('Required').'</label>'.(' 'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' /> '.&mt('No restriction').'</label></span>'; 15097: if ($formname eq 'ccrs') { 15098: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom); 15099: } else { 15100: $cloneabletitle = &mt('Cloneable by you'); 15101: } 15102: } 15103: my $officialjs; 15104: if ($crstype eq 'Course') { 15105: if (exists($filter->{'instcodefilter'})) { 15106: # if (($fixeddom) || ($formname eq 'requestcrs') || 15107: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) { 15108: if ($codedom) { 15109: $officialjs = 1; 15110: ($instcodeform,$jscript,$$numtitlesref) = 15111: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker', 15112: $officialjs,$codetitlesref); 15113: if ($jscript) { 15114: $jscript = '<script type="text/javascript">'."\n". 15115: '// <![CDATA['."\n". 15116: $jscript."\n". 15117: '// ]]>'."\n". 15118: '</script>'."\n"; 15119: } 15120: } 15121: if ($instcodeform eq '') { 15122: $instcodeform = 15123: '<input type="text" name="instcodefilter" size="10" value="'. 15124: $list->{'instcodefilter'}.'" />'; 15125: $instcodetitle = $lt{'ins'}; 15126: } else { 15127: $instcodetitle = $lt{'inc'}; 15128: } 15129: if ($fixeddom) { 15130: $instcodetitle .= '<br />('.$codedom.')'; 15131: } 15132: } 15133: } 15134: my $output = qq| 15135: <form method="post" name="filterpicker" action="$action"> 15136: <input type="hidden" name="form" value="$formname" /> 15137: |; 15138: if ($formname eq 'modifycourse') { 15139: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n". 15140: '<input type="hidden" name="prevphase" value="'. 15141: $prevphase.'" />'."\n"; 15142: } elsif ($formname eq 'quotacheck') { 15143: $output .= qq| 15144: <input type="hidden" name="sortby" value="" /> 15145: <input type="hidden" name="sortorder" value="" /> 15146: |; 15147: } else { 15148: my $name_input; 15149: if ($cnameelement ne '') { 15150: $name_input = '<input type="hidden" name="cnameelement" value="'. 15151: $cnameelement.'" />'; 15152: } 15153: $output .= qq| 15154: <input type="hidden" name="cnumelement" value="$cnumelement" /> 15155: <input type="hidden" name="cdomelement" value="$cdomelement" /> 15156: $name_input 15157: $roleelement 15158: $multelement 15159: $typeelement 15160: |; 15161: if ($formname eq 'portform') { 15162: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n"; 15163: } 15164: } 15165: if ($fixeddom) { 15166: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n"; 15167: } 15168: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box(); 15169: if ($sincefilterform) { 15170: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'}) 15171: .$sincefilterform 15172: .&Apache::lonhtmlcommon::row_closure(); 15173: } 15174: if ($createdfilterform) { 15175: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'}) 15176: .$createdfilterform 15177: .&Apache::lonhtmlcommon::row_closure(); 15178: } 15179: if ($domainselectform) { 15180: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'}) 15181: .$domainselectform 15182: .&Apache::lonhtmlcommon::row_closure(); 15183: } 15184: if ($typeselectform) { 15185: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) { 15186: $output .= $typeselectform; 15187: } else { 15188: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'}) 15189: .$typeselectform 15190: .&Apache::lonhtmlcommon::row_closure(); 15191: } 15192: } 15193: if ($instcodeform) { 15194: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle) 15195: .$instcodeform 15196: .&Apache::lonhtmlcommon::row_closure(); 15197: } 15198: if (exists($filter->{'ownerfilter'})) { 15199: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}). 15200: '<table><tr><td>'.&mt('Username').'<br />'. 15201: '<input type="text" name="ownerfilter" size="20" value="'. 15202: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'. 15203: $ownerdomselectform.'</td></tr></table>'. 15204: &Apache::lonhtmlcommon::row_closure(); 15205: } 15206: if (exists($filter->{'personfilter'})) { 15207: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}). 15208: '<table><tr><td>'.&mt('Username').'<br />'. 15209: '<input type="text" name="personfilter" size="20" value="'. 15210: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'. 15211: $persondomselectform.'</td></tr></table>'. 15212: &Apache::lonhtmlcommon::row_closure(); 15213: } 15214: if (exists($filter->{'coursefilter'})) { 15215: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID')) 15216: .'<input type="text" name="coursefilter" size="25" value="' 15217: .$list->{'coursefilter'}.'" />' 15218: .&Apache::lonhtmlcommon::row_closure(); 15219: } 15220: if ($cloneableonlyform) { 15221: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle). 15222: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure(); 15223: } 15224: if (exists($filter->{'descriptfilter'})) { 15225: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'}) 15226: .'<input type="text" name="descriptfilter" size="40" value="' 15227: .$list->{'descriptfilter'}.'" />' 15228: .&Apache::lonhtmlcommon::row_closure(1); 15229: } 15230: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n". 15231: '<input type="hidden" name="updater" value="" />'."\n". 15232: '<input type="submit" name="gosearch" value="'. 15233: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n"; 15234: return $jscript.$clonewarning.$output; 15235: } 15236: 15237: =pod 15238: 15239: =item * &timebased_select_form() 15240: 15241: Create markup for a dropdown list used to select a time-based 15242: filter e.g., Course Activity, Course Created, when searching for courses 15243: or communities 15244: 15245: Inputs: 15246: 15247: item - name of form element (sincefilter or createdfilter) 15248: 15249: filter - anonymous hash of criteria and their values 15250: 15251: Returns: HTML for a select box contained a blank, then six time selections, 15252: with value set in incoming form variables currently selected. 15253: 15254: Side Effects: None 15255: 15256: =cut 15257: 15258: sub timebased_select_form { 15259: my ($item,$filter) = @_; 15260: if (ref($filter) eq 'HASH') { 15261: $filter->{$item} =~ s/[^\d-]//g; 15262: if (!$filter->{$item}) { $filter->{$item}=-1; } 15263: return &select_form( 15264: $filter->{$item}, 15265: $item, 15266: { '-1' => '', 15267: '86400' => &mt('today'), 15268: '604800' => &mt('last week'), 15269: '2592000' => &mt('last month'), 15270: '7776000' => &mt('last three months'), 15271: '15552000' => &mt('last six months'), 15272: '31104000' => &mt('last year'), 15273: 'select_form_order' => 15274: ['-1','86400','604800','2592000','7776000', 15275: '15552000','31104000']}); 15276: } 15277: } 15278: 15279: =pod 15280: 15281: =item * &js_changer() 15282: 15283: Create script tag containing Javascript used to submit course search form 15284: when course type or domain is changed, and also to hide 'Searching ...' on 15285: page load completion for page showing search result. 15286: 15287: Inputs: None 15288: 15289: Returns: markup containing updateFilters() and hideSearching() javascript functions. 15290: 15291: Side Effects: None 15292: 15293: =cut 15294: 15295: sub js_changer { 15296: return <<ENDJS; 15297: <script type="text/javascript"> 15298: // <![CDATA[ 15299: function updateFilters(caller) { 15300: if (typeof(caller) != "undefined") { 15301: document.filterpicker.updater.value = caller.name; 15302: } 15303: document.filterpicker.submit(); 15304: } 15305: 15306: function hideSearching() { 15307: if (document.getElementById('searching')) { 15308: document.getElementById('searching').style.display = 'none'; 15309: } 15310: return; 15311: } 15312: 15313: // ]]> 15314: </script> 15315: 15316: ENDJS 15317: } 15318: 15319: =pod 15320: 15321: =item * &search_courses() 15322: 15323: Process selected filters form course search form and pass to lonnet::courseiddump 15324: to retrieve a hash for which keys are courseIDs which match the selected filters. 15325: 15326: Inputs: 15327: 15328: dom - domain being searched 15329: 15330: type - course type ('Course' or 'Community' or '.' if any). 15331: 15332: filter - anonymous hash of criteria and their values 15333: 15334: numtitles - for institutional codes - number of categories 15335: 15336: cloneruname - optional username of new course owner 15337: 15338: clonerudom - optional domain of new course owner 15339: 15340: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 15341: (used when DC is using course creation form) 15342: 15343: codetitles - reference to array of titles of components in institutional codes (official courses). 15344: 15345: 15346: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type. 15347: 15348: 15349: Side Effects: None 15350: 15351: =cut 15352: 15353: 15354: sub search_courses { 15355: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_; 15356: my (%courses,%showcourses,$cloner); 15357: if (($filter->{'ownerfilter'} ne '') || 15358: ($filter->{'ownerdomfilter'} ne '')) { 15359: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'. 15360: $filter->{'ownerdomfilter'}; 15361: } 15362: foreach my $item ('descriptfilter','coursefilter','combownerfilter') { 15363: if (!$filter->{$item}) { 15364: $filter->{$item}='.'; 15365: } 15366: } 15367: my $now = time; 15368: my $timefilter = 15369: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'}); 15370: my ($createdbefore,$createdafter); 15371: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) { 15372: $createdbefore = $now; 15373: $createdafter = $now-$filter->{'createdfilter'}; 15374: } 15375: my ($instcodefilter,$regexpok); 15376: if ($numtitles) { 15377: if ($env{'form.official'} eq 'on') { 15378: $instcodefilter = 15379: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles); 15380: $regexpok = 1; 15381: } elsif ($env{'form.official'} eq 'off') { 15382: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles); 15383: unless ($instcodefilter eq '') { 15384: $regexpok = -1; 15385: } 15386: } 15387: } else { 15388: $instcodefilter = $filter->{'instcodefilter'}; 15389: } 15390: if ($instcodefilter eq '') { $instcodefilter = '.'; } 15391: if ($type eq '') { $type = '.'; } 15392: 15393: if (($clonerudom ne '') && ($cloneruname ne '')) { 15394: $cloner = $cloneruname.':'.$clonerudom; 15395: } 15396: %courses = &Apache::lonnet::courseiddump($dom, 15397: $filter->{'descriptfilter'}, 15398: $timefilter, 15399: $instcodefilter, 15400: $filter->{'combownerfilter'}, 15401: $filter->{'coursefilter'}, 15402: undef,undef,$type,$regexpok,undef,undef, 15403: undef,undef,$cloner,$env{'form.cc_clone'}, 15404: $filter->{'cloneableonly'}, 15405: $createdbefore,$createdafter,undef, 15406: $domcloner); 15407: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) { 15408: my $ccrole; 15409: if ($type eq 'Community') { 15410: $ccrole = 'co'; 15411: } else { 15412: $ccrole = 'cc'; 15413: } 15414: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'}, 15415: $filter->{'persondomfilter'}, 15416: 'userroles',undef, 15417: [$ccrole,'in','ad','ep','ta','cr'], 15418: $dom); 15419: foreach my $role (keys(%rolehash)) { 15420: my ($cnum,$cdom,$courserole) = split(':',$role); 15421: my $cid = $cdom.'_'.$cnum; 15422: if (exists($courses{$cid})) { 15423: if (ref($courses{$cid}) eq 'HASH') { 15424: if (ref($courses{$cid}{roles}) eq 'ARRAY') { 15425: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) { 15426: push (@{$courses{$cid}{roles}},$courserole); 15427: } 15428: } else { 15429: $courses{$cid}{roles} = [$courserole]; 15430: } 15431: $showcourses{$cid} = $courses{$cid}; 15432: } 15433: } 15434: } 15435: %courses = %showcourses; 15436: } 15437: return %courses; 15438: } 15439: 15440: =pod 15441: 15442: =back 15443: 15444: =head1 Routines for version requirements for current course. 15445: 15446: =over 4 15447: 15448: =item * &check_release_required() 15449: 15450: Compares required LON-CAPA version with version on server, and 15451: if required version is newer looks for a server with the required version. 15452: 15453: Looks first at servers in user's owen domain; if none suitable, looks at 15454: servers in course's domain are permitted to host sessions for user's domain. 15455: 15456: Inputs: 15457: 15458: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp) 15459: 15460: $courseid - Course ID of current course 15461: 15462: $rolecode - User's current role in course (for switchserver query string). 15463: 15464: $required - LON-CAPA version needed by course (format: Major.Minor). 15465: 15466: 15467: Returns: 15468: 15469: $switchserver - query string tp append to /adm/switchserver call (if 15470: current server's LON-CAPA version is too old. 15471: 15472: $warning - Message is displayed if no suitable server could be found. 15473: 15474: =cut 15475: 15476: sub check_release_required { 15477: my ($loncaparev,$courseid,$rolecode,$required) = @_; 15478: my ($switchserver,$warning); 15479: if ($required ne '') { 15480: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/); 15481: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/); 15482: if ($reqdmajor ne '' && $reqdminor ne '') { 15483: my $otherserver; 15484: if (($major eq '' && $minor eq '') || 15485: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) { 15486: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1); 15487: my $switchlcrev = 15488: &Apache::lonnet::get_server_loncaparev($env{'user.domain'}, 15489: $userdomserver); 15490: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/); 15491: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) || 15492: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) { 15493: my $cdom = $env{'course.'.$courseid.'.domain'}; 15494: if ($cdom ne $env{'user.domain'}) { 15495: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1); 15496: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname); 15497: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID); 15498: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom); 15499: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'}); 15500: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver); 15501: my $canhost = 15502: &Apache::lonnet::can_host_session($env{'user.domain'}, 15503: $coursedomserver, 15504: $remoterev, 15505: $udomdefaults{'remotesessions'}, 15506: $defdomdefaults{'hostedsessions'}); 15507: 15508: if ($canhost) { 15509: $otherserver = $coursedomserver; 15510: } else { 15511: $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."); 15512: } 15513: } else { 15514: $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)."); 15515: } 15516: } else { 15517: $otherserver = $userdomserver; 15518: } 15519: } 15520: if ($otherserver ne '') { 15521: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode; 15522: } 15523: } 15524: } 15525: return ($switchserver,$warning); 15526: } 15527: 15528: =pod 15529: 15530: =item * &check_release_result() 15531: 15532: Inputs: 15533: 15534: $switchwarning - Warning message if no suitable server found to host session. 15535: 15536: $switchserver - query string to append to /adm/switchserver containing lonHostID 15537: and current role. 15538: 15539: Returns: HTML to display with information about requirement to switch server. 15540: Either displaying warning with link to Roles/Courses screen or 15541: display link to switchserver. 15542: 15543: =cut 15544: 15545: sub check_release_result { 15546: my ($switchwarning,$switchserver) = @_; 15547: my $output = &start_page('Selected course unavailable on this server'). 15548: '<p class="LC_warning">'; 15549: if ($switchwarning) { 15550: $output .= $switchwarning.'<br /><a href="/adm/roles">'; 15551: if (&show_course()) { 15552: $output .= &mt('Display courses'); 15553: } else { 15554: $output .= &mt('Display roles'); 15555: } 15556: $output .= '</a>'; 15557: } elsif ($switchserver) { 15558: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.'). 15559: '<br />'. 15560: '<a href="/adm/switchserver?'.$switchserver.'">'. 15561: &mt('Switch Server'). 15562: '</a>'; 15563: } 15564: $output .= '</p>'.&end_page(); 15565: return $output; 15566: } 15567: 15568: =pod 15569: 15570: =item * &needs_coursereinit() 15571: 15572: Determine if course contents stored for user's session needs to be 15573: refreshed, because content has changed since "Big Hash" last tied. 15574: 15575: Check for change is made if time last checked is more than 10 minutes ago 15576: (by default). 15577: 15578: Inputs: 15579: 15580: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp) 15581: 15582: $interval (optional) - Time which may elapse (in s) between last check for content 15583: change in current course. (default: 600 s). 15584: 15585: Returns: an array; first element is: 15586: 15587: =over 4 15588: 15589: 'switch' - if content updates mean user's session 15590: needs to be switched to a server running a newer LON-CAPA version 15591: 15592: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded) 15593: on current server hosting user's session 15594: 15595: '' - if no action required. 15596: 15597: =back 15598: 15599: If first item element is 'switch': 15600: 15601: second item is $switchwarning - Warning message if no suitable server found to host session. 15602: 15603: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID 15604: and current role. 15605: 15606: otherwise: no other elements returned. 15607: 15608: =back 15609: 15610: =cut 15611: 15612: sub needs_coursereinit { 15613: my ($loncaparev,$interval) = @_; 15614: return() unless ($env{'request.course.id'} && $env{'request.course.tied'}); 15615: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; 15616: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; 15617: my $now = time; 15618: if ($interval eq '') { 15619: $interval = 600; 15620: } 15621: if (($now-$env{'request.course.timechecked'})>$interval) { 15622: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum); 15623: &Apache::lonnet::appenv({'request.course.timechecked'=>$now}); 15624: if ($lastchange > $env{'request.course.tied'}) { 15625: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired'); 15626: if ($curr_reqd_hash{'internal.releaserequired'} ne '') { 15627: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'}; 15628: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) { 15629: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' => 15630: $curr_reqd_hash{'internal.releaserequired'}}); 15631: my ($switchserver,$switchwarning) = 15632: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'}, 15633: $curr_reqd_hash{'internal.releaserequired'}); 15634: if ($switchwarning ne '' || $switchserver ne '') { 15635: return ('switch',$switchwarning,$switchserver); 15636: } 15637: } 15638: } 15639: return ('update'); 15640: } 15641: } 15642: return (); 15643: } 15644: 15645: sub update_content_constraints { 15646: my ($cdom,$cnum,$chome,$cid) = @_; 15647: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired'); 15648: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'}); 15649: my %checkresponsetypes; 15650: foreach my $key (keys(%Apache::lonnet::needsrelease)) { 15651: my ($item,$name,$value) = split(/:/,$key); 15652: if ($item eq 'resourcetag') { 15653: if ($name eq 'responsetype') { 15654: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key} 15655: } 15656: } 15657: } 15658: my $navmap = Apache::lonnavmaps::navmap->new(); 15659: if (defined($navmap)) { 15660: my %allresponses; 15661: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) { 15662: my %responses = $res->responseTypes(); 15663: foreach my $key (keys(%responses)) { 15664: next unless(exists($checkresponsetypes{$key})); 15665: $allresponses{$key} += $responses{$key}; 15666: } 15667: } 15668: foreach my $key (keys(%allresponses)) { 15669: my ($major,$minor) = split(/\./,$checkresponsetypes{$key}); 15670: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) { 15671: ($reqdmajor,$reqdminor) = ($major,$minor); 15672: } 15673: } 15674: undef($navmap); 15675: } 15676: unless (($reqdmajor eq '') && ($reqdminor eq '')) { 15677: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid); 15678: } 15679: return; 15680: } 15681: 15682: sub allmaps_incourse { 15683: my ($cdom,$cnum,$chome,$cid) = @_; 15684: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') { 15685: $cid = $env{'request.course.id'}; 15686: $cdom = $env{'course.'.$cid.'.domain'}; 15687: $cnum = $env{'course.'.$cid.'.num'}; 15688: $chome = $env{'course.'.$cid.'.home'}; 15689: } 15690: my %allmaps = (); 15691: my $lastchange = 15692: &Apache::lonnet::get_coursechange($cdom,$cnum); 15693: if ($lastchange > $env{'request.course.tied'}) { 15694: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum"); 15695: unless ($ferr) { 15696: &update_content_constraints($cdom,$cnum,$chome,$cid); 15697: } 15698: } 15699: my $navmap = Apache::lonnavmaps::navmap->new(); 15700: if (defined($navmap)) { 15701: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) { 15702: $allmaps{$res->src()} = 1; 15703: } 15704: } 15705: return \%allmaps; 15706: } 15707: 15708: sub parse_supplemental_title { 15709: my ($title) = @_; 15710: 15711: my ($foldertitle,$renametitle); 15712: if ($title =~ /&&&/) { 15713: $title = &HTML::Entites::decode($title); 15714: } 15715: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) { 15716: $renametitle=$4; 15717: my ($time,$uname,$udom) = ($1,$2,$3); 15718: $foldertitle=&Apache::lontexconvert::msgtexconverted($4); 15719: my $name = &plainname($uname,$udom); 15720: $name = &HTML::Entities::encode($name,'"<>&\''); 15721: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\''); 15722: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '. 15723: $name.': <br />'.$foldertitle; 15724: } 15725: if (wantarray) { 15726: return ($title,$foldertitle,$renametitle); 15727: } 15728: return $title; 15729: } 15730: 15731: sub recurse_supplemental { 15732: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_; 15733: if ($suppmap) { 15734: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap); 15735: if ($fatal) { 15736: $errors ++; 15737: } else { 15738: if ($#LONCAPA::map::resources > 0) { 15739: foreach my $res (@LONCAPA::map::resources) { 15740: my ($title,$src,$ext,$type,$status)=split(/\:/,$res); 15741: if (($src ne '') && ($status eq 'res')) { 15742: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) { 15743: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors); 15744: } else { 15745: $numfiles ++; 15746: } 15747: } 15748: } 15749: } 15750: } 15751: } 15752: return ($numfiles,$errors); 15753: } 15754: 15755: sub symb_to_docspath { 15756: my ($symb) = @_; 15757: return unless ($symb); 15758: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb); 15759: if ($resurl=~/\.(sequence|page)$/) { 15760: $mapurl=$resurl; 15761: } elsif ($resurl eq 'adm/navmaps') { 15762: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'}; 15763: } 15764: my $mapresobj; 15765: my $navmap = Apache::lonnavmaps::navmap->new(); 15766: if (ref($navmap)) { 15767: $mapresobj = $navmap->getResourceByUrl($mapurl); 15768: } 15769: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1}; 15770: my $type=$2; 15771: my $path; 15772: if (ref($mapresobj)) { 15773: my $pcslist = $mapresobj->map_hierarchy(); 15774: if ($pcslist ne '') { 15775: foreach my $pc (split(/,/,$pcslist)) { 15776: next if ($pc <= 1); 15777: my $res = $navmap->getByMapPc($pc); 15778: if (ref($res)) { 15779: my $thisurl = $res->src(); 15780: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1}; 15781: my $thistitle = $res->title(); 15782: $path .= '&'. 15783: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'. 15784: &escape($thistitle). 15785: ':'.$res->randompick(). 15786: ':'.$res->randomout(). 15787: ':'.$res->encrypted(). 15788: ':'.$res->randomorder(). 15789: ':'.$res->is_page(); 15790: } 15791: } 15792: } 15793: $path =~ s/^\&//; 15794: my $maptitle = $mapresobj->title(); 15795: if ($mapurl eq 'default') { 15796: $maptitle = 'Main Content'; 15797: } 15798: $path .= (($path ne '')? '&' : ''). 15799: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'. 15800: &escape($maptitle). 15801: ':'.$mapresobj->randompick(). 15802: ':'.$mapresobj->randomout(). 15803: ':'.$mapresobj->encrypted(). 15804: ':'.$mapresobj->randomorder(). 15805: ':'.$mapresobj->is_page(); 15806: } else { 15807: my $maptitle = &Apache::lonnet::gettitle($mapurl); 15808: my $ispage = (($type eq 'page')? 1 : ''); 15809: if ($mapurl eq 'default') { 15810: $maptitle = 'Main Content'; 15811: } 15812: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'. 15813: &escape($maptitle).':::::'.$ispage; 15814: } 15815: unless ($mapurl eq 'default') { 15816: $path = 'default&'. 15817: &escape('Main Content'). 15818: ':::::&'.$path; 15819: } 15820: return $path; 15821: } 15822: 15823: sub captcha_display { 15824: my ($context,$lonhost) = @_; 15825: my ($output,$error); 15826: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost); 15827: if ($captcha eq 'original') { 15828: $output = &create_captcha(); 15829: unless ($output) { 15830: $error = 'captcha'; 15831: } 15832: } elsif ($captcha eq 'recaptcha') { 15833: $output = &create_recaptcha($pubkey); 15834: unless ($output) { 15835: $error = 'recaptcha'; 15836: } 15837: } 15838: return ($output,$error,$captcha); 15839: } 15840: 15841: sub captcha_response { 15842: my ($context,$lonhost) = @_; 15843: my ($captcha_chk,$captcha_error); 15844: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost); 15845: if ($captcha eq 'original') { 15846: ($captcha_chk,$captcha_error) = &check_captcha(); 15847: } elsif ($captcha eq 'recaptcha') { 15848: $captcha_chk = &check_recaptcha($privkey); 15849: } else { 15850: $captcha_chk = 1; 15851: } 15852: return ($captcha_chk,$captcha_error); 15853: } 15854: 15855: sub get_captcha_config { 15856: my ($context,$lonhost) = @_; 15857: my ($captcha,$pubkey,$privkey,$hashtocheck); 15858: my $hostname = &Apache::lonnet::hostname($lonhost); 15859: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname); 15860: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID); 15861: if ($context eq 'usercreation') { 15862: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom); 15863: if (ref($domconfig{$context}) eq 'HASH') { 15864: $hashtocheck = $domconfig{$context}{'cancreate'}; 15865: if (ref($hashtocheck) eq 'HASH') { 15866: if ($hashtocheck->{'captcha'} eq 'recaptcha') { 15867: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') { 15868: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'}; 15869: $privkey = $hashtocheck->{'recaptchakeys'}{'private'}; 15870: } 15871: if ($privkey && $pubkey) { 15872: $captcha = 'recaptcha'; 15873: } else { 15874: $captcha = 'original'; 15875: } 15876: } elsif ($hashtocheck->{'captcha'} ne 'notused') { 15877: $captcha = 'original'; 15878: } 15879: } 15880: } else { 15881: $captcha = 'captcha'; 15882: } 15883: } elsif ($context eq 'login') { 15884: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom); 15885: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') { 15886: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'}; 15887: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'}; 15888: if ($privkey && $pubkey) { 15889: $captcha = 'recaptcha'; 15890: } else { 15891: $captcha = 'original'; 15892: } 15893: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') { 15894: $captcha = 'original'; 15895: } 15896: } 15897: return ($captcha,$pubkey,$privkey); 15898: } 15899: 15900: sub create_captcha { 15901: my %captcha_params = &captcha_settings(); 15902: my ($output,$maxtries,$tries) = ('',10,0); 15903: while ($tries < $maxtries) { 15904: $tries ++; 15905: my $captcha = Authen::Captcha->new ( 15906: output_folder => $captcha_params{'output_dir'}, 15907: data_folder => $captcha_params{'db_dir'}, 15908: ); 15909: my $md5sum = $captcha->generate_code($captcha_params{'numchars'}); 15910: 15911: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') { 15912: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n". 15913: &mt('Type in the letters/numbers shown below').' '. 15914: '<input type="text" size="5" name="code" value="" autocomplete="off" />'. 15915: '<br />'. 15916: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />'; 15917: last; 15918: } 15919: } 15920: return $output; 15921: } 15922: 15923: sub captcha_settings { 15924: my %captcha_params = ( 15925: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'}, 15926: www_output_dir => "/captchaspool", 15927: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'}, 15928: numchars => '5', 15929: ); 15930: return %captcha_params; 15931: } 15932: 15933: sub check_captcha { 15934: my ($captcha_chk,$captcha_error); 15935: my $code = $env{'form.code'}; 15936: my $md5sum = $env{'form.crypt'}; 15937: my %captcha_params = &captcha_settings(); 15938: my $captcha = Authen::Captcha->new( 15939: output_folder => $captcha_params{'output_dir'}, 15940: data_folder => $captcha_params{'db_dir'}, 15941: ); 15942: $captcha_chk = $captcha->check_code($code,$md5sum); 15943: my %captcha_hash = ( 15944: 0 => 'Code not checked (file error)', 15945: -1 => 'Failed: code expired', 15946: -2 => 'Failed: invalid code (not in database)', 15947: -3 => 'Failed: invalid code (code does not match crypt)', 15948: ); 15949: if ($captcha_chk != 1) { 15950: $captcha_error = $captcha_hash{$captcha_chk} 15951: } 15952: return ($captcha_chk,$captcha_error); 15953: } 15954: 15955: sub create_recaptcha { 15956: my ($pubkey) = @_; 15957: my $use_ssl; 15958: if ($ENV{'SERVER_PORT'} == 443) { 15959: $use_ssl = 1; 15960: } 15961: my $captcha = Captcha::reCAPTCHA->new; 15962: return $captcha->get_options_setter({theme => 'white'})."\n". 15963: $captcha->get_html($pubkey,undef,$use_ssl). 15964: &mt('If the text is hard to read, [_1] will replace them.', 15965: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />'). 15966: '<br /><br />'; 15967: } 15968: 15969: sub check_recaptcha { 15970: my ($privkey) = @_; 15971: my $captcha_chk; 15972: my $captcha = Captcha::reCAPTCHA->new; 15973: my $captcha_result = 15974: $captcha->check_answer( 15975: $privkey, 15976: $ENV{'REMOTE_ADDR'}, 15977: $env{'form.recaptcha_challenge_field'}, 15978: $env{'form.recaptcha_response_field'}, 15979: ); 15980: if ($captcha_result->{is_valid}) { 15981: $captcha_chk = 1; 15982: } 15983: return $captcha_chk; 15984: } 15985: 15986: sub emailusername_info { 15987: my @fields = ('firstname','lastname','institution','web','location','officialemail'); 15988: my %titles = &Apache::lonlocal::texthash ( 15989: lastname => 'Last Name', 15990: firstname => 'First Name', 15991: institution => 'School/college/university', 15992: location => "School's city, state/province, country", 15993: web => "School's web address", 15994: officialemail => 'E-mail address at institution (if different)', 15995: ); 15996: return (\@fields,\%titles); 15997: } 15998: 15999: sub cleanup_html { 16000: my ($incoming) = @_; 16001: my $outgoing; 16002: if ($incoming ne '') { 16003: $outgoing = $incoming; 16004: $outgoing =~ s/;/;/g; 16005: $outgoing =~ s/\#/#/g; 16006: $outgoing =~ s/\&/&/g; 16007: $outgoing =~ s/</</g; 16008: $outgoing =~ s/>/>/g; 16009: $outgoing =~ s/\(/(/g; 16010: $outgoing =~ s/\)/)/g; 16011: $outgoing =~ s/"/"/g; 16012: $outgoing =~ s/'/'/g; 16013: $outgoing =~ s/\$/$/g; 16014: $outgoing =~ s{/}{/}g; 16015: $outgoing =~ s/=/=/g; 16016: $outgoing =~ s/\\/\/g 16017: } 16018: return $outgoing; 16019: } 16020: 16021: # Checks for critical messages and returns a redirect url if one exists. 16022: # $interval indicates how often to check for messages. 16023: sub critical_redirect { 16024: my ($interval) = @_; 16025: if ((time-$env{'user.criticalcheck.time'})>$interval) { 16026: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 16027: $env{'user.name'}); 16028: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time}); 16029: my $redirecturl; 16030: if ($what[0]) { 16031: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) { 16032: $redirecturl='/adm/email?critical=display'; 16033: my $url=&Apache::lonnet::absolute_url().$redirecturl; 16034: return (1, $url); 16035: } 16036: } 16037: } 16038: return (); 16039: } 16040: 16041: # Use: 16042: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver); 16043: # 16044: ################################################## 16045: # password associated functions # 16046: ################################################## 16047: sub des_keys { 16048: # Make a new key for DES encryption. 16049: # Each key has two parts which are returned separately. 16050: # Please note: Each key must be passed through the &hex function 16051: # before it is output to the web browser. The hex versions cannot 16052: # be used to decrypt. 16053: my @hexstr=('0','1','2','3','4','5','6','7', 16054: '8','9','a','b','c','d','e','f'); 16055: my $lkey=''; 16056: for (0..7) { 16057: $lkey.=$hexstr[rand(15)]; 16058: } 16059: my $ukey=''; 16060: for (0..7) { 16061: $ukey.=$hexstr[rand(15)]; 16062: } 16063: return ($lkey,$ukey); 16064: } 16065: 16066: sub des_decrypt { 16067: my ($key,$cyphertext) = @_; 16068: my $keybin=pack("H16",$key); 16069: my $cypher; 16070: if ($Crypt::DES::VERSION>=2.03) { 16071: $cypher=new Crypt::DES $keybin; 16072: } else { 16073: $cypher=new DES $keybin; 16074: } 16075: my $plaintext= 16076: $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16)))); 16077: $plaintext.= 16078: $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16)))); 16079: $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) ); 16080: return $plaintext; 16081: } 16082: 16083: 1; 16084: __END__; 16085: