KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > filemanager > DAVFilemanager_Engine


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 //
14
// Filemanger_Engine
15
// NK 10.02.2001
16
//
17
//
18

19 package org.jahia.engines.filemanager;
20
21 import java.io.File JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Comparator JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.HashSet JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32 import java.util.TreeSet JavaDoc;
33 import java.util.Vector JavaDoc;
34 import java.security.Principal JavaDoc;
35 import java.text.Collator JavaDoc;
36 import javax.servlet.http.HttpSession JavaDoc;
37 import org.apache.slide.content.NodeProperty;
38 import org.apache.slide.webdav.util.WebdavUtils;
39 import org.apache.slide.common.SlideException;
40 import org.apache.slide.macro.MacroException;
41 import org.apache.slide.security.AccessDeniedException;
42 import org.apache.regexp.RE;
43 import org.apache.regexp.RESyntaxException;
44 import org.jahia.data.JahiaData;
45 import org.jahia.data.events.JahiaEvent;
46 import org.jahia.engines.*;
47 import org.jahia.engines.rights.ManageRights;
48 import org.jahia.engines.users.SelectUG_Engine;
49 import org.jahia.exceptions.JahiaException;
50 import org.jahia.exceptions.JahiaForbiddenAccessException;
51 import org.jahia.params.ParamBean;
52 import org.jahia.registries.ServicesRegistry;
53 import org.jahia.services.usermanager.JahiaGroup;
54 import org.jahia.services.usermanager.JahiaGroupManagerService;
55 import org.jahia.services.usermanager.JahiaUser;
56 import org.jahia.services.usermanager.JahiaUserManagerService;
57 import org.jahia.services.webdav.DAVFileAccess;
58 import org.jahia.services.webdav.JahiaWebdavBaseService;
59 import org.jahia.services.acl.JahiaAbstractACL;
60 import org.jahia.services.acl.JahiaBaseACL;
61 import org.jahia.services.applications.ServletIncludeRequestWrapper;
62 import org.jahia.tools.files.FileUpload;
63 import org.jahia.bin.Jahia;
64
65
66 /**
67  * Handle file upload, download, virtual folder structure
68  *
69  * @author Khue ng
70  * @version 1.0
71  */

72 public class DAVFilemanager_Engine implements JahiaEngine {
73     /** Then engine's name */
74     public static final String JavaDoc ENGINE_NAME = "filemanager";
75
76     /** logger instance */
77     private static final org.apache.log4j.Logger logger =
78             org.apache.log4j.Logger.getLogger (Filemanager_Engine.class);
79
80     private static final String JavaDoc FILEEDIT_TEMPLATE_JSP = "filemanager_fileedit";
81     private static final String JavaDoc VIEW_TEMPLATE_JSP = "filemanager_view";
82     private static final String JavaDoc CREATEDIR_TEMPLATE_JSP = "filemanager_createdir";
83     private static final String JavaDoc FILEUPLOAD_TEMPLATE_JSP = "filemanager_fileupload";
84     private static final String JavaDoc FILEUPLOAD_CONFIRM_TEMPLATE_JSP = "filemanager_fileuploadconfirm";
85     private static final String JavaDoc FILERENAME_TEMPLATE_JSP = "filemanager_filerename";
86     private static final String JavaDoc FILEDELETE_TEMPLATE_JSP = "filemanager_filedelete";
87     private static final String JavaDoc FILEUSAGE_TEMPLATE_JSP = "filemanager_fileusage";
88     private static final String JavaDoc MIGRATION_TEMPLATE_JSP = "filemanager_migration";
89     private static final String JavaDoc RIGHTS_JSP = "/jsp/jahia/engines/rights/manage_rights.jsp";
90     private static final String JavaDoc ERROR_JSP = "filemanager_error";
91     private static final String JavaDoc CLOSE_JSP = "filemanager_close";
92
93     private static DAVFilemanager_Engine instance = null;
94
95     private EngineToolBox toolBox;
96
97
98     /**
99      * constructor
100      */

101     protected DAVFilemanager_Engine () {
102         logger.debug ("***** Starting " + DAVFilemanager_Engine.class.getName () +
103                 " engine *****");
104         toolBox = EngineToolBox.getInstance ();
105     }
106
107
108     /**
109      * returns a single instance of the object
110      */

111     public static synchronized DAVFilemanager_Engine getInstance () {
112         if (instance == null) {
113             instance = new DAVFilemanager_Engine ();
114         }
115         return instance;
116     }
117
118
119     /**
120      * authoriseRender
121      */

122     public boolean authoriseRender (ParamBean jParams) {
123         return toolBox.authoriseRender (jParams);
124     }
125
126
127     /**
128      * renderLink
129      */

130     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
131             throws JahiaException {
132         return null;
133     }
134
135
136     /**
137      * needsJahiaData
138      */

139     public boolean needsJahiaData (ParamBean jParams) {
140         return false;
141     }
142
143
144     /**
145      * handdles the engine actions
146      *
147      * @param jParams a ParamBean object
148      * @param jData a JahiaData object (not mandatory)
149      */

150     public void handleActions (ParamBean jParams, JahiaData jData)
151             throws JahiaException {
152         HashMap JavaDoc engineMap = new HashMap JavaDoc ();
153         processLastScreen (jParams, engineMap);
154         initEngineMap (jParams, engineMap);
155
156         String JavaDoc actionScreen = (String JavaDoc) engineMap.get ("screen");
157
158         jParams.getRequest ().getSession ().setAttribute ("filemanager-lastscreen",
159                 actionScreen);
160         String JavaDoc path = jParams.getRequest ().getParameter ("path");
161         if (path == null) {
162             path = "/";
163         }
164
165         engineMap.put ("path", path);
166         path = TableEntry.javascriptDecode(path);
167 // try {
168
if (actionScreen.equals ("view")) {
169             engineMap.put ("act", jParams.getParameter ("act"));
170             List JavaDoc hiddenEntries = new ArrayList JavaDoc ();
171             hiddenEntries.add (path);
172             if (jParams.getParameter ("selectDir") == null &&
173                     jParams.getParameter ("filetree") == null) {
174                 jParams.setParameter ("select-file", path);
175             }
176             prepareFileTree (jParams, engineMap, hiddenEntries, false, false);
177         } else if (actionScreen.equals ("fileDelete")) {
178             List JavaDoc list = JahiaWebdavBaseService.getInstance ().findUsages (path, jParams, false);
179             engineMap.put ("usages", list);
180         } else if (actionScreen.equals ("fileUsage")) {
181             List JavaDoc list = JahiaWebdavBaseService.getInstance ().findUsages (path, jParams, false);
182             engineMap.put ("usages", list);
183         } else if (actionScreen.equals ("rightsMgmt")) {
184             DAVFileAccess objectDav = prepareFileEdit (jParams, path, engineMap);
185             loadAcl (objectDav, jParams, engineMap);
186         } else if (actionScreen.equals ("edit")) {
187             DAVFileAccess objectDav = prepareFileEdit (jParams, path, engineMap);
188             loadProperties (objectDav, jParams, engineMap);
189         } else if (actionScreen.equals ("migrate")) {
190             engineMap.put ("migration_mapping",
191                     JahiaWebdavBaseService.getInstance ().migrate (jParams));
192         }
193 // } catch (AccessDeniedException e) {
194
// throw new JahiaForbiddenAccessException ();
195
//// throw new JahiaException("Webdav repository access denied",
196
//// "User '" + user.getUsername() + "' has no permission to access this engine",
197
//// JahiaException.ENGINE_ERROR, JahiaException.WARNING_SEVERITY);
198
// } catch (ObjectNotFoundException e) {
199
// throw new JahiaException("File not found",
200
// "User '" + user.getUsername() + "' has no permission to access this engine",
201
// JahiaException.ENGINE_ERROR, JahiaException.WARNING_SEVERITY);
202
// }
203

204         toolBox.displayScreen (jParams, engineMap);
205     }
206
207
208     /**
209      * Retrieve the engine name.
210      *
211      * @return the engine name.
212      */

213     public final String JavaDoc getName () {
214         return ENGINE_NAME;
215     }
216
217
218     private DAVFileAccess prepareFileEdit (ParamBean jParams, String JavaDoc path, HashMap JavaDoc engineMap)
219             throws JahiaException {
220         DAVFileAccess objectDav = JahiaWebdavBaseService.getInstance ().getDAVFileAccess (
221                 jParams, jParams.getSite(), jParams.getUser(), path);
222         if (path == null) {
223             throw new JahiaException ("No file specified",
224                     "No file specified",
225                     JahiaException.ENGINE_ERROR, JahiaException.WARNING_SEVERITY);
226         }
227         engineMap.put ("fileNode", objectDav);
228         return objectDav;
229     }
230
231     private void processLastScreen (ParamBean jParams, HashMap JavaDoc engineMap)
232             throws JahiaException {
233         String JavaDoc lastScreen = (String JavaDoc) jParams.getRequest ().getSession ().getAttribute (
234                 "filemanager-lastscreen");
235         if (lastScreen == null) {
236             return;
237         }
238         String JavaDoc actionScreen = jParams.getParameter ("screen");
239         if (actionScreen.equals ("cancel")) {
240             jParams.setParameter ("screen", "close");
241         }
242         if (!actionScreen.equals ("save") && !actionScreen.equals ("apply")) {
243             return;
244         }
245         boolean result = false;
246         String JavaDoc path = jParams.getParameter ("path");
247         if (path == null) {
248             return;
249         }
250
251         DAVFileAccess objectDav = JahiaWebdavBaseService.getInstance ().getDAVFileAccess (
252                 jParams, jParams.getSite(), jParams.getUser(), TableEntry.javascriptDecode(path));
253
254         if (objectDav.getException () == null) {
255             objectDav.beginTransaction ();
256
257             if (actionScreen.equals ("save")) {
258                 jParams.setParameter ("screen", "close");
259             } else if (actionScreen.equals ("apply")) {
260                 jParams.setParameter ("screen", lastScreen);
261             }
262
263             try{
264                 if (lastScreen.equals ("view")) {
265                     String JavaDoc action = jParams.getParameter ("act");
266                     if (action.equals ("move")) {
267                         try {
268                             result = moveFile (objectDav, jParams, engineMap);
269                         } catch (MacroException e) {
270                             if (isAccessDenied(e)) {
271                                 jParams.getRequest().setAttribute("error", "org.jahia.engines.filemanager.Filemanager_Engine.moveDenied.label");
272                             }
273                         }
274                     } else if (action.equals ("copy")) {
275                         try {
276                             result = copyFile (objectDav, jParams, engineMap);
277                         } catch (MacroException e) {
278                             if (isAccessDenied(e)) {
279                                 // ignore access denied
280
result = true;
281                             }
282                         }
283                     }
284                 } else if (lastScreen.equals ("edit")) {
285                     result = editFile (objectDav, jParams, engineMap);
286                 } else if (lastScreen.equals ("fileDelete")) {
287                     try {
288                         result = deleteFile (objectDav, jParams, engineMap);
289                     } catch (MacroException e) {
290                         if (isAccessDenied(e)) {
291                             jParams.getRequest().setAttribute("error", "org.jahia.engines.filemanager.Filemanager_Engine.deleteDenied.label");
292                         }
293                     }
294                 } else if (lastScreen.equals ("fileRename")) {
295                     try {
296                         result = renameFile (objectDav, jParams, engineMap);
297                     } catch (MacroException e) {
298                         if (isAccessDenied(e)) {
299                             jParams.getRequest().setAttribute("error", "org.jahia.engines.filemanager.Filemanager_Engine.renameDenied.label");
300                         }
301                     }
302                 } else if (lastScreen.equals ("rightsMgmt")) {
303                     result = saveAcl (objectDav, jParams, engineMap);
304                     if (!result) {
305                         jParams.getRequest().setAttribute("error", "org.jahia.engines.filemanager.Filemanager_Engine.permissionError.label");
306                     }
307                 } else if (lastScreen.equals ("createDir")) {
308                     jParams.getRequest ().getSession ().setAttribute ("changeDir",
309                             TableEntry.javascriptEncode(objectDav.getPath ()));
310                     result = createCollection (objectDav, jParams, engineMap);
311                 } else if (lastScreen.equals ("fileUpload")) {
312                     jParams.getRequest ().getSession ().setAttribute ("changeDir",
313                             TableEntry.javascriptEncode(objectDav.getPath ()));
314                     result = uploadFile (objectDav, jParams, engineMap);
315                 } else if (lastScreen.equals ("fileUploadConfirm")) {
316                     jParams.getRequest ().getSession ().setAttribute ("changeDir",
317                             TableEntry.javascriptEncode(objectDav.getPath ()));
318                     result = uploadConfirm (objectDav, jParams, engineMap);
319                 }
320             } catch (SlideException e) {
321                 logger.debug("Error when doing slide operation : "+e.getMessage());
322                 // Unknown error ?
323
}
324
325             if (result) {
326                 objectDav.commitTransaction ();
327             } else {
328                 objectDav.rollbackTransaction ();
329                 if (jParams.getRequest().getAttribute("error") == null) {
330                     jParams.getRequest().setAttribute("error", "org.jahia.engines.filemanager.Filemanager_Engine.filemanagerError.label");
331                 }
332                 jParams.setParameter ("screen", "error");
333             }
334         }
335     }
336
337     private boolean isAccessDenied(MacroException e) {
338         Enumeration JavaDoc en = e.enumerateExceptions();
339         while (en.hasMoreElements()) {
340             Exception JavaDoc exception = (Exception JavaDoc) en.nextElement();
341             if (!(exception instanceof AccessDeniedException)) {
342                 return false;
343             }
344         }
345         return true;
346     }
347
348     public void prepareFileTree (ParamBean jParams, HashMap JavaDoc engineMap, List JavaDoc hiddenEntries,
349                                  boolean flat, boolean filesInTree) throws JahiaException {
350         engineMap.remove ("dirEntries");
351
352         try {
353             if (flat) {
354                 String JavaDoc defaultFolder;
355                 if (jParams.getUser () != null) {
356                     defaultFolder = TableEntry.javascriptEncode("/users/" + jParams.getUser ().getUsername ());
357                 } else {
358                     defaultFolder = "/";
359                 }
360                 prepareFileTree (jParams, defaultFolder, engineMap, hiddenEntries, flat,
361                         filesInTree);
362             } else {
363                 prepareFileTree (jParams, "/groups", engineMap, hiddenEntries, flat,
364                         filesInTree);
365                 prepareFileTree (jParams, "/shared", engineMap, hiddenEntries, flat,
366                         filesInTree);
367                 prepareFileTree (jParams, "/users", engineMap, hiddenEntries, flat,
368                         filesInTree);
369             }
370         } catch (JahiaForbiddenAccessException e) {
371         }
372         engineMap.put ("fileManagerEngineUrl", jParams.composeEngineUrl ("filemanager"));
373     }
374
375     private void prepareFileTree (ParamBean jParams, String JavaDoc path, HashMap JavaDoc engineMap,
376                                   List JavaDoc hiddenEntries, boolean flat, boolean filesInTree)
377             throws JahiaException {
378         HttpSession JavaDoc httpsession = jParams.getRequest ().getSession ();
379         httpsession.setAttribute ("filepicker-expand-/", "on");
380
381         String JavaDoc selectedDir = jParams.getParameter ("selectDir");
382         String JavaDoc changeDir = (String JavaDoc) httpsession.getAttribute ("changeDir");
383         if (changeDir != null) {
384             httpsession.removeAttribute ("changeDir");
385             selectedDir = changeDir;
386         }
387
388         String JavaDoc selectedFile = jParams.getParameter ("select-file");
389
390         if (selectedDir == null && selectedFile == null) {
391             selectedFile = path;
392         }
393
394         if (selectedFile != null) {
395             httpsession.setAttribute (jParams.getSiteID () + "-filepicker-selectedfile",
396                     selectedFile);
397             if ((!flat || selectedDir == null) && selectedFile.indexOf ('/') == 0) {
398                 selectedDir = selectedFile.substring (0, selectedFile.lastIndexOf ('/'));
399             }
400         }
401
402         if (selectedDir == null) {
403             selectedDir = (String JavaDoc) httpsession.getAttribute (
404                     jParams.getSiteID () + "-filepicker-selecteddir");
405         }
406         if (flat && selectedDir == null) {
407             selectedDir = path;
408         }
409
410         if (selectedDir != null) {
411             httpsession.setAttribute (jParams.getSiteID () + "-filepicker-selecteddir",
412                     selectedDir);
413
414             String JavaDoc expandedDir = selectedDir;
415             while (expandedDir.lastIndexOf ('/') >= 0) {
416                 httpsession.setAttribute (jParams.getSiteID () + "-filepicker-expand-" +
417                         expandedDir,
418                         "on");
419                 expandedDir = expandedDir.substring (0, expandedDir.lastIndexOf ('/'));
420             }
421         }
422
423
424         String JavaDoc filetreeparam = jParams.getRequest ().getParameter ("filetree");
425         if (filetreeparam != null) {
426             if (filetreeparam.startsWith ("collapse|")) {
427                 String JavaDoc expPath = filetreeparam.substring (9);
428                 httpsession.removeAttribute (jParams.getSiteID () + "-filepicker-expand-" +
429                         expPath);
430             } else if (filetreeparam.startsWith ("expand|")) {
431                 String JavaDoc expPath = filetreeparam.substring (7);
432                 httpsession.setAttribute (
433                         jParams.getSiteID () + "-filepicker-expand-" + expPath,
434                         "on");
435             } else if (filetreeparam.startsWith ("expandall|")) {
436                 String JavaDoc expPath = filetreeparam.substring (10);
437                 httpsession.setAttribute (
438                         jParams.getSiteID () + "-filepicker-expand-" + expPath,
439                         "all");
440             }
441         }
442
443         // selected dir actions
444
DAVFileAccess objectDav;
445         if (flat) {
446             objectDav = JahiaWebdavBaseService.getInstance ().getDAVFileAccess (jParams,
447                     jParams.getSite(), jParams.getUser(), TableEntry.javascriptDecode(selectedDir));
448         } else {
449             objectDav = JahiaWebdavBaseService.getInstance ().getDAVFileAccess (jParams,
450                     jParams.getSite(), jParams.getUser(), TableEntry.javascriptDecode(path));
451         }
452
453         List JavaDoc dirEntries = (List JavaDoc) engineMap.get ("dirEntries");
454         if (dirEntries == null) {
455             dirEntries = new ArrayList JavaDoc ();
456             engineMap.put ("dirEntries", dirEntries);
457         }
458
459         hiddenEntries.add ("/actions");
460         createEntries (objectDav, dirEntries, hiddenEntries, -1, 0, false, jParams, filesInTree,
461                 false, false, !flat);
462         engineMap.put ("hiddenEntries", hiddenEntries);
463     }
464
465
466     private int createEntries (DAVFileAccess object, List JavaDoc dirEntries, List JavaDoc hiddenEntries,
467                                int parentIndex, int indent, boolean expandAll,
468                                ParamBean jParams, boolean filesInTree, boolean canWriteParent,
469                                boolean canAdminParent, boolean recurse) {
470         int count = 0;
471         int index = dirEntries.size ();
472         String JavaDoc path = TableEntry.javascriptEncode(object.getPath ());
473         expandAll |= ("all".equals (
474                 jParams.getRequest ().getSession ().getAttribute (
475                         jParams.getSiteID () + "-filepicker-expand-" + path)));
476         if (expandAll) {
477             jParams.getRequest ().getSession ().setAttribute (
478                     jParams.getSiteID () + "-filepicker-expand-" + path, "on");
479         }
480
481         boolean expanded = jParams.getRequest ().getSession ().getAttribute (
482                 jParams.getSiteID () + "-filepicker-expand-" + path) !=
483                 null;
484         boolean selectedDir = jParams.getRequest ().getSession ().getAttribute (
485                 jParams.getSiteID () + "-filepicker-selecteddir") !=
486                 null &&
487                 jParams.getRequest ().getSession ().getAttribute (
488                         jParams.getSiteID () + "-filepicker-selecteddir")
489                 .equals (path);
490 // boolean valid = !WebdavUtils.isCollection(token,slideToken, path);
491

492         boolean canWrite = object.hasPermission (DAVFileAccess.WRITE) && object.isWriteable ();
493         boolean canAdmin = object.hasPermission (DAVFileAccess.MANAGE);
494         boolean hasRevisions = object.hasRevisions ();
495         boolean isLocked = object.isLocked ();
496         TableEntry entry = new TableEntry (object.getPath (), object.getName (), expanded, indent,
497                 "collection", canWrite, canAdmin, canWriteParent, canAdminParent, hasRevisions,
498                 isLocked);
499         dirEntries.add (entry);
500
501
502         // Displaying ACL info
503
// if( org.apache.slide.util.Configuration.useIntegratedSecurity() )
504
// displayPermissions(permissionsList, writer, false);
505
//
506
// Displaying lock info
507
// displayLocks(locksList, writer, false);
508

509
510         if (expanded) {
511             int lastIndex = -1;
512             List JavaDoc resources = object.getChildren ();
513             final Collator JavaDoc collator = Collator.getInstance(jParams.getLocale());
514             TreeSet JavaDoc sortedResources = new TreeSet JavaDoc (new Comparator JavaDoc () {
515                 public int compare (Object JavaDoc o1, Object JavaDoc o2) {
516                     DAVFileAccess davFileAccess1 = (DAVFileAccess) o1;
517                     DAVFileAccess davFileAccess2 = (DAVFileAccess) o2;
518                     boolean collection1 = davFileAccess1.isCollection ();
519                     boolean collection2 = davFileAccess2.isCollection ();
520                     if (collection1 != collection2) {
521                         return collection1 ? -1 : 1;
522                     } else {
523                         int i = collator.compare(davFileAccess1.getPath (),davFileAccess2.getPath ());
524                         return i==0 ? 1 : i;
525                     }
526                 }
527             });
528             sortedResources.addAll (resources);
529             entry.setHasChildren (false);
530             for (Iterator JavaDoc iterator = sortedResources.iterator (); iterator.hasNext ();) {
531                 DAVFileAccess resource = (DAVFileAccess) iterator.next ();
532                 if (!hiddenEntries.contains (resource.getPath ())) {
533                     if (resource.isCollection ()) {
534                         entry.setHasChildren (true);
535                         lastIndex = dirEntries.size ();
536                         if (recurse) {
537                             count += createEntries (resource, dirEntries, hiddenEntries,
538                                     index, indent + 1, expandAll, jParams, filesInTree,
539                                     canWrite, canAdmin, recurse);
540                         } else {
541                             dirEntries.add (
542                                     new TableEntry (resource.getPath (), resource.getName (),
543                                             false, indent + 1, "collection",
544                                             resource.hasPermission (DAVFileAccess.WRITE) &&
545                                     resource.isWriteable (),
546                                             resource.hasPermission (DAVFileAccess.MANAGE),
547                                             canWrite, canAdmin, resource.hasRevisions (),
548                                             resource.isLocked ()));
549                             count++;
550                         }
551                     } else if (filesInTree) {
552                         entry.setHasChildren (true);
553                         lastIndex = dirEntries.size ();
554                         dirEntries.add (
555                                 new TableEntry (resource.getPath (), resource.getName (),
556                                         false, indent + 1,
557                                         resource.getJahiaFileField ().getType (),
558                                         resource.hasPermission (DAVFileAccess.WRITE) &&
559                                 resource.isWriteable (),
560                                         resource.hasPermission (DAVFileAccess.MANAGE),
561                                         canWrite, canAdmin, resource.hasRevisions (),
562                                         resource.isLocked ()));
563                         count++;
564                     } else if (!filesInTree && selectedDir) {
565 // fileEntries.add( resource.getJahiaFileField() );
566
}
567                 }
568             }
569             if (lastIndex != -1) {
570                 ((TableEntry) dirEntries.get (lastIndex)).setLastSister (true);
571             }
572         } else {
573             entry.setHasChildren (true);
574         }
575         return count + 1;
576     }
577
578     /**
579      * Prepare the datas to display in the engine.
580      *
581      * @param jParams ;)
582      *
583      * @throws JahiaException
584      */

585     private void initEngineMap (ParamBean jParams, HashMap JavaDoc engineMap)
586             throws JahiaException {
587         engineMap.clear ();
588
589         String JavaDoc theScreen = jParams.getParameter ("screen");
590
591
592         if (theScreen == null) {
593             theScreen = "view";
594         }
595
596         if (theScreen.equals ("close")) {
597             engineMap.put ("jspSource", CLOSE_JSP);
598         } else if (theScreen.equals ("error")) {
599             engineMap.put ("jspSource", ERROR_JSP);
600         } else if (theScreen.equals ("createDir")) {
601             engineMap.put ("jspSource", CREATEDIR_TEMPLATE_JSP);
602         } else if (theScreen.equals ("fileUpload")) {
603             engineMap.put ("jspSource", FILEUPLOAD_TEMPLATE_JSP);
604         } else if (theScreen.equals ("fileUploadConfirm")) {
605             engineMap.put ("jspSource", FILEUPLOAD_CONFIRM_TEMPLATE_JSP);
606         } else if (theScreen.equals ("fileDelete")) {
607             engineMap.put ("jspSource", FILEDELETE_TEMPLATE_JSP);
608         } else if (theScreen.equals ("fileUsage")) {
609             engineMap.put ("jspSource", FILEUSAGE_TEMPLATE_JSP);
610         } else if (theScreen.equals ("fileRename")) {
611             engineMap.put ("jspSource", FILERENAME_TEMPLATE_JSP);
612         } else if (theScreen.equals ("view")) {
613             engineMap.put ("jspSource", VIEW_TEMPLATE_JSP);
614         } else if (theScreen.equals ("edit")) {
615             engineMap.put ("jspSource", FILEEDIT_TEMPLATE_JSP);
616         } else if (theScreen.equals ("rightsMgmt")) {
617             engineMap.put ("jspSource", FILEEDIT_TEMPLATE_JSP);
618         } else if (theScreen.equals ("migrate")) {
619             engineMap.put ("jspSource", MIGRATION_TEMPLATE_JSP);
620         }
621
622         engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
623         engineMap.put ("screen", theScreen);
624         engineMap.put (ENGINE_NAME_PARAM, ENGINE_NAME);
625         String JavaDoc value = jParams.composeEngineUrl (ENGINE_NAME, EMPTY_STRING);
626         engineMap.put (ENGINE_URL_PARAM, value);
627         engineMap.put ("fileManagerEngineUrl", jParams.composeEngineUrl (ENGINE_NAME, EMPTY_STRING));
628
629         jParams.getRequest ().setAttribute ("engineTitle", "File Manager"); // Displayed in 'engine.jsp'
630
jParams.getRequest ().setAttribute ("org.jahia.engines.EngineHashMap", engineMap);
631     }
632
633     private boolean editFile (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) {
634         Map JavaDoc props = dav.getProperties ();
635         for (Iterator JavaDoc iterator = props.keySet ().iterator (); iterator.hasNext ();) {
636             String JavaDoc key = (String JavaDoc) iterator.next ();
637             String JavaDoc value = jParams.getParameter (key);
638             if (value != null) {
639                 if ("DAV:displayname".equals (key)) {
640                     dav.setName (value);
641                 } else {
642                     NodeProperty p = (NodeProperty) props.get (key);
643                     if (p != null && !p.isProtected ()) {
644                         dav.setProperty (p.getNamespace (), p.getName (), value, false);
645                     }
646                 }
647             }
648         }
649         if (jParams.getParameter ("newName") != null &&
650                 jParams.getParameter ("newValue") != null &&
651                 jParams.getParameter ("newName").length () > 0) {
652             dav.setProperty ("http://www.jahia.org/", jParams.getParameter ("newName"),
653                     jParams.getParameter ("newValue"), false);
654         }
655         return true;
656     }
657
658     private boolean moveFile (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) throws SlideException {
659         String JavaDoc dest = TableEntry.javascriptDecode(jParams.getParameter ("selectDir"));
660         String JavaDoc path = dav.getPath ();
661         boolean b = dav.moveFile (dest);
662         jParams.getRequest ().getSession ().setAttribute (jParams.getSiteID () + "-movedfrom",
663                 path);
664         jParams.getRequest ().getSession ().setAttribute (jParams.getSiteID () + "-movedto",
665                 dav.getPath ());
666         return b;
667     }
668
669     private boolean copyFile (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) throws SlideException {
670         String JavaDoc dest = TableEntry.javascriptDecode(jParams.getParameter ("selectDir"));
671         return dav.copyFile (dest);
672     }
673
674     private boolean renameFile (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) throws SlideException {
675         String JavaDoc newName = jParams.getParameter ("new_name");
676         String JavaDoc path = dav.getPath ();
677         boolean b = dav.renameFile (newName);
678         jParams.getRequest ().getSession ().setAttribute (jParams.getSiteID () + "-movedfrom",
679                 path);
680         jParams.getRequest ().getSession ().setAttribute (jParams.getSiteID () + "-movedto",
681                 dav.getPath ());
682         return b;
683     }
684
685     private boolean deleteFile (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) throws SlideException {
686         return dav.deleteFile ();
687     }
688
689
690     private boolean createCollection (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) {
691         String JavaDoc dirName = jParams.getParameter ("dir_name");
692         jParams.getRequest ().getSession ().setAttribute (
693                 jParams.getSiteID () + "-filepicker-expand-" + dav.getPath (), "on");
694
695         return dav.createCollection (dirName) != null;
696     }
697
698     private boolean uploadFile (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) {
699         if (ParamBean.isMultipartRequest (jParams.getRequest ())) {
700             try {
701                 String JavaDoc savePath = jParams.settings ().getTmpContentDiskPath();
702                 File JavaDoc tmp = new File JavaDoc (savePath);
703                 if (!tmp.exists ()) {
704                     tmp.mkdir ();
705                 }
706                 FileUpload fupload = new FileUpload (jParams.getContext (), jParams.getRequest (),
707                         savePath, jParams.settings().getJahiaFileUploadMaxSize());
708
709                 // get files name
710
Enumeration JavaDoc filesName = fupload.getFileNames ();
711
712                 Vector JavaDoc existingFiles = new Vector JavaDoc ();
713                 Vector JavaDoc canOverwrite = new Vector JavaDoc ();
714                 while (filesName.hasMoreElements ()) {
715                     String JavaDoc name = (String JavaDoc) filesName.nextElement ();
716                     if (fupload.getFileSystemName (name) == null) {
717                         continue;
718                     }
719                     String JavaDoc filename = decodeStrangeBrowserEncoding(fupload.getFileSystemName (name));
720                     filename = JahiaWebdavBaseService.getInstance().cleanTitle(filename);
721                     if (Jahia.getSettings().isTransformFilenames()) {
722                         filename = DAVFileAccess.cleanName(filename);
723                     }
724                     DAVFileAccess old = JahiaWebdavBaseService.getInstance ().getDAVFileAccess (
725                             jParams, jParams.getSite(), jParams.getUser(), dav.getPath () + "/" + filename);
726                     if (old.isValid ()) {
727                         existingFiles.add (name);
728                         if (old.hasPermission (DAVFileAccess.WRITE) && old.isWriteable ()) {
729                             canOverwrite.add (name);
730                         }
731                     } else {
732                         doUpload (fupload, name, jParams, filename, dav);
733                     }
734                 }
735                 if (!existingFiles.isEmpty ()) {
736                     jParams.getRequest ().getSession ().setAttribute ("lastFupload", fupload);
737                     jParams.getRequest ().getSession ().setAttribute (
738                             "lastFuploadExistingFiles",
739                             existingFiles);
740                     jParams.getRequest ().getSession ().setAttribute (
741                             "lastFuploadCanOverwrite",
742                             canOverwrite);
743                     jParams.setParameter ("screen", "fileUploadConfirm");
744                 }
745             } catch (IOException JavaDoc e) {
746                 logger.warn("File upload failed!", e);
747                 return false;
748             }
749         }
750         jParams.getRequest ().getSession ().setAttribute (
751                 jParams.getSiteID () + "-filepicker-expand-" + dav.getPath (), "on");
752         return true;
753     }
754
755
756     private boolean uploadConfirm (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) {
757         boolean result;
758         try {
759             FileUpload fupload = (FileUpload) jParams.getRequest ().getSession ().getAttribute (
760                     "lastFupload");
761             Vector JavaDoc existingFiles = (Vector JavaDoc) jParams.getRequest ().getSession ().getAttribute (
762                     "lastFuploadExistingFiles");
763             for (Iterator JavaDoc iterator = existingFiles.iterator (); iterator.hasNext ();) {
764                 String JavaDoc name = (String JavaDoc) iterator.next ();
765                 String JavaDoc filename = decodeStrangeBrowserEncoding(fupload.getFileSystemName (name));
766                 String JavaDoc action = jParams.getParameter ("action-" + name);
767                 if (action.equals ("overwrite")) {
768                     result = doUpload (fupload, name, jParams, filename, dav);
769                 } else if (action.equals ("rename")) {
770                     int i = 1;
771                     int dot = filename.lastIndexOf ('.');
772                     String JavaDoc newName = JahiaWebdavBaseService.getInstance().cleanTitle(filename);
773                     if (Jahia.getSettings().isTransformFilenames()) {
774                         newName = DAVFileAccess.cleanName(newName);
775                     }
776
777                     while (JahiaWebdavBaseService.getInstance ().getDAVFileAccess (jParams,
778                             jParams.getSite(), jParams.getUser(), dav.getPath () + "/" + newName)
779                             .isValid ()) {
780                         if (dot > -1) {
781                             newName = filename.substring (0, dot) + "_" + (i++) +
782                                     filename.substring (dot);
783                             newName = JahiaWebdavBaseService.getInstance().cleanTitle(newName);
784                             if (Jahia.getSettings().isTransformFilenames()) {
785                                 newName = DAVFileAccess.cleanName(newName);
786                             }
787                         } else {
788                             newName = filename + "_" + (i++);
789                             newName = JahiaWebdavBaseService.getInstance().cleanTitle(newName);
790                             if (Jahia.getSettings().isTransformFilenames()) {
791                                 newName = DAVFileAccess.cleanName(newName);
792                             }
793                         }
794                     }
795                     result = doUpload (fupload, name, jParams, newName, dav);
796                 } else if (action.equals ("version")) {
797
798                 }
799             }
800             result = true;
801         } catch (Exception JavaDoc e) {
802             logger.error("Error when uploading file", e);
803             result = false;
804         } finally {
805             jParams.getRequest ().getSession ().removeAttribute ("lastFupload");
806             jParams.getRequest ().getSession ().removeAttribute ("lastFuploadExistingFiles");
807             jParams.getRequest ().getSession ().removeAttribute ("lastFuploadCanOverwrite");
808         }
809         return result;
810     }
811
812     private boolean doUpload (FileUpload fupload, String JavaDoc name, ParamBean jParams, String JavaDoc filename,
813                            DAVFileAccess dav) {
814         File JavaDoc f = fupload.getFile (name);
815         if (f != null && f.exists () && f.canWrite ()) {
816             String JavaDoc contentType = fupload.getFileContentType (name);
817             if (contentType == null) {
818                 contentType = jParams.getContext ().getMimeType (filename);
819             }
820             String JavaDoc finalName = dav.uploadFile (filename, fupload.getFile (name), contentType, false);
821             fupload.getFile (name).delete ();
822             jParams.getRequest ().getSession ().setAttribute (jParams.getSiteID () +
823                     "-justUploaded",
824                     dav.getPath () + "/" + finalName);
825             return (filename != null);
826         }
827         return false;
828     }
829
830     private boolean loadAcl (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap)
831             throws JahiaException {
832         if (dav == null) {
833             return false;
834         }
835         engineMap.put("hasNegativePermissions", Boolean.TRUE);
836         engineMap.put("actionNames", JahiaAbstractACL.getActionNames());
837         
838         Map JavaDoc readPerms = dav.getPermissions (DAVFileAccess.READ);
839         Map JavaDoc writePerms = dav.getPermissions (DAVFileAccess.WRITE);
840         Map JavaDoc adminPerms = dav.getPermissions (DAVFileAccess.MANAGE);
841
842         Set JavaDoc allUsers = new HashSet JavaDoc ();
843         allUsers.addAll (readPerms.keySet ());
844         allUsers.addAll (writePerms.keySet ());
845         allUsers.addAll (adminPerms.keySet ());
846
847         HashMap JavaDoc aclEntries = new HashMap JavaDoc ();
848         for (Iterator JavaDoc iterator = allUsers.iterator (); iterator.hasNext ();) {
849             String JavaDoc s = (String JavaDoc) iterator.next ();
850
851             int permissions = 0;
852             permissions |= getPermissionsAsInt(
853               s, JahiaBaseACL.READ_RIGHTS, readPerms);
854             permissions |= getPermissionsAsInt(
855               s, JahiaBaseACL.WRITE_RIGHTS, writePerms);
856             permissions |= getPermissionsAsInt(
857               s, JahiaBaseACL.ADMIN_RIGHTS, adminPerms);
858
859             if (s.equals ("nobody") || s.equals ("all")) {
860                 s = "+/groups/" + JahiaGroupManagerService.GUEST_GROUPNAME + "/members";
861             } else if (s.equals ("root")) {
862                 s = "+/groups/" + JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME +
863                         "/members";
864             } else if (s.equals ("user") || s.equals ("authenticated")) {
865                 s = "+/groups/" + JahiaGroupManagerService.USERS_GROUPNAME + "/members";
866             } else if (s.equals ("guest") || s.equals ("unauthenticated")) {
867                 s = "/users/" + JahiaUserManagerService.GUEST_USERNAME + "/members";
868             }
869             if (s.startsWith ("+/groups/")) {
870                 JahiaGroup group = ServicesRegistry.getInstance ().getJahiaGroupManagerService ()
871                         .lookupGroup (jParams.getSiteID (), s.substring (9, s.lastIndexOf ('/')));
872                 if (group == null) {
873                     continue;
874                 }
875                 aclEntries.put (group, new Integer JavaDoc(permissions));
876
877             } else if (s.startsWith ("/users/")) {
878                 String JavaDoc name = s.substring (7);
879                 if (name.indexOf ('/') > -1) {
880                     name = name.substring (0, name.indexOf ('/'));
881                 }
882                 JahiaUser jahiaUser = null;
883                 try {
884                     jahiaUser = ServicesRegistry.getInstance ().getJahiaSiteUserManagerService ()
885                             .getMember (jParams.getSiteID (), name);
886                 } catch (JahiaException e) {
887                     continue;
888                 }
889                 aclEntries.put (jahiaUser, new Integer JavaDoc(permissions));
890 // aclEntries.add(JahiaTools.replacePattern(value, " ", " "));
891
// aclEntries.add(JahiaTools.replacePattern(aclEntryStr, " ",
892
// " "));
893
}
894         }
895         engineMap.put ("aclEntries", aclEntries);
896         engineMap.put ("noInheritanceCut", Boolean.TRUE);
897         engineMap.put ("selectUsrGrp", SelectUG_Engine.getInstance ().renderLink (jParams, EMPTY_STRING));
898         engineMap.put ("inheritance", new Integer JavaDoc (0));
899         engineMap.put ("fieldForm", ServicesRegistry.getInstance ().
900                 getJahiaFetcherService ().fetchServlet (jParams, RIGHTS_JSP));
901 // engineMap.put()
902
return true;
903     }
904
905     private boolean loadProperties (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) {
906         engineMap.put ("properties", dav.getProperties ());
907         engineMap.put ("canWrite",
908                 new Boolean JavaDoc (dav.hasPermission (DAVFileAccess.WRITE) && dav.isWriteable ()));
909         return true;
910     }
911
912     private boolean saveAcl (DAVFileAccess dav, ParamBean jParams, HashMap JavaDoc engineMap) {
913         // Check if the inheritance has to be permanently prevent or not.
914
Integer JavaDoc userNameWidth = (Integer JavaDoc) jParams.getRequest ().getSession ().getAttribute (
915                 "userNameWidth");
916         String JavaDoc cutRestAllInherit = jParams.getRequest ().getParameter ("cutRestAllInherit");
917         if (cutRestAllInherit != null) { // Is the check box checked ?
918
// if (acl.getInheritance() == ACLInfo.INHERITANCE) { // Has it changed ?
919
// acl.setInheritance(ACLInfo.NO_INHERITANCE);
920
// }
921
} else {
922 // if (acl.getInheritance() == ACLInfo.NO_INHERITANCE) { // Has the checkbox changed ?
923
// acl.setInheritance(ACLInfo.INHERITANCE);
924
// }
925
}
926         String JavaDoc[] submitedACLEntries = jParams.getRequest ().getParameterValues ("aclEntries");
927         if (submitedACLEntries == null || submitedACLEntries[0].substring (0, 4).equals (
928                 "null")) {
929             return true;
930         }
931         for (int i = 0; i < submitedACLEntries.length; i++) {
932             String JavaDoc aclEntry = submitedACLEntries[i];
933             if ("00000000".equals (aclEntry.substring (0, 8))) {
934                 continue; // Don't do anything if no changes to the ACL entry.
935
}
936             // What kind of object has to be saved : user or group ?
937
// String usr_grpName;
938
Principal JavaDoc usr_grp;
939             String JavaDoc subject;
940             logger.debug ("Submited ACL entry : " + aclEntry);
941             ManageRights mRights = ManageRights.getInstance();
942             int keyIndex = mRights.getVKey(userNameWidth);
943             switch (aclEntry.charAt(keyIndex - 1)) {
944             case 'u':
945                 usr_grp = ServicesRegistry.getInstance ().getJahiaUserManagerService ().
946                         lookupUser (
947                                 aclEntry.substring (keyIndex));
948 // usr_grpName = ((JahiaUser)usr_grp).getUsername();
949
String JavaDoc username = ((JahiaUser)usr_grp).getUsername ();
950 // if (JahiaUserManagerService.GUEST_USERNAME.equals(username)) {
951
// subject = "guest";
952
// } else {
953
subject = "/users/" + username;
954 // }
955
break;
956             case 'g':
957                 usr_grp = ServicesRegistry.getInstance ()
958                         .getJahiaGroupManagerService ().
959                         lookupGroup (
960                                 aclEntry.substring (keyIndex));
961 // usr_grpName = ((JahiaGroup)usr_grp).getGroupname();
962
String JavaDoc groupname = ((JahiaGroup)usr_grp).getGroupname();
963 // if (JahiaGroupManagerService.GUEST_GROUPNAME.equals(groupname)) {
964
// subject = "nobody";
965
// } else if (JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME.equals(groupname)) {
966
// subject = "root";
967
// } else if (JahiaGroupManagerService.USERS_GROUPNAME.equals(groupname)) {
968
// subject = "user";
969
// } else {
970
subject = "+/groups/" + groupname + "/members";
971 // }
972
break;
973             default:
974                 logger.error("Unknown principal type");
975                 return false;
976             }
977             // Decode the select box value parameters
978
int vDefInherit = mRights.getVDefaultInherit();
979             String JavaDoc permissions = aclEntry.substring(
980               ManageRights.V_DEFAULT_PERMISSION, vDefInherit);
981             if (aclEntry.charAt (ManageRights.V_ADDED_ACL) == '1') {
982                 logger.debug ("Added ACL entry for user : " + subject);
983                 boolean res = dav.changePermissions (subject, permissions);
984                 if (!res) {
985                     return res;
986                 }
987             } else if (aclEntry.charAt(vDefInherit) == '%') {
988                 logger.debug ("Cut inheritance for user : " + subject);
989                 boolean res = dav.changePermissions (subject, permissions);
990                 if (!res) {
991                     return res;
992                 }
993             } else if (aclEntry.charAt (ManageRights.V_REM_ACL_ENTRY) == '1') {
994                 logger.debug ("Remove ACL for user : " + subject);
995                 boolean res = dav.revokePermissions (subject);
996                 if (!res) {
997                     return res;
998                 }
999                 continue;
1000            } else if (aclEntry.charAt (ManageRights.V_RIGHT_CHANGE) == '1') {
1001                logger.debug ("Permissions have changed to " +
1002                        permissions + " for user : " + subject);
1003                boolean res = dav.changePermissions (subject, permissions);
1004                if (!res) {
1005                    return res;
1006                }
1007            }
1008            if (aclEntry.charAt (ManageRights.V_RESET_CHILD_PERMISSION) == '1') {
1009                /** @todo Reset child permissions. */
1010            }
1011        }
1012        return true;
1013
1014    }
1015
1016
1017    private int getPermissionsAsInt(String JavaDoc subject, int c, Map JavaDoc perms) {
1018        if (perms.containsKey(subject)) {
1019            c = 1 << c;
1020            int state = ((Integer JavaDoc) perms.get(subject)).intValue();
1021            if ((state & DAVFileAccess.GRANTED) == DAVFileAccess.GRANTED)
1022                if ((state & DAVFileAccess.INHERITED) == DAVFileAccess.INHERITED)
1023                    return c + JahiaBaseACL.RIGHTS_INHERITANCE_FLAG;
1024                else
1025                    return c;
1026            else if ((state & DAVFileAccess.INHERITED) == DAVFileAccess.INHERITED)
1027                return JahiaBaseACL.RIGHTS_INHERITANCE_FLAG;
1028        }
1029        return 0;
1030    }
1031
1032    private String JavaDoc decodeStrangeBrowserEncoding(String JavaDoc name) {
1033        StringBuffer JavaDoc sb = new StringBuffer JavaDoc(name);
1034        try {
1035            RE re = new RE("&#([0-9]{1,5});");
1036            while (re.match(sb.toString())) {
1037                int v = Integer.parseInt(re.getParen(1));
1038                sb.replace(re.getParenStart(0), re.getParenEnd(0), new String JavaDoc(new byte[] { (byte)(v >>> 8), (byte)(v & 0xFF)}, "UTF-16BE"));
1039            }
1040        } catch (Exception JavaDoc e) {
1041            e.printStackTrace();
1042        }
1043        return sb.toString();
1044    }
1045
1046
1047}
1048
Popular Tags