KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > template > Template_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
// Template_Engine
15
// NK 27.01.2002
16
//
17

18 package org.jahia.engines.template;
19
20 import java.io.File JavaDoc;
21 import java.util.HashMap JavaDoc;
22
23 import javax.servlet.http.HttpSession JavaDoc;
24
25 import org.jahia.data.JahiaData;
26 import org.jahia.data.events.JahiaEvent;
27 import org.jahia.engines.EngineToolBox;
28 import org.jahia.engines.JahiaEngine;
29 import org.jahia.engines.audit.ManageLogs_Engine;
30 import org.jahia.engines.rights.ManageRights;
31 import org.jahia.exceptions.JahiaException;
32 import org.jahia.exceptions.JahiaForbiddenAccessException;
33 import org.jahia.exceptions.JahiaSessionExpirationException;
34 import org.jahia.params.ParamBean;
35 import org.jahia.registries.ServicesRegistry;
36 import org.jahia.services.acl.ACLResource;
37 import org.jahia.services.pages.JahiaPageDefinition;
38 import org.jahia.services.pages.JahiaPageDefinitionTemp;
39 import org.jahia.services.usermanager.JahiaUser;
40 import org.jahia.utils.JahiaObjectTool;
41 import org.jahia.utils.JahiaTools;
42
43 /**
44  * Engine for editing and setting rights on template
45  *
46  * @author Khue Nguyen
47  */

48 public class Template_Engine implements JahiaEngine {
49
50     private static final String JavaDoc TEMPLATE_JSP = "manage_template";
51     public static final String JavaDoc TEMPLATE_SESSION_NAME = "theTemplate";
52
53     // the temporary template to hold change until they have to be saved.
54
private static final String JavaDoc TEMPORARY_TEMPLATE_SESSION_NAME = "theTemporaryTemplate";
55
56     private static Template_Engine instance;
57     public static final String JavaDoc ENGINE_NAME = "template";
58     private EngineToolBox toolBox;
59
60     private static final org.apache.log4j.Logger logger =
61             org.apache.log4j.Logger.getLogger (Template_Engine.class);
62
63     private final String JavaDoc WRITE_ACCESS_STR = "writeAccess";
64     private final String JavaDoc ADMIN_ACCESS_STR = "adminAccess";
65
66     private final String JavaDoc SCREEN_STR = "screen";
67
68     private final String JavaDoc EDIT_STR = "edit";
69     private final String JavaDoc SAVE_STR = "save";
70     private final String JavaDoc CANCEL_STR = "cancel";
71     private final String JavaDoc LOGS_STR = "logs";
72     private final String JavaDoc APPLY_STR = "apply";
73     private final String JavaDoc CLOSE_STR = "close";
74     private final String JavaDoc LASTSCREEN_STR = "lastscreen";
75     private final String JavaDoc JSPSOURCE_STR = "jspSource";
76
77
78     /**
79      * constructor
80      */

81     private Template_Engine () {
82         logger.debug ("***** Starting " + Template_Engine.class.getName () + " engine *****");
83         toolBox = EngineToolBox.getInstance ();
84     }
85
86     /**
87      * getInstance
88      */

89     public static synchronized Template_Engine getInstance () {
90         if (instance == null) {
91             instance = new Template_Engine ();
92         }
93         return instance;
94     }
95
96     /**
97      * authoriseRender
98      */

99     public boolean authoriseRender (ParamBean jParams) {
100         return true; // we do not check if we are in Edit mode
101
}
102
103     /**
104      * renderLink
105      */

106     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
107             throws JahiaException {
108         JahiaPageDefinition theTemplate = (JahiaPageDefinition) theObj;
109         String JavaDoc params = "?mode=display&templateid=" + theTemplate.getID ();
110
111         return jParams.composeEngineUrl (ENGINE_NAME, params);
112     }
113
114     /**
115      * needsJahiaData
116      */

117     public boolean needsJahiaData (ParamBean jParams) {
118         return false;
119     }
120
121     /**
122      * handles the engine actions
123      *
124      * @param jParams a ParamBean object
125      * @param jData a JahiaData object (not mandatory)
126      */

127     public void handleActions (ParamBean jParams, JahiaData jData)
128             throws JahiaException,
129             JahiaSessionExpirationException,
130             JahiaForbiddenAccessException {
131         // initalizes the hashmap
132
HashMap JavaDoc engineMap = initEngineMap (jData);
133
134         // checks if the user has the right to display the engine
135
JahiaPageDefinition theTemplate =
136                 (JahiaPageDefinition) engineMap.get (TEMPLATE_SESSION_NAME);
137         JahiaUser theUser = jParams.getUser ();
138
139         if (ACLResource.checkAdminAccess (theTemplate, theUser)) {
140             engineMap.put (ADMIN_ACCESS_STR, Boolean.TRUE);
141             engineMap.put ("enableRightView", Boolean.TRUE);
142             engineMap.put (WRITE_ACCESS_STR, Boolean.TRUE);
143
144         } else if (ACLResource.checkWriteAccess (theTemplate, theUser)) {
145             engineMap.put (WRITE_ACCESS_STR, Boolean.TRUE);
146         }
147
148         if (engineMap.get (WRITE_ACCESS_STR) != null) {
149             processLastScreen (jParams, engineMap);
150             processCurrentScreen (jParams, engineMap);
151         } else {
152             throw new JahiaForbiddenAccessException ();
153         }
154
155         // displays the screen
156
toolBox.displayScreen (jParams, engineMap);
157     }
158
159     /**
160      * Retrieve the engine name.
161      *
162      * @return the engine name.
163      */

164     public final String JavaDoc getName () {
165         return ENGINE_NAME;
166     }
167
168
169     /**
170      * processes the last screen sent by the user
171      *
172      * @param jParams a ParamBean object
173      * @param engineMap the engine map
174      */

175     public void processLastScreen (ParamBean jParams, HashMap JavaDoc engineMap)
176             throws JahiaException,
177             JahiaForbiddenAccessException {
178         JahiaPageDefinition theTemplate =
179                 (JahiaPageDefinition) engineMap.get (TEMPLATE_SESSION_NAME);
180
181         // gets the last screen
182
// lastscreen = edit, rights, logs
183
String JavaDoc lastScreen = jParams.getRequest ().getParameter (LASTSCREEN_STR);
184         if (lastScreen == null) {
185             lastScreen = EDIT_STR;
186         }
187
188         int mode = JahiaEngine.UPDATE_MODE;
189
190         if (lastScreen.equals (EDIT_STR)) {
191             if (!processTemplateEdit (jParams, mode, engineMap)) {
192                 // if there was an error, come back to last screen
193
engineMap.put (SCREEN_STR, lastScreen);
194                 engineMap.put (JSPSOURCE_STR, TEMPLATE_JSP);
195             }
196         } else if (lastScreen.equals ("rightsMgmt")) {
197             if (engineMap.get (ADMIN_ACCESS_STR) != null) {
198                 ManageRights.getInstance ()
199                         .handleActions (jParams, mode, engineMap, theTemplate.getAclID ());
200             } else {
201                 throw new JahiaForbiddenAccessException ();
202             }
203         } else if (lastScreen.equals (LOGS_STR)) {
204             if (engineMap.get (ADMIN_ACCESS_STR) != null) {
205                 ManageLogs_Engine.getInstance ().handleActions (jParams, mode, engineMap, null);
206             } else {
207                 throw new JahiaForbiddenAccessException ();
208             }
209         }
210     }
211
212
213     /**
214      * prepares the screen requested by the user
215      *
216      * @param jParams a ParamBean object
217      */

218     public void processCurrentScreen (ParamBean jParams, HashMap JavaDoc engineMap)
219             throws JahiaException,
220             JahiaForbiddenAccessException {
221         // gets the current screen
222
// screen = edit, rights, logs
223
String JavaDoc theScreen = (String JavaDoc) engineMap.get (SCREEN_STR);
224         JahiaPageDefinition theTemplate =
225                 (JahiaPageDefinition) engineMap.get (TEMPLATE_SESSION_NAME);
226
227         // indicates to sub engines that we are processing last screen
228
int mode = JahiaEngine.LOAD_MODE;
229
230         // dispatches to the appropriate sub engine
231
if (theScreen.equals (EDIT_STR)) {
232             processTemplateEdit (jParams, mode, engineMap);
233         } else if (theScreen.equals (LOGS_STR)) {
234             toolBox.loadLogData (jParams, JahiaObjectTool.TEMPLATE_TYPE, engineMap);
235         } else if (theScreen.equals ("rightsMgmt")) {
236             if (engineMap.get (ADMIN_ACCESS_STR) != null) {
237                 ManageRights.getInstance ()
238                         .handleActions (jParams, mode, engineMap, theTemplate.getAclID ());
239             } else {
240                 throw new JahiaForbiddenAccessException ();
241             }
242         } else if (theScreen.equals (SAVE_STR) || theScreen.equals (APPLY_STR)) {
243             mode = JahiaEngine.SAVE_MODE;
244             if (processTemplateSave (jParams, engineMap)) {
245                 if (engineMap.get (ADMIN_ACCESS_STR) != null) {
246                     engineMap.put ("logObjectType",
247                             Integer.toString (JahiaObjectTool.TEMPLATE_TYPE));
248                     engineMap.put ("logObject", theTemplate);
249                     ManageRights.getInstance ()
250                             .handleActions (jParams, mode, engineMap, theTemplate.getAclID ());
251                 }
252
253                 JahiaEvent theEvent = new JahiaEvent (this, jParams, theTemplate);
254                 ServicesRegistry.getInstance ().getJahiaEventService ().fireUpdateTemplate (
255                         theEvent);
256             } else {
257                 // if there was an error, come back to last screen
258
engineMap.put (SCREEN_STR, EDIT_STR);
259                 engineMap.put (JSPSOURCE_STR, TEMPLATE_JSP);
260             }
261             if (theScreen.equals (APPLY_STR)) {
262
263                 JahiaPageDefinitionTemp theTemporaryTemplate = (JahiaPageDefinitionTemp)
264                         engineMap.get (TEMPORARY_TEMPLATE_SESSION_NAME);
265
266                 // remove template context and the sitekey from the source path
267
String JavaDoc templateContext = jParams.settings ().getTemplatesContext () +
268                         jParams.getSite ().getSiteKey () +
269                         "/";
270                 if ((templateContext != null)
271                         &&
272                         (theTemporaryTemplate.getSourcePath ().indexOf (templateContext) != -1)) {
273                     theTemporaryTemplate.setSourcePath (
274                             theTemporaryTemplate.getSourcePath ().substring (
275                                     templateContext.length (),
276                                     theTemporaryTemplate.getSourcePath ().length ()));
277                 }
278
279                 engineMap.put (SCREEN_STR, jParams.getRequest ().getParameter (LASTSCREEN_STR));
280             }
281             logger.debug ("Saving !!");
282         } else if (theScreen.equals (CANCEL_STR)) {
283             engineMap.put (ENGINE_OUTPUT_FILE_PARAM, JahiaEngine.CANCEL_JSP);
284         }
285     }
286
287
288     /**
289      * inits the engine map
290      *
291      * @param jData the jahia data bean
292      *
293      * @return HashMap, a HashMap object containing all the basic values needed by an engine
294      */

295     private HashMap JavaDoc initEngineMap (JahiaData jData)
296             throws JahiaException,
297             JahiaSessionExpirationException {
298         ParamBean jParams = jData.params ();
299
300         HashMap JavaDoc engineMap = new HashMap JavaDoc ();
301         JahiaPageDefinition theTemplate;
302
303         // gets session values
304
HttpSession JavaDoc theSession = jParams.getSession ();
305
306         // tries to find if this is the first screen generated by the engine
307
String JavaDoc theScreen = jParams.getRequest ().getParameter (SCREEN_STR);
308         if (theScreen != null) {
309             // if no, load the engine map value from the session
310
engineMap = (HashMap JavaDoc) theSession.getAttribute (ParamBean.SESSION_JAHIA_ENGINEMAP);
311             if (engineMap == null) {
312                 throw new JahiaSessionExpirationException ();
313             }
314             theTemplate = (JahiaPageDefinition) engineMap.get (TEMPLATE_SESSION_NAME);
315         } else {
316             // first screen generated by engine -> init sessions
317
int templateID = -1;
318             String JavaDoc value = jParams.getRequest ().getParameter ("templateid");
319             if (value != null)
320                 templateID = Integer.parseInt (value);
321
322             theTemplate = ServicesRegistry.getInstance ()
323                     .getJahiaPageTemplateService ()
324                     .lookupPageTemplate (templateID);
325
326             theScreen = EDIT_STR;
327
328             // init the temporary template bean
329
JahiaPageDefinitionTemp theTemporaryTemplate =
330                     new JahiaPageDefinitionTemp (theTemplate,
331                             (jParams.getSite ().getDefaultTemplateID () ==
332                     theTemplate.getID ()));
333
334             // remove template context and the sitekey from the source path
335
String JavaDoc templateContext = jParams.settings ().getTemplatesContext () +
336                     jParams.getSite ().getSiteKey () +
337                     "/";
338             if ((templateContext != null)
339                     &&
340                     (theTemporaryTemplate.getSourcePath ().indexOf (templateContext) != -1)) {
341                 theTemporaryTemplate.setSourcePath (
342                         theTemporaryTemplate.getSourcePath ().substring (
343                                 templateContext.length (),
344                                 theTemporaryTemplate.getSourcePath ().length ()));
345             }
346
347             // init session
348
engineMap.put (TEMPLATE_SESSION_NAME, theTemplate);
349             engineMap.put (TEMPORARY_TEMPLATE_SESSION_NAME, theTemporaryTemplate);
350         }
351
352         engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
353         engineMap.put (ENGINE_NAME_PARAM, ENGINE_NAME);
354         engineMap.put (ENGINE_URL_PARAM,
355                 jParams.composeEngineUrl (ENGINE_NAME, "?templateid=" + theTemplate.getID ()));
356
357         theSession.setAttribute (ParamBean.SESSION_JAHIA_ENGINEMAP, engineMap);
358
359         // sets screen
360
engineMap.put (SCREEN_STR, theScreen);
361         if (theScreen.equals (SAVE_STR)) {
362             engineMap.put (JSPSOURCE_STR, CLOSE_STR);
363         } else if (theScreen.equals (APPLY_STR)) {
364             engineMap.put (JSPSOURCE_STR, APPLY_STR);
365         } else if (theScreen.equals (CANCEL_STR)) {
366             engineMap.put (JSPSOURCE_STR, CLOSE_STR);
367         } else {
368             engineMap.put (JSPSOURCE_STR, TEMPLATE_JSP);
369         }
370
371         // sets engineMap for JSPs
372
jParams.getRequest ().setAttribute (ENGINE_NAME_PARAM, "Manage Templates");
373         jParams.getRequest ().setAttribute ("org.jahia.engines.EngineHashMap", engineMap);
374         jParams.getRequest ().setAttribute ("Template_Engine.warningMsg", EMPTY_STRING);
375         return engineMap;
376     }
377
378
379     /**
380      * Prepare data to display or retrieves submitted values and store them in session
381      */

382     private boolean processTemplateEdit (ParamBean jParams, int mode, HashMap JavaDoc engineMap) {
383
384         if (mode == JahiaEngine.LOAD_MODE) {
385             // everything is in the session , so do nothing
386
return true;
387         } else if (mode == JahiaEngine.UPDATE_MODE) {
388             // check the last screen
389
String JavaDoc lastScreen = jParams.getRequest ().getParameter (LASTSCREEN_STR);
390             if (lastScreen == null)
391                 lastScreen = EMPTY_STRING;
392
393             if (lastScreen.equals (EDIT_STR)) {
394                 // retrieve submitted data
395
JahiaPageDefinitionTemp theTemporaryTemplate = (JahiaPageDefinitionTemp)
396                         engineMap.get (TEMPORARY_TEMPLATE_SESSION_NAME);
397                 if (theTemporaryTemplate == null)
398                     return false; // should not
399

400                 // get the name
401
String JavaDoc value = jParams.getRequest ().getParameter ("templateName");
402                 if (value != null)
403                     theTemporaryTemplate.setName (value);
404
405                 // get the source path
406
value = jParams.getRequest ().getParameter ("sourcePath");
407                 if (value != null)
408                     theTemporaryTemplate.setSourcePath (value);
409
410                 // get the available option
411
value = jParams.getRequest ().getParameter ("templateAvailable");
412                 theTemporaryTemplate.setAvailable (value != null);
413
414                 // get the default option
415
value = jParams.getRequest ().getParameter ("templateDefault");
416                 theTemporaryTemplate.setDefault (value != null);
417             }
418             return true;
419         }
420         return false;
421     }
422
423
424     /**
425      * Save data
426      */

427     private boolean processTemplateSave (ParamBean jParams, HashMap JavaDoc engineMap)
428             throws JahiaException {
429
430         StringBuffer JavaDoc warningMsg = new StringBuffer JavaDoc (EMPTY_STRING);
431
432         JahiaPageDefinitionTemp theTemporaryTemplate = (JahiaPageDefinitionTemp)
433                 engineMap.get (TEMPORARY_TEMPLATE_SESSION_NAME);
434
435         JahiaPageDefinition theTemplate = (JahiaPageDefinition)
436                 engineMap.get (TEMPLATE_SESSION_NAME);
437
438         // check data integrity
439
if (theTemporaryTemplate.getName () == null
440                 || theTemporaryTemplate.getName ().trim ().equals (EMPTY_STRING))
441             warningMsg.append ("<lu><li>The name is required.<br>");
442
443         // check sourcepath
444
warningMsg.append (checkSourcePath (warningMsg.toString (), jParams,
445                 theTemporaryTemplate));
446
447         if (!warningMsg.toString ().equals (EMPTY_STRING)) {
448             warningMsg.append ("</lu>");
449             jParams.getRequest ().setAttribute ("Template_Engine.warningMsg",
450                     warningMsg.toString ());
451             return false;
452         }
453
454         // If everything is ok save new values
455
theTemplate.setName (theTemporaryTemplate.getName ());
456         theTemplate.setSourcePath (theTemporaryTemplate.getSourcePath ());
457         logger.debug ("Source path :" + theTemporaryTemplate.getSourcePath ());
458         theTemplate.setAvailable (theTemporaryTemplate.isAvailable ());
459         theTemplate.commitChanges ();
460
461         // save site's default template if needed
462
boolean doUpdateSite = true;
463         if ((jParams.getSite ().getDefaultTemplateID () == theTemplate.getID ())
464                 && !theTemporaryTemplate.isDefault ()) {
465             jParams.getSite ().setDefaultTemplateID (-1);
466         } else if (theTemporaryTemplate.isDefault ()) {
467             jParams.getSite ().setDefaultTemplateID (theTemplate.getID ());
468         } else {
469             doUpdateSite = false;
470         }
471
472         if (doUpdateSite)
473             ServicesRegistry.getInstance ()
474                     .getJahiaSitesService ().updateSite (jParams.getSite ());
475
476         return true;
477
478     }
479
480     /**
481      * Returns a warning msg in case of not valid source path
482      */

483     private String JavaDoc checkSourcePath (String JavaDoc warningMsg, ParamBean jParams,
484                                     JahiaPageDefinitionTemp tempoPageDef) {
485
486         if (tempoPageDef.getSourcePath () == null
487                 || tempoPageDef.getSourcePath ().trim ().equals (EMPTY_STRING)) {
488             return "<li>The source path is required.<br>";
489         }
490
491         // replace all "\" by "/"
492
String JavaDoc sourcePath = JahiaTools.replacePattern (tempoPageDef.getSourcePath (), "\\",
493                 "/");
494
495         while (sourcePath.startsWith ("/") || sourcePath.startsWith (".")) {
496             sourcePath = sourcePath.substring (1, sourcePath.length ());
497         }
498         sourcePath = JahiaTools.replacePattern (sourcePath, "..", EMPTY_STRING);
499         sourcePath = JahiaTools.replacePattern (sourcePath, "./", "/");
500         sourcePath = JahiaTools.replacePattern (sourcePath, "/.", "/");
501         sourcePath = JahiaTools.replacePattern (sourcePath, "//", "/");
502
503
504
505         // check if the file exists
506
String JavaDoc path = jParams.settings ().getJahiaTemplatesDiskPath ();
507         path = JahiaTools.replacePattern (path, "\\", "/");
508         if (!path.endsWith ("/"))
509             path += "/";
510         File JavaDoc f = new File JavaDoc (
511                 path + jParams.getSite ().getSiteKey () + File.separator + sourcePath);
512         logger.debug (" Template Path = " + f.getAbsolutePath ());
513
514         if (!f.isFile ())
515             return "<li>The source file does not exist.<br>";
516
517         if (!f.canRead ())
518             return "<li>No access allowed to the source file.<br>";
519
520         // if everything is ok , save :
521
if (warningMsg.equals (EMPTY_STRING)) {
522             String JavaDoc templateContext = jParams.settings ().getTemplatesContext ()
523                     + jParams.getSite ().getSiteKey () + "/";
524             tempoPageDef.setSourcePath (templateContext + sourcePath);
525         }
526         return EMPTY_STRING;
527     }
528
529 }
530
Popular Tags