001/*
002 * File   : $Source$
003 * Date   : $Date$
004 * Version: $Revision$
005 *
006 * This library is part of OpenCms -
007 * the Open Source Content Management System
008 *
009 * Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com)
010 *
011 * This library is free software; you can redistribute it and/or
012 * modify it under the terms of the GNU Lesser General Public
013 * License as published by the Free Software Foundation; either
014 * version 2.1 of the License, or (at your option) any later version.
015 *
016 * This library is distributed in the hope that it will be useful,
017 * but WITHOUT ANY WARRANTY; without even the implied warranty of
018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
019 * Lesser General Public License for more details.
020 *
021 * For further information about Alkacon Software, please see the
022 * company website: http://www.alkacon.com
023 *
024 * For further information about OpenCms, please see the
025 * project website: http://www.opencms.org
026 *
027 * You should have received a copy of the GNU Lesser General Public
028 * License along with this library; if not, write to the Free Software
029 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
030 */
031
032package org.opencms.workplace.tools.sites;
033
034import org.opencms.ade.configuration.CmsADEManager;
035import org.opencms.configuration.CmsSitesConfiguration;
036import org.opencms.file.CmsFile;
037import org.opencms.file.CmsObject;
038import org.opencms.file.CmsProperty;
039import org.opencms.file.CmsPropertyDefinition;
040import org.opencms.file.CmsResource;
041import org.opencms.file.CmsResourceFilter;
042import org.opencms.file.CmsVfsResourceNotFoundException;
043import org.opencms.file.types.CmsResourceTypeFolder;
044import org.opencms.file.types.CmsResourceTypeFolderSubSitemap;
045import org.opencms.file.types.CmsResourceTypeJsp;
046import org.opencms.file.types.I_CmsResourceType;
047import org.opencms.i18n.CmsEncoder;
048import org.opencms.jsp.CmsJspActionElement;
049import org.opencms.loader.CmsLoaderException;
050import org.opencms.main.CmsException;
051import org.opencms.main.CmsIllegalArgumentException;
052import org.opencms.main.CmsLog;
053import org.opencms.main.OpenCms;
054import org.opencms.module.CmsModule;
055import org.opencms.site.CmsSite;
056import org.opencms.util.CmsStringUtil;
057import org.opencms.widgets.CmsCheckboxWidget;
058import org.opencms.widgets.CmsComboWidget;
059import org.opencms.widgets.CmsDisplayWidget;
060import org.opencms.widgets.CmsInputWidget;
061import org.opencms.widgets.CmsSelectWidget;
062import org.opencms.widgets.CmsSelectWidgetOption;
063import org.opencms.widgets.CmsVfsFileWidget;
064import org.opencms.workplace.CmsDialog;
065import org.opencms.workplace.CmsWidgetDialog;
066import org.opencms.workplace.CmsWidgetDialogParameter;
067import org.opencms.workplace.CmsWorkplaceSettings;
068import org.opencms.xml.content.CmsXmlContent;
069import org.opencms.xml.content.CmsXmlContentFactory;
070import org.opencms.xml.types.I_CmsXmlContentValue;
071
072import java.util.ArrayList;
073import java.util.Collections;
074import java.util.HashMap;
075import java.util.List;
076import java.util.Locale;
077import java.util.Map;
078
079import javax.servlet.http.HttpServletRequest;
080import javax.servlet.http.HttpServletResponse;
081import javax.servlet.jsp.PageContext;
082
083import org.apache.commons.logging.Log;
084
085/**
086 * Dialog for showing the sites details.<p>
087 *
088 * @since 9.0.0
089 */
090@Deprecated
091public class CmsSiteDetailDialog extends CmsWidgetDialog {
092
093    /** The module name constant. */
094    public static final String MODULE_NAME = "org.opencms.workplace.tools.sites";
095
096    /** Defines which pages are valid for this dialog. */
097    public static final String[] PAGES = {"page1"};
098
099    /** Module parameter constant for the create OU default flag. */
100    public static final String PARAM_CREATE_OU = "createou";
101
102    /** Module parameter constant for the web server script. */
103    public static final String PARAM_OU_DESCRIPTION = "oudescription";
104
105    /** The dialog action for editing a site. */
106    protected static final String DIALOG_EDIT = "edit";
107
108    /** Constant. */
109    private static final String BLANK_HTML = "blank.html";
110
111    /** Dialog new action parameter value. */
112    private static final String DIALOG_NEW = "new";
113
114    /** The logger for this class. */
115    private static Log LOG = CmsLog.getLog(CmsSiteDetailDialog.class.getName());
116
117    /** Constant. */
118    private static final String MODEL_PAGE = "ModelPage";
119
120    /** Constant. */
121    private static final String MODEL_PAGE_PAGE = "ModelPage/Page";
122
123    /** Constant. */
124    private static final String NEW = ".templates/";
125
126    /** Signals whether to create an OU or not. */
127    private boolean m_createou;
128
129    /** The OU description text. */
130    private String m_ouDescription;
131
132    /** The edit action to perform. */
133    private String m_paramEditaction;
134
135    /** The sites parameter. */
136    private String m_paramSites;
137
138    /** The dialog object. */
139    private CmsSiteBean m_site;
140
141    /** The name of the sites root folder. */
142    private String m_sitename;
143
144    /** The template property. */
145    private String m_template;
146
147    /**
148     * Public constructor with JSP action element.<p>
149     *
150     * @param jsp an initialized JSP action element
151     */
152    public CmsSiteDetailDialog(CmsJspActionElement jsp) {
153
154        super(jsp);
155    }
156
157    /**
158     * Public constructor with JSP variables.<p>
159     *
160     * @param context the JSP page context
161     * @param req the JSP request
162     * @param res the JSP response
163     */
164    public CmsSiteDetailDialog(PageContext context, HttpServletRequest req, HttpServletResponse res) {
165
166        this(new CmsJspActionElement(context, req, res));
167    }
168
169    /**
170     * @see org.opencms.workplace.CmsWidgetDialog#actionCommit()
171     */
172    @Override
173    public void actionCommit() {
174
175        try {
176
177            // validate the dialog form
178            validateDialog();
179
180            // create a root site clone of the current CMS object.
181            CmsObject cms = OpenCms.initCmsObject(getCms());
182            cms.getRequestContext().setSiteRoot("");
183
184            // create the site root path
185            String siteRoot = "/sites".concat(m_sitename);
186            m_site.setSiteRoot(siteRoot);
187
188            CmsResource siteRootResource = null;
189            String sitePath = null;
190            // check if the site root already exists
191            try {
192                // take the existing site and do not perform any OU related actions
193                siteRootResource = cms.readResource(siteRoot);
194                sitePath = cms.getSitePath(siteRootResource);
195            } catch (CmsVfsResourceNotFoundException e) {
196                // not create a new site folder and the according OU if option is checked checked
197                I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(
198                    CmsResourceTypeFolderSubSitemap.TYPE_SUBSITEMAP);
199                siteRootResource = cms.createResource(siteRoot, type);
200                sitePath = cms.getSitePath(siteRootResource);
201            }
202
203            // add template  property
204            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getTemplate())) {
205                CmsProperty prop = new CmsProperty(
206                    CmsPropertyDefinition.PROPERTY_TEMPLATE,
207                    getTemplate(),
208                    getTemplate());
209                cms.writePropertyObject(siteRoot, prop);
210            }
211
212            // create OU
213            if (m_createou) {
214                OpenCms.getOrgUnitManager().createOrganizationalUnit(
215                    cms,
216                    "/" + siteRootResource.getName(),
217                    m_ouDescription.replace("%(site)", m_site.getTitle() + " [" + m_site.getSiteRoot() + "]"),
218                    0,
219                    siteRootResource.getRootPath());
220            }
221
222            // create sitemap configuration
223            String contentFolder = CmsStringUtil.joinPaths(sitePath, CmsADEManager.CONTENT_FOLDER_NAME + "/");
224            String sitemapConfig = CmsStringUtil.joinPaths(contentFolder, CmsADEManager.CONFIG_FILE_NAME);
225            if (!cms.existsResource(sitemapConfig)) {
226                CmsResource config = createSitemapContentFolder(cms, siteRootResource);
227                if (config != null) {
228                    try {
229                        CmsResource newFolder = cms.createResource(
230                            contentFolder + NEW,
231                            OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.RESOURCE_TYPE_NAME));
232                        I_CmsResourceType containerType = OpenCms.getResourceManager().getResourceType(
233                            org.opencms.file.types.CmsResourceTypeXmlContainerPage.RESOURCE_TYPE_NAME);
234                        CmsResource modelPage = cms.createResource(newFolder.getRootPath() + BLANK_HTML, containerType);
235                        String defTitle = Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
236                            Messages.GUI_DEFAULT_MODEL_TITLE_1,
237                            m_site.getTitle());
238                        String defDes = Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
239                            Messages.GUI_DEFAULT_MODEL_DESCRIPTION_1,
240                            m_site.getTitle());
241                        CmsProperty prop = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, defTitle, defTitle);
242                        cms.writePropertyObject(modelPage.getRootPath(), prop);
243                        prop = new CmsProperty(CmsPropertyDefinition.PROPERTY_DESCRIPTION, defDes, defDes);
244                        cms.writePropertyObject(modelPage.getRootPath(), prop);
245                        CmsFile file = cms.readFile(config);
246                        CmsXmlContent con = CmsXmlContentFactory.unmarshal(cms, file);
247                        con.addValue(cms, MODEL_PAGE, Locale.ENGLISH, 0);
248                        I_CmsXmlContentValue val = con.getValue(MODEL_PAGE_PAGE, Locale.ENGLISH);
249                        val.setStringValue(cms, modelPage.getRootPath());
250                        file.setContents(con.marshal());
251                        cms.writeFile(file);
252                    } catch (CmsException e) {
253                        LOG.error(e.getLocalizedMessage(), e);
254                    }
255                }
256            }
257
258            // update the site manager state
259            CmsSite newSite = m_site.toCmsSite();
260            OpenCms.getSiteManager().updateSite(getCms(), m_site.getOriginalSite(), newSite);
261            // update the workplace server if the changed site was the workplace server
262            if ((m_site.getOriginalSite() != null)
263                && m_site.getOriginalSite().getUrl().equals(OpenCms.getSiteManager().getWorkplaceServer())) {
264                OpenCms.getSiteManager().updateGeneralSettings(
265                    getCms(),
266                    OpenCms.getSiteManager().getDefaultUri(),
267                    Collections.singletonList(newSite.getUrl()),
268                    OpenCms.getSiteManager().getSharedFolder());
269            }
270            // write the site configuration
271            OpenCms.writeConfiguration(CmsSitesConfiguration.class);
272            // refresh the list of sites
273            Map<?, ?> objects = (Map<?, ?>)getSettings().getListObject();
274            if (objects != null) {
275                objects.remove(CmsSitesOverviewList.class.getName());
276            }
277        } catch (Exception e) {
278            addCommitError(e);
279        }
280    }
281
282    /**
283     * @see org.opencms.workplace.CmsDialog#getCancelAction()
284     */
285    @Override
286    public String getCancelAction() {
287
288        // set the default action
289        setParamPage(getPages().get(0));
290        return DIALOG_SET;
291    }
292
293    /**
294     * Returns the paramEditAction.<p>
295     *
296     * @return the paramEditAction
297     */
298    public String getParamEditaction() {
299
300        return m_paramEditaction;
301    }
302
303    /**
304     * Returns the paramSites.<p>
305     *
306     * @return the paramSites
307     */
308    public String getParamSites() {
309
310        return m_paramSites;
311    }
312
313    /**
314     * Returns the paramSitename.<p>
315     *
316     * @return the paramSitename
317     */
318    public String getSitename() {
319
320        return m_sitename;
321    }
322
323    /**
324     * Returns the template property.<p>
325     *
326     * @return the template property to set
327     */
328    public String getTemplate() {
329
330        return m_template;
331    }
332
333    /**
334     * Returns the paramCreateou.<p>
335     *
336     * @return the paramCreateou
337     */
338    public boolean isCreateou() {
339
340        return m_createou;
341    }
342
343    /**
344     * Sets the paramCreateou.<p>
345     *
346     * @param createou the paramCreateou to set
347     */
348    public void setCreateou(boolean createou) {
349
350        m_createou = createou;
351    }
352
353    /**
354     * Sets the paramEditAction.<p>
355     *
356     * @param paramEditaction the paramEditAction to set
357     */
358    public void setParamEditaction(String paramEditaction) {
359
360        m_paramEditaction = paramEditaction;
361    }
362
363    /**
364     * Sets the paramSites.<p>
365     *
366     * @param paramSites the paramSites to set
367     */
368    public void setParamSites(String paramSites) {
369
370        m_paramSites = paramSites;
371    }
372
373    /**
374     * Sets the site name.<p>
375     *
376     * @param sitename the site name to set
377     */
378    public void setSitename(String sitename) {
379
380        m_sitename = sitename;
381    }
382
383    /**
384     * Sets the the template property.<p>
385     *
386     * @param template the template property to set
387     */
388    public void setTemplate(String template) {
389
390        m_template = template;
391    }
392
393    /**
394     * @see org.opencms.workplace.CmsWidgetDialog#createDialogHtml(java.lang.String)
395     */
396    @Override
397    protected String createDialogHtml(String dialog) {
398
399        StringBuffer result = new StringBuffer(1024);
400        result.append(createWidgetTableStart());
401
402        // show error header once if there were validation errors
403        result.append(createWidgetErrorHeader());
404
405        String title = m_site.getTitle() != null
406        ? m_site.getTitle()
407        : Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(Messages.GUI_SITES_NEW_SITE_TITLE_0);
408
409        // only show the position if editing a site or creating a new site
410        int count = getParamEditaction() == null ? 4 : 5;
411        // +1 if favicon present
412        count = m_site.getFavicon() != null ? ++count : count;
413
414        // site info
415        result.append(
416            dialogBlockStart(
417                Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
418                    Messages.GUI_SITES_DETAIL_INFO_1,
419                    title)));
420        result.append(createWidgetTableStart());
421        result.append(createDialogRowsHtml(0, count));
422
423        // site parameters
424        if (DIALOG_EDIT.equals(getParamEditaction()) || DIALOG_NEW.equals(getParamEditaction())) {
425            result.append(createDialogRowsHtml(++count, count));
426        } else if (!m_site.getParameters().isEmpty()) {
427            result.append(createDialogRowsHtml(++count, (count + m_site.getParameters().size()) - 1));
428            count += m_site.getParameters().size() - 1;
429        }
430
431        // +2 for OU check box and template property when creating a new site
432        if (DIALOG_NEW.equals(getParamEditaction())) {
433            result.append(createDialogRowsHtml(++count, count + 1));
434            count += 1;
435        }
436
437        result.append(createWidgetTableEnd());
438        result.append(dialogBlockEnd());
439        if ((getParamEditaction() != null) || CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_site.getSecureUrl())) {
440            // secure site
441            result.append(
442                dialogBlockStart(
443                    Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
444                        Messages.GUI_SITES_DETAIL_SECURE_1,
445                        title)));
446            result.append(createWidgetTableStart());
447            result.append(createDialogRowsHtml(++count, count + 2));
448            result.append(createWidgetTableEnd());
449            result.append(dialogBlockEnd());
450            count += 2;
451        }
452
453        // site aliases
454        if ((DIALOG_EDIT.equals(getParamEditaction()) || DIALOG_NEW.equals(getParamEditaction()))
455            || !m_site.getAliases().isEmpty()) {
456            result.append(
457                dialogBlockStart(
458                    Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
459                        Messages.GUI_SITES_DETAIL_ALIASES_1,
460                        title)));
461            result.append(createWidgetTableStart());
462            if (DIALOG_EDIT.equals(getParamEditaction()) || DIALOG_NEW.equals(getParamEditaction())) {
463                result.append(createDialogRowsHtml(++count, count));
464            } else if (!m_site.getAliases().isEmpty()) {
465                result.append(createDialogRowsHtml(++count, (count + m_site.getAliases().size()) - 1));
466            }
467            result.append(createWidgetTableEnd());
468            result.append(dialogBlockEnd());
469        }
470
471        // close the beginning table
472        result.append(createWidgetTableEnd());
473        return result.toString();
474    }
475
476    /**
477     * @see org.opencms.workplace.CmsWidgetDialog#defineWidgets()
478     */
479    @Override
480    protected void defineWidgets() {
481
482        initSite();
483        setKeyPrefix(CmsSitesOverviewList.KEY_PREFIX_SITES);
484
485        if (DIALOG_NEW.equals(getParamEditaction()) || DIALOG_EDIT.equals(getParamEditaction())) {
486            // edit or new
487            // site info
488            addWidget(new CmsWidgetDialogParameter(m_site, "title", PAGES[0], new CmsInputWidget()));
489            addWidget(new CmsWidgetDialogParameter(this, "sitename", PAGES[0], new CmsInputWidget()));
490            addWidget(new CmsWidgetDialogParameter(m_site, "server", PAGES[0], new CmsInputWidget()));
491            addWidget(
492                new CmsWidgetDialogParameter(
493                    m_site,
494                    "errorPage",
495                    PAGES[0],
496                    new CmsVfsFileWidget(true, "", true, false)));
497            addWidget(
498                new CmsWidgetDialogParameter(m_site, "position", PAGES[0], new CmsSelectWidget(createNavOpts(m_site))));
499            addWidget(new CmsWidgetDialogParameter(m_site, "webserver", PAGES[0], new CmsCheckboxWidget()));
500            addWidget(new CmsWidgetDialogParameter(m_site, "parameters", PAGES[0], new CmsInputWidget()));
501            if (DIALOG_NEW.equals(getParamEditaction())) {
502                addWidget(new CmsWidgetDialogParameter(this, "createou", PAGES[0], new CmsCheckboxWidget()));
503                addWidget(new CmsWidgetDialogParameter(this, "template", PAGES[0], createTemplateSelect()));
504            }
505
506            if (m_site.getFavicon() != null) {
507                try {
508                    CmsObject clone = OpenCms.initCmsObject(getCms());
509                    clone.getRequestContext().setSiteRoot("");
510
511                    CmsDisplayWidget dis = new CmsDisplayWidget(
512                        "<img src='"
513                            + OpenCms.getLinkManager().getOnlineLink(clone, m_site.getFavicon())
514                            + "' border='0' width='16' height='16' />");
515                    addWidget(new CmsWidgetDialogParameter(m_site, "favicon", PAGES[0], dis));
516                } catch (Exception e) {
517                    // noop
518                }
519            }
520
521            // secure site
522            addWidget(new CmsWidgetDialogParameter(m_site, "secureUrl", PAGES[0], new CmsInputWidget()));
523            addWidget(new CmsWidgetDialogParameter(m_site, "exclusiveUrl", PAGES[0], new CmsCheckboxWidget()));
524            addWidget(new CmsWidgetDialogParameter(m_site, "exclusiveError", PAGES[0], new CmsCheckboxWidget()));
525
526            // site aliases
527            addWidget(new CmsWidgetDialogParameter(m_site, "aliases", PAGES[0], new CmsInputWidget()));
528        } else {
529            // display site
530            addWidget(new CmsWidgetDialogParameter(m_site, "title", PAGES[0], new CmsDisplayWidget()));
531            addWidget(new CmsWidgetDialogParameter(m_site, "siteRoot", PAGES[0], new CmsDisplayWidget()));
532            addWidget(new CmsWidgetDialogParameter(m_site, "server", PAGES[0], new CmsDisplayWidget()));
533            CmsWidgetDialogParameter errorPage;
534            if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_site.getErrorPage())) {
535                errorPage = new CmsWidgetDialogParameter(
536                    m_site,
537                    "errorPage",
538                    PAGES[0],
539                    new CmsDisplayWidget(
540                        Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
541                            Messages.GUI_SITES_ERROR_PAGE_NOT_AVAILABLE_0)));
542            } else {
543                errorPage = new CmsWidgetDialogParameter(m_site, "errorPage", PAGES[0], new CmsDisplayWidget());
544            }
545            addWidget(errorPage);
546            addWidget(new CmsWidgetDialogParameter(m_site, "webserver", PAGES[0], new CmsDisplayWidget()));
547            int count = 5;
548            for (String parameter : m_site.getParameters().keySet()) {
549                String output = parameter + "=" + m_site.getParameters().get(parameter);
550                CmsWidgetDialogParameter widget = new CmsWidgetDialogParameter(
551                    output,
552                    output,
553                    Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
554                        Messages.GUI_SITES_DETAIL_PARAMETERS_0) + " [" + (count - 4) + "]",
555                    new CmsDisplayWidget(),
556                    PAGES[0],
557                    1,
558                    1,
559                    count);
560                addWidget(widget);
561                count++;
562            }
563            if (m_site.getFavicon() != null) {
564                try {
565                    CmsObject clone = OpenCms.initCmsObject(getCms());
566                    clone.getRequestContext().setSiteRoot("");
567
568                    CmsDisplayWidget dis = new CmsDisplayWidget(
569                        "<img src='"
570                            + OpenCms.getLinkManager().getOnlineLink(clone, m_site.getFavicon())
571                            + "' border='0' width='16' height='16' />");
572                    addWidget(new CmsWidgetDialogParameter(m_site, "favicon", PAGES[0], dis));
573                } catch (Exception e) {
574                    // noop
575                }
576            }
577
578            if (m_site.hasSecureServer()) {
579                addWidget(new CmsWidgetDialogParameter(m_site, "secureUrl", PAGES[0], new CmsDisplayWidget()));
580                addWidget(new CmsWidgetDialogParameter(m_site, "exclusiveUrl", PAGES[0], new CmsDisplayWidget()));
581                addWidget(new CmsWidgetDialogParameter(m_site, "exclusiveError", PAGES[0], new CmsDisplayWidget()));
582            }
583            count = 0;
584            for (String aliasUrl : m_site.getAliases()) {
585                CmsWidgetDialogParameter alias = new CmsWidgetDialogParameter(
586                    aliasUrl,
587                    aliasUrl,
588                    Messages.get().getBundle(getCms().getRequestContext().getLocale()).key(
589                        Messages.GUI_SITES_DETAIL_LABEL_ALIAS_0) + " [" + (count + 1) + "]",
590                    new CmsDisplayWidget(),
591                    PAGES[0],
592                    1,
593                    1,
594                    count);
595                addWidget(alias);
596                count++;
597            }
598
599        }
600    }
601
602    /**
603     * @see org.opencms.workplace.CmsWidgetDialog#getPageArray()
604     */
605    @Override
606    protected String[] getPageArray() {
607
608        return PAGES;
609    }
610
611    /**
612     * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
613     */
614    @Override
615    protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
616
617        super.initWorkplaceRequestValues(settings, request);
618        // save the current state of the site (may be changed because of the widget values)
619        setDialogObject(m_site);
620    }
621
622    /**
623     * Build select options for the position.<p>
624     *
625     * @param currSite the current selected site
626     *
627     * @return the select options
628     */
629    private List<CmsSelectWidgetOption> createNavOpts(CmsSiteBean currSite) {
630
631        List<CmsSite> sites = new ArrayList<CmsSite>();
632        for (CmsSite site : OpenCms.getSiteManager().getAvailableSites(getCms(), true)) {
633            if (site.getSiteMatcher() != null) {
634                sites.add(site);
635            }
636        }
637
638        float maxValue = 0;
639        float nextPos = 0;
640
641        // calculate value for the first navigation position
642        float firstValue = 1;
643        if (sites.size() > 0) {
644            try {
645                maxValue = sites.get(0).getPosition();
646            } catch (Exception e) {
647                // should usually never happen
648            }
649        }
650
651        if (maxValue != 0) {
652            firstValue = maxValue / 2;
653        }
654
655        List<String> options = new ArrayList<String>(sites.size() + 1);
656        List<String> values = new ArrayList<String>(sites.size() + 1);
657
658        // add the first entry: before first element
659        options.add(getMessages().key(org.opencms.workplace.commons.Messages.GUI_CHNAV_POS_FIRST_0));
660        values.add(firstValue + "");
661
662        // show all present navigation elements in box
663        for (int i = 0; i < sites.size(); i++) {
664            String navText = sites.get(i).getTitle();
665            float navPos = sites.get(i).getPosition();
666            String siteRoot = sites.get(i).getSiteRoot();
667            // get position of next nav element
668            nextPos = navPos + 2;
669            if ((i + 1) < sites.size()) {
670                nextPos = sites.get(i + 1).getPosition();
671            }
672            // calculate new position of current nav element
673            float newPos;
674            if ((nextPos - navPos) > 1) {
675                newPos = navPos + 1;
676            } else {
677                newPos = (navPos + nextPos) / 2;
678            }
679            // check new maxValue of positions and increase it
680            if (navPos > maxValue) {
681                maxValue = navPos;
682            }
683            // if the element is the current file, mark it in select box
684            if ((currSite != null) && (currSite.getSiteRoot() != null) && currSite.getSiteRoot().equals(siteRoot)) {
685                options.add(
686                    CmsEncoder.escapeHtml(
687                        getMessages().key(
688                            org.opencms.workplace.commons.Messages.GUI_CHNAV_POS_CURRENT_1,
689                            new Object[] {sites.get(i).getSiteRoot()})));
690                values.add("-1");
691            } else {
692                options.add(CmsEncoder.escapeHtml(navText + " [" + sites.get(i).getSiteRoot() + "/]"));
693                values.add(newPos + "");
694            }
695        }
696
697        // add the entry: at the last position
698        options.add(getMessages().key(org.opencms.workplace.commons.Messages.GUI_CHNAV_POS_LAST_0));
699        values.add((maxValue + 1) + "");
700
701        // add the entry: no change
702        options.add(getMessages().key(org.opencms.workplace.commons.Messages.GUI_CHNAV_NO_CHANGE_0));
703        if ((currSite != null) && (currSite.getPosition() == Float.MAX_VALUE)) {
704            // current resource has no valid position, use "last position"
705            values.add((maxValue + 1) + "");
706        } else {
707            // current resource has valid position, use "-1" for no change
708            values.add("-1");
709        }
710        List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>();
711        for (int i = 0; i < values.size(); i++) {
712            String val = values.get(i);
713            String opt = options.get(i);
714            result.add(new CmsSelectWidgetOption(val, false, opt));
715        }
716        return result;
717    }
718
719    /**
720     * Helper method for creating the .content folder of a sub-sitemap.<p>
721     *
722     * @param cms the current CMS context
723     * @param subSitemapFolder the sub-sitemap folder in which the .content folder should be created
724     *
725     * @return the created folder
726     *
727     * @throws CmsException if something goes wrong
728     * @throws CmsLoaderException if something goes wrong
729     */
730    private CmsResource createSitemapContentFolder(CmsObject cms, CmsResource subSitemapFolder)
731    throws CmsException, CmsLoaderException {
732
733        CmsResource configFile = null;
734        String sitePath = cms.getSitePath(subSitemapFolder);
735        String folderName = CmsStringUtil.joinPaths(sitePath, CmsADEManager.CONTENT_FOLDER_NAME + "/");
736        String sitemapConfigName = CmsStringUtil.joinPaths(folderName, CmsADEManager.CONFIG_FILE_NAME);
737        if (!cms.existsResource(folderName)) {
738            cms.createResource(
739                folderName,
740                OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_FOLDER_TYPE));
741        }
742        I_CmsResourceType configType = OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE);
743        if (cms.existsResource(sitemapConfigName)) {
744            configFile = cms.readResource(sitemapConfigName);
745            if (!OpenCms.getResourceManager().getResourceType(configFile).getTypeName().equals(
746                configType.getTypeName())) {
747                throw new CmsException(
748                    Messages.get().container(
749                        Messages.ERR_CREATING_SUB_SITEMAP_WRONG_CONFIG_FILE_TYPE_2,
750                        sitemapConfigName,
751                        CmsADEManager.CONFIG_TYPE));
752            }
753        } else {
754            configFile = cms.createResource(
755                sitemapConfigName,
756                OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE));
757        }
758        return configFile;
759    }
760
761    /**
762     * Creates a template select combo widget.<p>
763     *
764     * @return the widget
765     */
766    private CmsComboWidget createTemplateSelect() {
767
768        List<CmsSelectWidgetOption> options = new ArrayList<CmsSelectWidgetOption>();
769        try {
770            I_CmsResourceType templateType = OpenCms.getResourceManager().getResourceType(
771                CmsResourceTypeJsp.getContainerPageTemplateTypeName());
772            List<CmsResource> templates = getCms().readResources(
773                "/system/",
774                CmsResourceFilter.DEFAULT.addRequireType(templateType));
775            for (CmsResource res : templates) {
776                options.add(new CmsSelectWidgetOption(res.getRootPath()));
777            }
778
779        } catch (CmsException e) {
780            LOG.error(e.getMessage(), e);
781        }
782        return new CmsComboWidget(options);
783    }
784
785    /**
786     * Checks if there are at least one character in the folder name,
787     * also ensures that it starts and ends with a '/'.<p>
788     *
789     * @param resourcename folder name to check (complete path)
790     *
791     * @return the validated folder name
792     *
793     * @throws CmsIllegalArgumentException if the folder name is empty or <code>null</code>
794     */
795    private String ensureFoldername(String resourcename) throws CmsIllegalArgumentException {
796
797        if (CmsStringUtil.isEmpty(resourcename)) {
798            throw new CmsIllegalArgumentException(
799                org.opencms.db.Messages.get().container(org.opencms.db.Messages.ERR_BAD_RESOURCENAME_1, resourcename));
800        }
801        if (!CmsResource.isFolder(resourcename)) {
802            resourcename = resourcename.concat("/");
803        }
804        if (resourcename.charAt(0) != '/') {
805            resourcename = "/".concat(resourcename);
806        }
807        return resourcename;
808    }
809
810    /**
811     * Initializes the dialog site object.<p>
812     */
813    private void initSite() {
814
815        Object o = null;
816        if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) {
817            // this is the initial dialog call
818            if (CmsStringUtil.isNotEmpty(m_paramSites)) {
819                // edit an existing site, get it from manager
820                o = OpenCms.getSiteManager().getSiteForSiteRoot(m_paramSites);
821            }
822        } else {
823            // this is not the initial call, get site from session
824            o = getDialogObject();
825        }
826        if (o instanceof CmsSite) {
827            // reuse site stored in session
828            m_site = new CmsSiteBean((CmsSite)o);
829        } else if (o instanceof CmsSiteBean) {
830            // create a new site
831            m_site = (CmsSiteBean)o;
832        } else if (DIALOG_NEW.equals(getParamEditaction())) {
833            m_site = new CmsSiteBean();
834        } else {
835            try {
836                getToolManager().jspForwardTool(this, "/sites", new HashMap<String, String[]>());
837            } catch (Exception e) {
838                // noop
839            }
840        }
841
842        if (!m_site.hasSecureServer()) {
843            m_site.setSecureUrl("");
844        }
845        try {
846            CmsObject clone = OpenCms.initCmsObject(getCms());
847            clone.getRequestContext().setSiteRoot("");
848            String iconPath = m_site.getSiteRoot() + "/" + CmsSiteFaviconDialog.ICON_NAME;
849            if (clone.existsResource(iconPath)) {
850                m_site.setFavicon(iconPath);
851            }
852        } catch (Throwable t) {
853            // noop
854        }
855
856        if (m_site.getSiteRoot() != null) {
857            setSitename(CmsResource.getName(m_site.getSiteRoot()));
858        }
859
860        CmsModule module = OpenCms.getModuleManager().getModule(MODULE_NAME);
861        m_createou = Boolean.valueOf(module.getParameter(PARAM_CREATE_OU, Boolean.FALSE.toString())).booleanValue();
862        m_ouDescription = module.getParameter(PARAM_OU_DESCRIPTION, "OU for: %(site)");
863        setDialogObject(m_site);
864    }
865
866    /**
867     * Validates the dialog before the commit action is performed.<p>
868     *
869     * @throws Exception if sth. goes wrong
870     */
871    private void validateDialog() throws Exception {
872
873        CmsResource.checkResourceName(m_sitename);
874        m_sitename = ensureFoldername(m_sitename);
875        if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_site.getServer())) {
876            // the server's URL must not be empty or null
877            throw new CmsException(Messages.get().container(Messages.ERR_SERVER_URL_NOT_EMPTY_0));
878        }
879    }
880}