source: trunk/www/filemanager/upload/select.jsp @ 3465

Last change on this file since 3465 was 3465, checked in by Nicklas Nordborg, 16 years ago

Fixes #630.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 16.7 KB
Line 
1<%-- $Id: select.jsp 3465 2007-06-07 11:50:45Z nicklas $
2  ------------------------------------------------------------------
3  Copyright (C) Authors contributing to this file.
4
5  This file is part of BASE - BioArray Software Environment.
6  Available at http://base.thep.lu.se/
7
8  BASE is free software; you can redistribute it and/or
9  modify it under the terms of the GNU General Public License
10  as published by the Free Software Foundation; either version 2
11  of the License, or (at your option) any later version.
12
13  BASE is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with this program; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place - Suite 330,
21  Boston, MA  02111-1307, USA.
22  ------------------------------------------------------------------
23
24
25  @author Nicklas
26  @version 2.0
27--%>
28<%@ page session="false"
29  import="net.sf.basedb.core.SessionControl"
30  import="net.sf.basedb.core.DbControl"
31  import="net.sf.basedb.core.Item"
32  import="net.sf.basedb.core.SystemItems"
33  import="net.sf.basedb.core.ItemContext"
34  import="net.sf.basedb.core.Permission"
35  import="net.sf.basedb.core.Directory"
36  import="net.sf.basedb.core.File"
37  import="net.sf.basedb.core.FileType"
38  import="net.sf.basedb.core.User"
39  import="net.sf.basedb.core.Group"
40  import="net.sf.basedb.core.Quota"
41  import="net.sf.basedb.core.QuotaType"
42  import="net.sf.basedb.core.Location"
43  import="net.sf.basedb.core.PluginDefinition"
44  import="net.sf.basedb.core.Include"
45  import="net.sf.basedb.core.ItemQuery"
46  import="net.sf.basedb.core.ItemResultList"
47  import="net.sf.basedb.core.PermissionDeniedException"
48  import="net.sf.basedb.core.BaseException"
49  import="net.sf.basedb.core.query.Orders"
50  import="net.sf.basedb.core.query.Hql"
51  import="net.sf.basedb.util.zip.FileUnpacker"
52  import="net.sf.basedb.clients.web.Base"
53  import="net.sf.basedb.clients.web.util.HTML"
54  import="net.sf.basedb.util.Values"
55  import="java.util.List"
56  import="java.util.Set"
57  import="java.util.HashSet"
58%>
59<%@ taglib prefix="base" uri="/WEB-INF/base.tld" %>
60<%@ taglib prefix="t" uri="/WEB-INF/tab.tld" %>
61<%
62final Item itemType = Item.FILE;
63final SessionControl sc = Base.getExistingSessionControl(pageContext, true);
64final ItemContext cc = Base.getAndSetCurrentContext(sc, itemType, null, null);
65final int itemId = cc.getId();
66final String ID = sc.getId();
67final float scale = Base.getScale(sc);
68final DbControl dc = sc.newDbControl();
69try
70{
71  String title = null;
72  File file = null;
73  Directory directory = null;
74  boolean readCurrentFileType = true;
75  int currentFileTypeId = 0;
76
77  if (itemId == 0)
78  {
79    title = "Upload new file";
80    currentFileTypeId = Values.getInt(cc.getPropertyValue("fileType"), 0);
81    if (currentFileTypeId == 0)
82    {
83      currentFileTypeId = Values.getInt(cc.getRecent(Item.FILETYPE.name(), 0), 0);
84    }
85    directory = Directory.getById(dc, Values.getInt(request.getParameter("directory_id"), SystemItems.getId(Directory.ROOT)));
86    cc.removeObject("item");
87  }
88  else
89  {
90    file = File.getById(dc, itemId);
91    directory = file.getDirectory();
92    cc.setObject("item", file);
93    title = "Upload again -- " + HTML.encodeTags(file.getName());
94    try
95    {
96      FileType ft = file.getFileType();
97      if (ft != null) currentFileTypeId = ft.getId();
98    }
99    catch (PermissionDeniedException ex)
100    {
101      readCurrentFileType = false;
102    }
103  }
104  if (file != null && !file.hasPermission(Permission.WRITE))
105  {
106    throw new PermissionDeniedException(Permission.WRITE, itemType.toString());
107  }
108 
109  if (file == null || file.getLocation() != Location.PRIMARY)
110  {
111    // Check quota
112    User user = User.getById(dc, sc.getLoggedInUserId());
113    QuotaType totalQuotaType = QuotaType.getById(dc, SystemItems.getId(QuotaType.TOTAL));
114    QuotaType fileQuotaType = QuotaType.getById(dc, SystemItems.getId(QuotaType.FILE));
115   
116    if (user.hasExceededQuota(totalQuotaType, Location.PRIMARY) 
117      || user.hasExceededQuota(fileQuotaType, Location.PRIMARY))
118    {
119      throw new PermissionDeniedException("Quota has been exceeded");
120    }
121  }
122 
123 
124  // Query to retrieve file types
125  final ItemQuery<FileType> fileTypeQuery = FileType.getQuery();
126  fileTypeQuery.order(Orders.asc(Hql.property("name")));
127  fileTypeQuery.setCacheResult(true);
128 
129  // Query to retreive FileUnpacker plugins
130  final ItemQuery<PluginDefinition> pluginQuery = PluginDefinition.getQuery(null, "net.sf.basedb.util.zip.FileUnpacker");
131  pluginQuery.order(Orders.asc(Hql.property("name")));
132  pluginQuery.include(Include.MINE, Include.SHARED, Include.IN_PROJECT, Include.OTHERS);
133  List<PluginDefinition> plugins = pluginQuery.list(dc);
134
135  final String clazz = "class=\"text\"";
136  final String requiredClazz = "class=\"text required\"";
137  %>
138  <base:page type="popup" title="<%=title%>">
139  <base:head scripts="tabcontrol.js,ajax.js" styles="tabcontrol.css,progressbar.css">
140    <script language="JavaScript">
141    // Validate the "File" tab
142    function validateFile()
143    {
144      var frm = document.forms['file'];
145      if (Main.trimString(frm.the_file.value) == '')
146      {
147        alert("You must select a file to upload");
148        frm.the_file.focus();
149        return false;
150      }
151      return true;
152    }
153
154    // Submit the form
155    function doUpload()
156    {
157      var frm = document.forms['file'];
158      if (TabControl.validateActiveTab('settings'))
159      {
160        // Copy form values so they are sent BEFORE the file
161        frm.check_md5.value = frm.temp_check_md5 && frm.temp_check_md5.checked ? "1" : "0";
162        frm.write_protected.value = frm.temp_write_protected.checked ? "1" : "0";
163        if (frm.temp_zip_format)
164        {
165          frm.zip_format.value = frm.temp_zip_format[frm.temp_zip_format.selectedIndex].value;
166          frm.zip_unpack.value = frm.temp_zip_unpack.checked ? "1" : "0";
167          frm.zip_overwrite.value = frm.temp_zip_overwrite.checked ? "1" : "0";
168          frm.zip_keep.value = frm.temp_zip_keep.checked ? "1" : "0";
169        }
170        frm.filetype_id.value = frm.temp_filetype_id[frm.temp_filetype_id.selectedIndex].value;
171        frm.description.value = frm.temp_description.value;
172        frm.submit();
173        Main.hide('selectForm');
174        Main.show('progressForm');
175        if (!sendProgressUpdateWithAjax())
176        {
177          window.top.frames['progress'].location.href = 'progress.jsp?ID=<%=ID%>';
178        }
179      }
180    }
181   
182    function sendProgressUpdateWithAjax()
183    {
184      var request = Ajax.getXmlHttpRequest();
185      if (request != null)
186      {
187        var url = 'progress.jsp?ID=<%=ID%>&ajax=1&'+Math.random();
188        request.open("GET", url, true);
189        Ajax.setReadyStateHandler(request, updateProgressWithAjax);
190        request.send(null);
191      }
192      return request != null;
193    }
194   
195    function updateProgressWithAjax(request)
196    {
197      var response = request.responseText.split(':');
198      //alert(response[0]+':'+response[1]+':'+response[2]+':'+response[3]+':'+response[4]+':'+response[5]);
199      displayProgress(response[0],response[1],response[2],response[3],response[4],response.slice(5).join(':'));
200      setTimeout('sendProgressUpdateWithAjax()', 1500);
201    }
202   
203    function abortUpload()
204    {
205      if (confirm('Are you sure you want to abort the upload? It cannot be resumed.'))
206      {
207        window.top.frames['progress'].location.href = 'progress.jsp?ID=<%=ID%>&abort=1';
208      }
209    }
210   
211    function fileOnChange()
212    {
213      var frm = document.forms['file'];
214      var filename = frm.the_file.value;
215      var isZip = false;
216      var zipIndex = 0;
217      var dotIndex = filename.lastIndexOf('.');
218      if (dotIndex != -1)
219      {
220        var ext = filename.substr(dotIndex+1);
221        var zf = allExtensions[ext];
222        if (zf)
223        {
224          isZip = true;
225          zipIndex = zf.index;
226        }
227      }
228      if (frm.temp_zip_format)
229      {
230        frm['temp_zip_format'].disabled = !isZip;
231        frm['temp_zip_format'].selectedIndex = zipIndex;
232        frm['temp_zip_unpack'].disabled = !isZip;
233        frm['temp_zip_overwrite'].disabled = !isZip || !frm['temp_zip_unpack'].checked;
234        frm['temp_zip_keep'].disabled = !isZip || !frm['temp_zip_unpack'].checked;
235      }
236    }
237    function unpackZipOnClick()
238    {
239      var frm = document.forms['file'];
240      var checked = frm['temp_zip_unpack'].checked;
241      if (!checked) frm['temp_zip_keep'].checked = true;
242      frm['temp_zip_overwrite'].disabled = !checked;
243      frm['temp_zip_keep'].disabled = !checked;
244    }
245   
246    function initZipFormats()
247    {
248      var frm = document.forms['file'];
249      var zipFormat = frm.temp_zip_format;
250      if (zipFormat)
251      {
252      <%
253      for (PluginDefinition plugin : plugins)
254      {
255        FileUnpacker unpacker = plugin.newInstance(FileUnpacker.class, null, sc, null, null);
256        %>
257          var extensions = [ '<%=Values.getString(unpacker.getExtensions(), "','", true)%>' ];
258          var zf = new ZipFormat(zipFormat.length, <%=plugin.getId()%>, '<%=HTML.javaScriptEncode(unpacker.getFormatName())%>', extensions);
259          zipFormat[zipFormat.length] = new Option(zf.toString(), zf.id);
260        <%
261      }
262      %>
263      }
264    }
265   
266    function displayProgress(fileName, transferredBytes, totalBytes, transferTime, remainTime, unpackMessage)
267    {
268      // File name
269      document.getElementById('fileName').innerHTML = 'Uploading ' + fileName + '...';
270       
271      // Percent done
272      var percentDone = totalBytes == 0 ? 0 : Math.round(100 * transferredBytes / totalBytes);
273      document.getElementById('percent').innerHTML = '&nbsp;' + percentDone+'%';
274      var doneElement = document.getElementById('percentDone');
275      doneElement.style.width = percentDone+'%';
276      var remainElement = document.getElementById('percentRemain');
277      remainElement.style.width = (100-percentDone)+'%';
278      if (percentDone == 100) Main.hide('percentRemain');
279     
280      // Bytes
281      document.getElementById('transferredBytes').innerHTML = Numbers.formatBytes(transferredBytes);
282      document.getElementById('totalBytes').innerHTML = Numbers.formatBytes(totalBytes);
283
284      // Times and rate
285      var transferRate = transferTime == 0 ? 0 : transferredBytes / transferTime;
286      document.getElementById('transferTime').innerHTML = Numbers.formatSeconds(transferTime);
287      document.getElementById('transferRate').innerHTML = '(' + Numbers.formatBytes(transferRate) + '/s)';
288      document.getElementById('remainTime').innerHTML = Numbers.formatSeconds(remainTime) + ' (estimated)';
289     
290      // Message
291      if (unpackMessage)
292      {
293        document.getElementById('unpackMessage').innerHTML = unpackMessage.replace(/(.*):(.*)/, '<b>$1:</b> $2');
294      }
295    }
296   
297    var allZipFormats = new Array();
298    var allExtensions = new Array();
299    function ZipFormat(index, id, name, extensions)
300    {
301      this.index = index;
302      this.id = id;
303      this.name = name;
304      this.extensions = extensions;
305     
306      allZipFormats[allZipFormats] = this;
307      // Map extension to ZipFormat object
308      if (extensions && extensions.length)
309      {
310        for (var i = 0; i < extensions.length; i++)
311        {
312          var ext = extensions[i];
313          if (!allExtensions[ext]) allExtensions[ext] = this;
314        }
315      }
316     
317      this.matchesExtension = function(filename)
318      {
319        var dotIndex = filename.lastIndexOf('.');
320        if (dotIndex != -1)
321        {
322          var ext = filename.substr(dotIndex+1);
323          for (var i = 0; i < this.extensions.length; i++)
324          {
325            if (ext == this.extensions[i]) return true;
326          }
327        }
328        return false;
329      }
330     
331      this.toString = function()
332      {
333        var s = this.name + " [";
334        for (var i = 0; i < this.extensions.length; i++)
335        {
336          if (i > 0) s += ', ';
337          s += '*.' + this.extensions[i];
338        }
339        s += ']';
340        return s;
341      }
342    }
343   
344    </script>
345  </base:head>
346  <base:body onload="initZipFormats()">
347  <p>
348  <div id="selectForm">
349    <form action="upload.jsp?ID=<%=ID%>&directory_id=<%=directory.getId()%>" 
350      method="post" name="file" enctype="multipart/form-data" onsubmit="return false;" target="upload">
351
352    <input type="hidden" name="check_md5" value="0">
353    <input type="hidden" name="write_protected" value="0">
354    <input type="hidden" name="zip_format" value="">
355    <input type="hidden" name="zip_unpack" value="0">
356    <input type="hidden" name="zip_overwrite" value="0">
357    <input type="hidden" name="zip_keep" value="1">
358    <input type="hidden" name="filetype_id" value="">
359    <input type="hidden" name="description" value="">
360
361    <h3 class="docked"><%=title%> <base:help tabcontrol="settings" /></h3>
362    <t:tabcontrol id="settings" contentstyle="<%="height: "+(int)(scale*340)+"px;"%>" 
363      position="bottom" remember="false">
364    <t:tab id="info" title="File" validate="validateFile()" helpid="file.upload">
365      <table class="form" cellspacing=0>
366      <tr>
367        <td class="prompt">Directory</td>
368        <td><%=HTML.encodeTags(directory.getPath().toString())%></td>
369      </tr>
370      <tr>
371        <td class="prompt">File</td>
372        <td>
373          <input <%=requiredClazz%> type="file" name="the_file" size="50"
374            onchange="fileOnChange()">
375        </td>
376      </tr>
377      <tr>
378        <td class="prompt">Write protected</td>
379        <td>
380          <input type="checkbox" name="temp_write_protected" value="1" 
381          <%=(file != null && file.isWriteProtected()) || 
382            (file == null && Values.getBoolean(cc.getPropertyValue("writeProtected"))) ? "checked" : ""%>>
383        </td>
384      </tr>
385      <%
386      if (file != null)
387      {
388        %>
389        <tr>
390          <td class="prompt">Validate MD5</td>
391          <td><input type="checkbox" name="temp_check_md5"></td>
392        </tr>
393        <%
394      }
395      %>
396      <tr valign="top">
397        <td class="prompt">Type</td>
398        <td colspan="2">
399          <select name="temp_filetype_id" <%=!readCurrentFileType ? "disabled readonly class=\"disabled\"" : ""%>>
400          <%
401          if (!readCurrentFileType)
402          {
403            %>
404            <option value="-1">- denied -
405            <%
406          }
407          else
408          {
409            %>
410            <option value="0">- none -
411            <%
412            ItemResultList<FileType> fileTypes = fileTypeQuery.list(dc);
413            for (FileType fileType : fileTypes)
414            {
415              int id = fileType.getId();
416              boolean current = id == currentFileTypeId;
417              %>
418              <option 
419                value="<%=current && file != null ? -id : id%>" 
420                <%=current ? "selected" : ""%>
421                ><%=HTML.encodeTags(fileType.getName())%>
422              <%
423            }
424          }
425          %>
426          </select>
427        </td>
428      </tr>
429
430      <tr valign=top>
431        <td class="prompt">Description</td>
432        <td nowrap>
433          <textarea <%=clazz%> rows="4" cols="50" name="temp_description" wrap="virtual"
434            ><%=HTML.encodeTags(file == null ? cc.getPropertyValue("description") : file.getDescription())%></textarea>
435          <a href="javascript:Main.zoom('Description', 'file', 'temp_description')"
436            title="Edit in larger window"><base:icon image="zoom.gif" /></a>
437        </td>
438      </tr>
439     
440      <tr valign=top>
441        <td class="prompt">Max trans-<br>fer rate</td>
442        <td nowrap>
443          <%
444          long maxTransferRate = Values.getInt(sc.getClientDefaultSetting("server.transferRate"), 0);
445          %>
446          <%=maxTransferRate == 0 ? "unlimited" : Values.formatBytes(maxTransferRate)+"/s (approx.)"%>
447        </td>
448      </tr>
449     
450      <%
451      if (file == null)
452      {
453        %>
454        <tr valign=top>
455          <td class="prompt">Compressed file</td>
456          <td>
457            <select name="temp_zip_format" disabled>
458              <option>
459            </select><br>
460         
461            <input type="checkbox" name="temp_zip_unpack" disabled
462              onclick="unpackZipOnClick()"><a 
463              href="javascript:document.forms['file'].temp_zip_unpack.click()">Unpack file</a><br>
464            <input type="checkbox" name="temp_zip_overwrite" disabled
465              ><a 
466              href="javascript:document.forms['file'].temp_zip_overwrite.click()">Overwrite existing files</a><br>
467            <input type="checkbox" name="temp_zip_keep" disabled checked
468              ><a 
469              href="javascript:document.forms['file'].temp_zip_keep.click()">Keep the compressed file</a><br>
470          </td>
471        </tr>
472        <%
473      }
474      %>
475     
476      </table>
477      <div align=right>&nbsp;<i><base:icon image="required.gif" /> = required information</i></div>
478    </t:tab>
479
480    </t:tabcontrol>
481
482    <table align="center">
483    <tr>
484      <td width="50%"><base:button image="upload.gif" onclick="doUpload()" title="Upload" /></td>
485      <td width="50%"><base:button onclick="top.window.close()" title="Cancel" /></td>
486    </tr>
487    </table>
488    </form>
489  </div>
490 
491  <div id="progressForm" style="display:none;">
492    <h3 class="docked" id="fileName">Preparing file upload...</h3>
493    <div class="boxed" style="background: #E0E0E0">
494      <br>
495      <table width="90%" border=0 cellspacing=0 cellpadding=0 align="center">
496      <tr>
497      <td width="90%" >
498        <table width="100%" class="progressbar" border=0 cellspacing=0 cellpadding=0>
499        <tr>
500          <td width="0%" class="done" id="percentDone">&nbsp;</td>
501          <td width="100%" class="remain" id="percentRemain">&nbsp;</td>
502        </tr>
503        </table>
504      </td>
505        <td width="10%" id="percent">&nbsp;0%</td>
506      </tr>
507      <tr>
508        <td colspan="2">
509          <b>Transferred:</b> <span id="transferredBytes">0 bytes</span> of <span id="totalBytes">unknown</span><br>
510          <b>Time:</b> <span id="transferTime">0s</span> <span id="transferRate"></span><br>
511          <b>Remain:</b> <span id="remainTime">unknown</span><br>
512          <span id="unpackMessage"></span>
513        </td>
514      </tr>
515      </table>
516      <br>
517    </div>
518    <br>
519    <table align="center">
520    <tr>
521      <td><base:button image="cancel.gif" onclick="abortUpload()" title="Abort..." /></td>
522    </tr>
523    </table>
524 
525  </div>
526  </base:body>
527  </base:page>
528  <%
529}
530finally
531{
532  if (dc != null) dc.close();
533}
534%>
Note: See TracBrowser for help on using the repository browser.