001: /*
002: Copyright (c) 2004 eInnovation Inc. All rights reserved
003:
004: This library is free software; you can redistribute it and/or modify it under the terms
005: of the GNU Lesser General Public License as published by the Free Software Foundation;
006: either version 2.1 of the License, or (at your option) any later version.
007:
008: This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
009: without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
010: See the GNU Lesser General Public License for more details.
011: */
012:
013: /*
014: * Created on Feb 17, 2004
015: *
016: * Updated by: Todd Fisher\Christopher Burke
017: * Date: 6/27/2005
018: * Comments: updated updateProject to download and save install.xml and run ANT shell script
019: */
020: package com.openedit.modules.update;
021:
022: import java.io.File;
023: import java.io.FileOutputStream;
024: import java.io.InputStream;
025: import java.net.URL;
026: import java.util.ArrayList;
027: import java.util.Arrays;
028: import java.util.Collections;
029: import java.util.HashMap;
030: import java.util.Iterator;
031: import java.util.List;
032: import java.util.Map;
033:
034: import org.apache.commons.httpclient.HttpClient;
035: import org.apache.commons.httpclient.methods.PostMethod;
036: import org.apache.commons.httpclient.methods.multipart.FilePart;
037: import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
038: import org.apache.commons.httpclient.methods.multipart.Part;
039: import org.apache.commons.httpclient.methods.multipart.StringPart;
040: import org.apache.commons.logging.Log;
041: import org.apache.commons.logging.LogFactory;
042: import org.dom4j.DocumentHelper;
043: import org.dom4j.Element;
044: import org.springframework.beans.factory.config.BeanDefinition;
045: import org.springframework.beans.factory.support.AbstractBeanDefinition;
046:
047: import com.openedit.OpenEditException;
048: import com.openedit.OpenEditRuntimeException;
049: import com.openedit.WebPageRequest;
050: import com.openedit.WebServer;
051: import com.openedit.config.Configuration;
052: import com.openedit.modules.BaseModule;
053: import com.openedit.modules.admin.filemanager.FileUpload;
054: import com.openedit.modules.admin.filemanager.UploadRequest;
055: import com.openedit.modules.scriptrunner.ScriptModule;
056: import com.openedit.page.Page;
057: import com.openedit.page.PageSettings;
058: import com.openedit.users.User;
059: import com.openedit.util.OutputFiller;
060: import com.openedit.util.PathUtilities;
061: import com.openedit.util.XmlUtil;
062: import com.openedit.util.ZipUtil;
063:
064: /**
065: * This module allows users to update their version of OpenEdit.
066: *
067: * @author dbrown
068: */
069: public class UpdateModule extends BaseModule {
070: protected WebServer fieldWebServer;
071:
072: private static final Log log = LogFactory
073: .getLog(UpdateModule.class);
074:
075: public void updateProject(WebPageRequest inContext)
076: throws Exception {
077: checkLogin(inContext);
078: String strUrl = inContext
079: .getRequestParameter("installscripturl");
080: if (strUrl != null) {
081: //*** configure file path variable
082: String strOutputFile = "/WEB-INF/install.js";
083:
084: //*** get root path of this object
085: String root = getRoot().getAbsolutePath();
086: if (root.endsWith("/")) {
087: root = root.substring(0, root.length() - 1);
088: }
089:
090: //*** connect to configured web site
091: File out = new File(root, strOutputFile);
092: new Downloader().download(strUrl, out);
093:
094: ScriptModule module = (ScriptModule) getModule("Script");
095: Map variables = new HashMap();
096: variables.put("context", inContext);
097: List logs = new ArrayList();
098: logs.add("Downloading latest upgrade script...");
099: inContext.putPageValue("log", logs);
100: variables.put("log", logs);
101: try {
102: log.info("Upgrading " + strUrl);
103: module.execScript(variables, strOutputFile);
104: } catch (OpenEditException ex) {
105: inContext.putPageValue("exception", ex);
106: log.error(ex);
107: }
108: }
109: //Read in the output file?
110: //redirect the user to a blank page
111: }
112:
113: /**
114: *
115: * @param inContext
116: * @param inModule
117: * @throws Exception
118: */
119: public void loadUpdateModule(WebPageRequest inContext, String inBean)
120: throws Exception {
121: inContext.putPageValue("updateModule", this );
122: //inContext.putPageValue("website", getWebSite());
123: //find out the version of the module in question
124: if (inBean != null) {
125: Bean obj = createBean(inBean);
126: inContext.putPageValue("bean", obj);
127: }
128:
129: }
130:
131: /**
132: *
133: * @param inReq
134: * @throws Exception
135: */
136: public List listModules(WebPageRequest inReq) throws Exception {
137: List allModules = new ArrayList();
138: List sortedNames = new ArrayList();
139:
140: String[] names = getWebServer().getBeanFactory()
141: .getBeanDefinitionNames();
142: sortedNames = Arrays.asList(names);
143:
144: for (int i = 0; i < sortedNames.size(); i++) {
145: String name = (String) sortedNames.get(i);
146: Bean bean = createBean(name);
147: if (bean != null) {
148: allModules.add(bean);
149: }
150: }
151:
152: //Collections.sort(allModules, new BeanComparator() );
153: inReq.putPageValue("allModules", allModules);
154: return allModules;
155: }
156:
157: public List listPlugIns(WebPageRequest inReq) throws Exception {
158: List allPlugins = new ArrayList();
159: List list = getWebServer().listPlugIns();
160: XmlUtil util = new XmlUtil();
161: for (Iterator iterator = list.iterator(); iterator.hasNext();) {
162: URL link = (URL) iterator.next();
163: Element root = util.getXml(link.openStream(), "UTF-8");
164: Element bean = root.element("bean");
165: String classname = bean.attributeValue("class");
166: Class classobj = Class.forName(classname);
167: Bean plugin = new Bean();
168: Package package1 = classobj.getPackage();
169: plugin.setVersion(package1.getImplementationVersion());
170: plugin.setTitle("title "
171: + package1.getImplementationTitle());
172: plugin.setName(classname);
173: plugin.setBeanDefinition(classobj);
174: allPlugins.add(plugin);
175: }
176:
177: //Collections.sort(allModules, new BeanComparator() );
178: inReq.putPageValue("installedplugins", allPlugins);
179:
180: //Look over all the top level directories and look for settings
181: List roots = getPageManager().getChildrenPaths("/");
182: List hits = new ArrayList();
183: for (Iterator iterator = roots.iterator(); iterator.hasNext();) {
184: String path = (String) iterator.next();
185: hits.add(path);
186: }
187: inReq.putPageValue("plugins", hits);
188:
189: return allPlugins;
190: }
191:
192: protected Bean createBean(String springId) throws Exception {
193: if (getWebServer().getBeanFactory().containsBean(springId)) {
194: BeanDefinition beanDe = getWebServer().getBeanFactory()
195: .getBeanDefinition(springId);
196: if (!(beanDe instanceof AbstractBeanDefinition)) {
197: throw new OpenEditRuntimeException(
198: "Spring version not supported yet");
199:
200: }
201: AbstractBeanDefinition beanDef = (AbstractBeanDefinition) beanDe;
202: Bean bean = new Bean();
203:
204: // get name of module
205: bean.setName(springId);
206: try {
207: beanDef.resolveBeanClass(Thread.currentThread()
208: .getContextClassLoader());
209: } catch (Exception ex) {
210: log.info("Could not load: " + springId + " " + ex);
211: return null;
212: }
213: bean.setBeanDefinition(beanDef.getBeanClass());
214:
215: // get version of module
216: String version = beanDef.getBeanClass().getPackage()
217: .getImplementationVersion();
218: bean.setVersion(version);
219:
220: // get title of module
221: String title = beanDef.getBeanClass().getPackage()
222: .getImplementationTitle();
223: bean.setTitle(title);
224: return bean;
225: }
226: return null;
227: }
228:
229: /**
230: *
231: * @param inReq
232: * @throws Exception
233: */
234: public void listPageValues(WebPageRequest inReq) throws Exception {
235: List allModules = new ArrayList();
236:
237: List sortedNames = new ArrayList(inReq.getPageMap().keySet());
238: Collections.sort(sortedNames);
239:
240: for (int i = 0; i < sortedNames.size(); i++) {
241:
242: String name = (String) sortedNames.get(i);
243: Bean bean = new Bean();
244: bean.setName(name);
245: Object obj = inReq.getPageValue(name);
246:
247: if (obj instanceof String) {
248: bean.setValue((String) obj);
249: }
250:
251: bean.setBeanDefinition(obj.getClass());
252: allModules.add(bean);
253: }
254:
255: inReq.putPageValue("allPageValues", allModules);
256: }
257:
258: public WebServer getWebServer() {
259: return fieldWebServer;
260: }
261:
262: public void setWebServer(WebServer inWebServer) {
263: fieldWebServer = inWebServer;
264: }
265:
266: public List loadSiteList(WebPageRequest inReq) throws Exception {
267: Page sites = getPageManager().getPage(
268: "/openedit/update/sites.xml");
269: Element root = new XmlUtil().getXml(sites.getReader(), sites
270: .getCharacterEncoding());
271: List all = new ArrayList();
272: for (Iterator iter = root.elementIterator("site"); iter
273: .hasNext();) {
274: Element child = (Element) iter.next();
275: Site site = new Site();
276: site.setId(child.attributeValue("id"));
277: site.setText(child.attributeValue("text"));
278: site.setHref(child.attributeValue("href"));
279: all.add(site);
280: }
281:
282: List dirs = new ArrayList();
283: dirs.add("/");
284: List names = getPageManager().getChildrenNames("/");
285: for (Iterator iterator = names.iterator(); iterator.hasNext();) {
286: String path = (String) iterator.next();
287: Page dir = getPageManager().getPage(path);
288: if (dir.isFolder()) {
289: dirs.add(path);
290: }
291: }
292: inReq.putPageValue("dirs", dirs);
293:
294: inReq.putPageValue("sites", all);
295: return all;
296: }
297:
298: public Site selectSite(WebPageRequest inReq) throws Exception {
299: String id = inReq.findValue("siteid");
300: if (id == null) {
301: return null;
302: }
303: List sites = loadSiteList(inReq);
304: Site selected = null;
305: for (Iterator iter = sites.iterator(); iter.hasNext();) {
306: Site site = (Site) iter.next();
307: if (site.getId().equals(id)) {
308: selected = site;
309: }
310: }
311: //set password
312: if (selected != null) {
313: String username = inReq.getRequestParameter("username");
314: String password = inReq.getRequestParameter("password");
315: selected.setUsername(username);
316: selected.setPassword(password);
317: }
318: inReq.putPageValue("sitetopush", selected);
319: return selected;
320: }
321:
322: public void pushDirectory(WebPageRequest inReq) throws Exception {
323: Site toUpgrade = selectSite(inReq);
324: inReq.setRequestParameter("name", "pushed to "
325: + toUpgrade.getId());
326: File backup = backUpDirectory(inReq);
327:
328: String url = toUpgrade.getHref();
329: if (!url.startsWith("http://")) {
330: url = "http://" + url;
331: }
332:
333: if (!url.endsWith("/")) {
334: url += "/";
335: }
336: url += "openedit/update/receivepush.html";
337: log.info("posting here:" + url);
338:
339: PostMethod postMethod = new PostMethod(url);
340:
341: Part[] parts = {
342: new StringPart("username", toUpgrade.getUsername()),
343: new StringPart("password", toUpgrade.getPassword()),
344: new StringPart("savedas", backup.getName()),
345: new FilePart("file", backup) };
346:
347: postMethod.setRequestEntity(new MultipartRequestEntity(parts,
348: postMethod.getParams()));
349:
350: HttpClient client = new HttpClient();
351: //client.getHttpConnectionManager().getParams().setConnectionTimeout(0);
352: int statusCode1 = client.executeMethod(postMethod);
353: postMethod.releaseConnection();
354: if (statusCode1 == 200) {
355: inReq.putPageValue("message", "Push is completed.");
356: } else {
357: inReq.putPageValue("message", "Status code: <b>"
358: + statusCode1 + "</b><br>"
359: + postMethod.getResponseBodyAsString());
360: }
361: }
362:
363: public File backUpDirectory(WebPageRequest inReq) throws Exception {
364: Backup backup = new Backup();
365: for (Iterator iter = inReq.getCurrentAction().getConfig()
366: .getChildIterator("exclude"); iter.hasNext();) {
367: Configuration exclude = (Configuration) iter.next();
368: backup.addExclude(exclude.getValue());
369: }
370: backup.setRoot(getRoot());
371: String subdir = inReq.getRequiredParameter("directory");
372: backup.setIncludePath(subdir);
373: backup.setPageManager(getPageManager());
374:
375: //String backupName = inReq.getRequiredParameter("name");
376: String backupName = inReq.getUserName() + subdir;
377: File results = backup.backupCurrentSite(backupName);
378: inReq.putPageValue("result", results);
379: return results;
380: }
381:
382: public List listVersions(WebPageRequest inReq) throws Exception {
383: Backup backup = new Backup();
384: backup.setRoot(getRoot());
385: backup.setPageManager(getPageManager());
386: List versions = backup.listSiteVersions();
387: inReq.putPageValue("versionlist", versions);
388: return versions;
389: }
390:
391: public void restoreVersion(WebPageRequest inReq) throws Exception {
392: String name = inReq.getRequestParameter("versionid");
393: if (name != null) {
394: //check that we are logged in
395: Backup backup = new Backup();
396: backup.setRoot(getRoot());
397: backup.setPageManager(getPageManager());
398: File version = backup.loadVersion(name);
399: if (version == null) {
400: log.error("No such backup found " + name);
401: inReq.putPageValue("error", "No such file");
402: } else {
403: backup.restoreBackup(version);
404: }
405: } else {
406: log.error("No versionid parameter");
407: }
408:
409: }
410:
411: public void receivePush(WebPageRequest inReq) throws Exception {
412: //this is an upload then a restore
413: FileUpload command = new FileUpload();
414: command.setPageManager(getPageManager());
415: UploadRequest properties = command.parseArguments(inReq);
416: if (properties == null) {
417: log.error("Nothing posted");
418: return;
419: }
420: String username = (String) properties.get("username");
421: String password = (String) properties.get("password");
422:
423: User admin = getUserManager().getUser(username);
424: if (!getUserManager().authenticate(admin, password)) {
425: throw new OpenEditException("Did not authenticate: "
426: + username);
427: } else {
428: inReq.setUser(admin);
429: }
430: String id = (String) properties.get("savedas");
431: if (id != null && id.length() > 0) {
432: String path = "/WEB-INF/versions/" + id;
433: Page page = properties.saveFirstFileAs(path, inReq
434: .getUser());
435: if (page.exists()
436: && page.getContentItem().getLength() > 5000) {
437: //TODO: Make sure we can unzip it
438: //backup
439: //backUpDirectory(inReq); //Restore now keeps old copies in the WEB-INF/trash directory
440: inReq.setRequestParameter("versionid", id);
441: restoreVersion(inReq);
442: } else {
443: log.error("Page did not save " + path);
444: }
445: } else {
446: log.error("No ID found");
447: }
448: }
449:
450: public void changeLayout(WebPageRequest inReq) throws Exception {
451: checkLogin(inReq);
452: String zip = inReq.getRequestParameter("ziplocation");
453: if (zip == null) {
454: return;
455: }
456: URL url = new URL(zip);
457: InputStream input = url.openStream();
458:
459: //save to the tmp directory?
460: String name = PathUtilities.extractPageName(zip);
461: File tmp = File.createTempFile("layoutzip", name);
462:
463: OutputFiller filler = new OutputFiller();
464: FileOutputStream out = new FileOutputStream(tmp);
465: filler.fill(input, out);
466: out.close();
467: input.close();
468:
469: //UNZIP
470: ZipUtil ziputil = new ZipUtil();
471: File destination = new File(getRoot(), "/WEB-INF/base/layouts/");
472: destination.mkdirs();
473: ziputil.unzip(tmp, destination);
474:
475: //CHECK THE BASE
476: // PageSettings settings = getPageManager().getPageSettingsManager().getPageSettings("/layouts/_site.xconf");
477: // PageProperty fall = settings.getFieldProperty("fallbackdirectory");
478: // if( fall == null)
479: // {
480: // fall = new PageProperty("fallbackdirectory");
481: // fall.setValue("/WEB-INF/base/layouts");
482: // settings.putProperty(fall);
483: // getPageManager().getPageSettingsManager().saveSetting(settings);
484: // }
485: //CHANGE LAYOUT
486: PageSettings topsettings = getPageManager()
487: .getPageSettingsManager().getPageSettings(
488: "/_site.xconf");
489:
490: topsettings.setInnerLayout("/layouts/" + name + "/layout.html");
491: getPageManager().getPageSettingsManager().saveSetting(
492: topsettings);
493: inReq.putPageValue("layoutname", name);
494:
495: //TODO: Create the directory structure for them to change stuff
496: }
497:
498: public void listFilesInDirectory(WebPageRequest inReq)
499: throws Exception {
500: checkLogin(inReq);
501: SyncToServer server = new SyncToServer();
502: server.setRoot(getRoot());
503: String path = inReq.getRequestParameter("syncpath");
504: if (path == null) {
505: throw new OpenEditException("syncpath is required");
506: }
507: List files = server.listLocalFiles(path);
508: Element root = DocumentHelper.createElement("files");
509: for (Iterator iterator = files.iterator(); iterator.hasNext();) {
510: Element e = (Element) iterator.next();
511: root.add(e);
512: }
513: inReq.putPageValue("files", root.asXML());
514: }
515:
516: public void downloadFiles(WebPageRequest inReq) throws Exception {
517: checkLogin(inReq);
518: //User passes a list of files to download and we make a zip file
519: SyncToServer server = new SyncToServer();
520: server.setRoot(getRoot());
521:
522: //Make list of files
523: String[] paths = inReq.getRequestParameters("file");
524: if (paths == null) {
525: throw new OpenEditException("No files specified");
526: }
527: List files = Arrays.asList(paths);
528:
529: server.sendFiles(files, inReq.getOutputStream());
530: }
531:
532: public void syncToServer(WebPageRequest inReq) throws Exception {
533: //get list for one directory at a time
534: //process list recursively
535: SyncToServer server = new SyncToServer();
536: server.setRoot(getRoot());
537: String user = inReq.findValue("accountname");
538: if (user == null) {
539: user = inReq.getRequestParameter("username"); //legacy
540: }
541: server.setUsername(user);
542: server.setPassword(inReq.findValue("password"));
543: Site toUpgrade = selectSite(inReq);
544: server.setServerUrl(toUpgrade.getHref());
545: String path = inReq.findValue("directory");
546: server.syncFromServer(path);
547:
548: }
549:
550: protected void checkLogin(WebPageRequest inReq) throws Exception {
551: if (inReq.getUser() == null) {
552: String username = inReq.getRequestParameter("accountname");
553: String password = inReq.getRequestParameter("password");
554:
555: User admin = getUserManager().getUser(username);
556: if (!getUserManager().authenticate(admin, password)) {
557: throw new OpenEditException("Did not authenticate: "
558: + username);
559: } else {
560: inReq.setUser(admin);
561: }
562: }
563: }
564:
565: }
|