Location: PHPKode > projects > Blandware AtLeap Lite - CMS on PHP > atleaplite/include/actions/page.php
<?php
/*
 *  Copyright 2008 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Actions for pages.
 *
 * @package     AtleapLite
 * @author      Roman Puchkovskiy
 * @license     http://www.apache.org/licenses/LICENSE-2.0  Apache License, Version 2.0
 */

require_once 'HTML/AJAX/JSON.php';

// ~ DAO functions

/**
 * Loads pages from DB.
 *
 * @param array $queryInfo optional query info
 * @param string $gridName optional grid name
 * @see loadObjects()
 * @return array objects
 */
function loadPages($queryInfo = array(), $gridName = 'pagesGrid')
{
    return loadObjects('page', getPageDescriptor(), $gridName, $queryInfo);
}

/**
 * Creates a page.
 *
 * @param object $dao   dao object
 * @param object $form  form object
 * @param array $layout layout
 * @return bool|array false if failed or array: 'page' => created page,
 * 'fields' => array of created fields
 */
function &addPage(&$dao, &$form, &$layout)
{
    $dao->fixed = 0;
    $dao->modification_date = getNowDate();
    $dao->insert();
    $success = isset($dao->id);

    if (!$success) {
        return false;
    }

    $fields = array();
    foreach ($layout['fields'] as $field) {
        $identifier = $field['identifier'];
        $value = $form->getElementValue("fields[$identifier]");
        $field =& getDao('field');
        $field->identifier = $identifier;
        $field->page_id = $dao->id;
        $field->data = $value;
        $field->insert();
        $fields[] = $field;
    }

    return array('page' => $dao, 'fields' => $fields);
}

/**
 * Updates a page.
 *
 * @param int $id       page ID
 * @param object $form  form object
 * @param array $layout layout
 * @return bool|array false if failed or array: 'page' => created page,
 * 'fields' => array of page fields
 */
function &savePage($id, &$form, &$layout)
{
    $dao =& staticGet('page', $id);
    $oldLayout = $dao->layout;
    formToDao($form, $dao, getPageDescriptor());
    $dao->layout = $oldLayout;
    $dao->modification_date = getNowDate();
    $success = $dao->update();

    $fields = array();
    foreach ($layout['fields'] as $field) {
        $identifier = $field['identifier'];
        $value = $form->getElementValue("fields[$identifier]");
        $field =& getDao('field');
        $field->identifier = $identifier;
        $field->page_id = $dao->id;
        $n = $field->find(true);
        if ($n != 1) {
            $field =& getDao('field');
            $field->identifier = $identifier;
            $field->page_id = $dao->id;
            $field->insert();
        }
        $field->data = $value;
        $field->update();
        $fields[] = $field;
    }

    return array('page' => $dao, 'fields' => $fields);
}

// ~ Actions

/**
 * Shows a page with list of pages.
 */
function listPages() {
    global $smarty, $perPage, $pagerDelta, $bottomLinks;

    processGridParams('pagesGrid', array('layout' => -1, 'language' => -1/*, 'page_active' => -1*/));
    $queryInfo = buildDefaultQueryInfo();
//    $queryInfo['additionalSelect'] = array("(published AND ('" . getNowDate() . "' BETWEEN publication_date AND expiration_date)) as page_active");
    $partial = loadPages($queryInfo);
    $total = $partial['total'];
    $pages = $partial['rows'];
    $pager = getPager(array('totalItems' => $total));
    exportPagerData($pager, $smarty, $pages);
    assignSortDirs('pagesGrid', $smarty, getPageDescriptor());
    assignFilters($smarty, 'pagesGrid');

    $smarty->assign('template', 'page/list.tpl');
    $smarty->assign('title', getMessage('page.list.title'));

    $smarty->assign('allowedViewPage', allowed('viewPage'));
    $smarty->assign('allowedUpdatePage', allowed('updatePage'));
    $smarty->assign('allowedDeletePage', allowed('deletePage'));
    $smarty->assign('deletePermId', 'deletePage');

    $smarty->initGrid('pagesGrid', getPageDescriptor(), $_GET['action']);

    $smarty->assign('layouts', getLayoutsForSelect(true));
    $smarty->assign('languagesForSelect', getLanguagesForSelect(true));
    $smarty->assign('allYesNoList', getAllYesNoList());

    setSystemMenuItemBold('managePages');

    $bottomLinks[] = array('link' => buildUrl('callCreatePage'),
                           'text' => getMessage('common.button.create'), 
                           'permId' => 'createPage',
                           'button' => true);
}

/**
 * Allows to view page properties.
 */
function viewPage()
{
    global $smarty, $bottomLinks;

    $bottomLinks[] = array('link' => getPageListUrl('title'),
                           'text' => getMessage('common.button.ok'),
                           'permId' => 'listPages',
                           'button' => true);
    $bottomLinks[] = array('link' => buildUrl('callUpdatePage', array('id' => $_GET['id'])),
                           'text' => getMessage('common.button.edit'),
                           'permId' => 'updatePage',
                           'button' => true);

    $dao =& staticGet('page', $_GET['id']);
    $smarty->assign('viewed', $dao);

    $smarty->assign('template', 'page/view.tpl');
    $smarty->assign('title', getMessage('page.view.title'));
}

/**
 * Displays a page to user.
 */
function showPage() {
    global $smarty, $bottomLinks;

    if (isset($_GET['identifier'])) {
        $identifier = $_GET['identifier'];
        $language = getCurrentLanguage();
        $page = getPageFromCacheOrDb($identifier, $language);
        if (empty($page->id)) {
            // no page in current language, possibly there's something in the
            // default language
            if ($language != getDefaultLanguage()) {
                $language = getDefaultLanguage();
                $page = getPageFromCacheOrDb($identifier, $language);
            }
        }
    }

    $active = true;
    if (!empty($page->id)) {
        $active = $page->isActive();
    }

    if (!empty($page->id) && $active) {
    	//client caching logic
        $cached = processPageCache(strtotime($page->modification_date));
        if ($cached) {
            $smarty->setNoOutput();
            return;
        }

        $layout = getLayout($page->layout);
        $outerTemplate = $layout['outerTemplate'];
        $innerTemplate = $layout['innerTemplate'];
        $smarty->assign('page', $page);
        $smarty->assign('template', $innerTemplate);
        $smarty->setDisplayLayout($layout);
    } else {
        $smarty->assign('template', 'no_page.tpl');
        $smarty->assign('title', getMessage('common.error'));
        $smarty->setAdminLayout(false);
    }
}

/**
 * Implements page client caching logic. If page does not need to be output
 * because it's still in cache, this function returns true.
 *
 * @param long $lastModified    last modified time-stamp
 * @return true if page is cached
 */
function processPageCache($lastModified) {
    //client caching logic
    $maxAge = getGlobalProperty('pageCacheMaxAge');
    if ($maxAge < 0) {
        header("Cache-Control: no-cache,no-store,max-age=0");
        header("Pragma: no-cache");
    } else {
        $cacheType = "public";

        $editMode = "false";
        if (!isAnonymous()) {
            $editMode = "true";
            $maxAge = 0;
        }

        header("Cache-Control: $cacheType,max-age=$maxAge");
        header("Pragma: ");
        $expireTime = gmdate("D, d M Y H:i:s", time() + $maxAge);
        header("Expires: $expireTime GMT");

        //check for entity tag
        if ($_SERVER['REQUEST_METHOD'] == "GET" && $lastModified != -1) {
            //ETag generation
            $locale = getCurrentLanguage();
            $username = getCurrentUser();

            $eTag = "W/\"$locale-$username-$editMode-$lastModified\"";
            header("ETag: $eTag");

            $conditionSatisfied = false;
            $headerValue = $_SERVER['HTTP_IF_NONE_MATCH'];
            if (get_magic_quotes_gpc() == 1) {
                $headerValue = stripslashes($headerValue);
            }
            if ($headerValue != null) {
                if ($headerValue != "*") {
                    $tokens = explode(',', $headerValue);
                    foreach ($tokens as $currentToken) {
                        if (trim($currentToken) == $eTag) {
                            $conditionSatisfied = true;
                        }
                    }
                } else {
                    $conditionSatisfied = true;
                }
                if ($conditionSatisfied) {
                    header("HTTP/1.0 304 Not Modified");
                    return true;
                }
            }
		}
	}
    return false;
}

/**
 * Creates an empty page form.
 *
 * @param string $name      form name
 * @param string $method    HTTP method
 * @param string $action    action
 * @param int $id optional  page ID (for updating)
 * @return object created form
 */
function &createEmptyPageForm($name, $method, $action, $id = null) {
    $params = array();
    if ($id != null) {
        $params['id'] = $id;
    }

    $form = new FormBase($name, $method, buildUrl($action, $params));

    return $form;
}

/**
 * Adds elements specific to page itself to form.
 *
 * @param object $form      form object
 * @param bool $create      whether this is for for creation, not for updating
 * @param string $layoutIdentifier identifier of the layout for which page
 * is created/updated (if a new page is created, it's null)
 * @param bool $initFlags   whether flags which are checked for newly created
 * pages should be checked
 */
function addPageElementsToForm(&$form, $create, $layoutIdentifier, $initFlags) {
    if ($create) {
        // no layout identifier is given, possibly we should take it from
        // parameters
        if (isset($_GET['layout'])) {
            $layoutIdentifier = $_GET['layout'];
        }

    }
    $identifier = ($create && $initFlags && !empty($_GET['identifier']))
            ? $_GET['identifier'] : null;
    $form->addTextElement('identifier', getMessage('page.form.identifier'), array('value' => $identifier));
    $form->addSelectElement('language', getMessage('page.form.language'), getLanguagesForSelect());
    if ($create && $initFlags && isset($_GET['languageCode'])) {
        $languageElem =& $form->getElement('language');
        $languageElem->setValue($_GET['languageCode']);
        $languageElem->freeze();
    }
    $form->addTextElement('title', getMessage('page.form.title'));
    $form->addTextElement('keywords', getMessage('page.form.keywords'));
    $form->addTextElement('description', getMessage('page.form.description'));
    $form->addSelectElement('layout', getMessage('page.form.layout'), getLayoutsForSelect(), array('onchange' => 'updateMenuList(this, "layoutsMenus", "menu")'));
    if ($create && $initFlags && isset($_GET['layout'])) {
        $layoutElem =& $form->getElement('layout');
        $layoutElem->setValue($_GET['layout']);
        $layoutElem->freeze();
    }
    if (!$create) {
        $layoutElem =& $form->getElement('layout');
        $layoutElem->freeze();
    }
    $form->addHiddenElement('layoutsMenus', packLayoutsMenus(getLayoutsMenus()));
    $form->addSelectElement('menu', getMessage('page.form.menu'), getMenusForSelect($layoutIdentifier, false));
    if ($create && $initFlags && isset($_GET['menu'])) {
        $menuElem =& $form->getElement('menu');
        $menuElem->setValue($_GET['menu']);
        $menuElem->freeze();
    }
    $form->addTextElement('menuIndex', getMessage('page.form.menuIndex'));
    $form->addCheckboxElement('published', getMessage('page.form.published'));
    if ($create && $initFlags) {
        $publishedElem =& $form->getElement('published');
        $publishedElem->setValue(true);
    }
    addCommonCalendarDateElement($form, 'publicationDate', getMessage('page.form.publicationDate'));
    $form->addCalendarDateElement('expirationDate', getMessage('page.form.expirationDate'), null,
            array('phpDatePattern' => DATE_PATTERN,
                'calendarDatePattern' => CALENDAR_DATE_PATTERN,
                'imgSrc' => 'images/calendar.gif',
                'startDate' => mktime(0, 0, 0, date("m"), date("d"), date("Y")+1)
                ));

    $form->addRequiredRule('title', getMessage('page.error.title.required'));
    $form->addRequiredRule('identifier', getMessage('page.error.identifier.required'));
    $form->addExtendedIdentifierRule('identifier', getMessage('page.error.identifier.extendedIdentifier'));
    $form->addDigitsRule('menuIndex', getMessage('page.error.menuIndex.digits'));
    $form->addFormRule($create ? 'validateCreatePageForm' : 'validateUpdatePageForm');
}

/**
 * Adds elements specific to page fields to form.
 *
 * @param object $form              form object
 * @param string $layoutIdentifier  identifier of layout
 */
function addFieldsElementsToForm(&$form, $layoutIdentifier) {
    $layout = getLayout($layoutIdentifier);

    $values = loadPageFieldsFromSession();

    foreach ($layout['fields'] as $field) {
        $identifier = $field['identifier'];
        $form->addRicheditElement("fields[$identifier]", $field['title']);
        if (is_array($values) && isset($values[$identifier])) {
            $elem =& $form->getElement("fields[$identifier]");
            $elem->setValue($values[$identifier]);
        }
    }
}

/**
 * Creates a form for page creation.
 *
 * @param string $method    HTTP method
 * @param bool $firstInocation  if true, this is first time form page is opened
 * @return object created form
 */
function &createCreatePageForm($method, $firstInvocation) {
    $form =& createEmptyPageForm('createPage', $method, 'callCreatePageFields');
    addPageElementsToForm($form, true, null, $firstInvocation);

    $form->addProceedElement(getMessage('common.button.next'));
    $form->addCancelElement(getMessage('common.button.cancel'));

    return $form;
}

/**
 * Creates a form for page fields creation.
 *
 * @param string $method            HTTP method
 * @param string $layoutIdentifier  identifier of layout
 * @return object created form
 */
function &createPageFieldsForm($method, $layoutIdentifier) {
    $form =& createEmptyPageForm('createPageFields', $method, 'createPage');

    addFieldsElementsToForm($form, $layoutIdentifier);

    $form->addProceedElement(getMessage('common.button.create'));
    $form->addCancelElement(getMessage('common.button.cancel'));
    $form->addBackElement(getMessage('common.button.back'));

    return $form;
}

/**
 * Creates a form for page update.
 *
 * @param string $method    HTTP method
 * @param bool $init        whether form needs to be initialized from dao
 * @return object created form
 */
function &createUpdatePageForm($method, $init, $dao, $layout) {
    $form =& createEmptyPageForm('updatePage', $method, 'updatePage', $dao->id);
    addPageElementsToForm($form, false, $dao->layout, false);
    addFieldsElementsToForm($form, $dao->layout);

    $form->addProceedElement(getMessage('common.button.update'));
    $form->addCancelElement(getMessage('common.button.cancel'));
    if (!$dao->isFixed() && allowed('deletePage')) {
        // we don't have a real back button here, so we utilize this one for
        // delete button
        $form->addBackElement(getMessage('common.button.delete'), array('onclick' => "return confirm('" . getMessage('page.form.confirmDelete') . "')"));
    }

    if ($init) {
        daoToForm($dao, $form, getPageDescriptor());
        $fields = $dao->getFields();
        foreach ($layout['fields'] as $field) {
            $identifier = $field['identifier'];
            $elem =& $form->getElement("fields[$identifier]");
            $fieldDao = findDaoByProperty($fields, 'identifier', $identifier);
            if ($fieldDao) {
                $elem->setValue($fieldDao->data);
            }
        }
    }

    return $form;
}

/**
 * Shows a page with form to create a page (i.e. step 1 or page creation).
 */
function callCreatePage()
{
    global $smarty, $bottomLinks;

    saveReturnUrlToSession('page');

    setSystemMenuItemBold('managePages');

    removePageFromSession();
    removePageFieldsFromSession();

    $form =& createCreatePageForm('POST', true);

    showForm($smarty, $form, 'page/create.tpl', getMessage('page.create.title'));
}

/**
 * Shows a page with form to create page fields (i.e. step 2 or page creation).
 */
function callCreatePageFields()
{
    global $smarty, $bottomLinks;

    setSystemMenuItemBold('managePages');

    if (isCancelled()) {
        removePageFromSession();
        removePageFieldsFromSession();
        redirectToReturnUrlOrStandardPageUrl('title');
    }

    $form =& createCreatePageForm('POST', false);
    if ($form->validate()) {
        $dao =& getDao('page');
        formToDao($form, $dao, getPageDescriptor());
        savePageToSession($dao);

        $form =& createPageFieldsForm('POST', $dao->layout);

        $layout = getLayout($dao->layout);
        $smarty->assign('fields', $layout['fields']);

        showForm($smarty, $form, 'page/create_fields.tpl', getMessage('page.createFields.title'));
    } else {
        showForm($smarty, $form, 'page/create.tpl', getMessage('page.create.title'));
    }
}

/**
 * Creates a page.
 */
function createPage()
{
    global $smarty, $bottomLinks;

    setSystemMenuItemBold('managePages');

    if (isCancelled()) {
        removePageFromSession();
        removePageFieldsFromSession();
        redirectToReturnUrlOrStandardPageUrl('title');
    }

    $dao = loadPageFromSession();
    $form =& createPageFieldsForm('POST', $dao->layout);
    $layout = getLayout($dao->layout);

    if (isBackPressed()) {
        
        $container = array();
        foreach ($layout['fields'] as $field) {
            $identifier = $field['identifier'];
            $container[$identifier] = $form->getElementValue("fields[$identifier]");
        }
        savePageFieldsToSession($container);

        $dao = loadPageFromSession();
        $form =& createCreatePageForm('POST', false);
        daoToForm($dao, $form, getPageDescriptor());

        showForm($smarty, $form, 'page/create.tpl', getMessage('page.create.title'));
        return;
    }


    if ($form->validate()) {
        $pageAndFields =& addPage(loadPageFromSession(), $form, $layout);
        if ($pageAndFields) {
            $page = $pageAndFields['page'];
            $fields = $pageAndFields['fields'];

            $cacheManager = new CacheManager();
            $cacheManager->putPage($page);
            foreach ($fields as $field) {
                $cacheManager->putField($field);
            }
            $cacheManager->cleanMenuPages();
        }
        removePageFromSession();
        removePageFieldsFromSession();
        redirectToReturnUrlOrStandardPageUrl();
    } else {
        showForm($smarty, $form, 'page/create_fields.tpl', getMessage('page.createFields.title'));
    }
}

/**
 * Shows a page with form to update a page.
 */
function callUpdatePage()
{
    global $smarty, $bottomLinks;

    saveReturnUrlToSession('page');

    setSystemMenuItemBold('managePages');

    $dao =& staticGet('page', $_GET['id']);
    $layout = getLayout($dao->layout);
    $form =& createUpdatePageForm('POST', true, $dao, $layout);

    $smarty->assign('fields', $layout['fields']);

    showForm($smarty, $form, 'page/update.tpl', getMessage('page.update.title'));
}

/**
 * Updates a page.
 */
function updatePage()
{
    global $smarty, $bottomLinks;

    if (isCancelled()) {
        redirectToReturnUrlOrStandardPageUrl('title');
    }

    // the 'back' button is used for delete button
    if (isBackPressed()) {
        $returnUrl = loadReturnUrlFromSession('page');
        if (!allowed('deletePage')) {
            setupForb(null, $returnUrl);
            return;
        }
        $deleted = deletePageById($_GET['id']);
        if (!$returnUrl) {
            $returnUrl = getPageListUrl('title');
        }
        if ($deleted) {
            redirect($returnUrl);
        } else {
            $smarty->assign('template', 'error.tpl');
            $smarty->assign('reason', getMessage('page.error.cannotDelete'));
            $smarty->assign('link', $returnUrl);
        }
    }

    setSystemMenuItemBold('managePages');

    $dao =& staticGet('page', $_GET['id']);
    $layout = getLayout($dao->layout);
    $form =& createUpdatePageForm('POST', false, $dao, $layout);

    $oldIdentifier = $dao->identifier;
    $oldLanguage = $dao->language;

    if ($form->validate()) {
        $pageAndFields =& savePage($_GET['id'], $form, $layout);
        $page = $pageAndFields['page'];
        $fields = $pageAndFields['fields'];

        $cacheManager = new CacheManager();
        $cacheManager->removePage($oldIdentifier, $oldLanguage);
        $cacheManager->putPage($page);
        foreach ($fields as $field) {
            $cacheManager->putField($field);
        }
        $cacheManager->cleanMenuPages();

        redirectToReturnUrlOrStandardPageUrl();
    } else {
        $smarty->assign('fields', $layout['fields']);
        showForm($smarty, $form, 'page/update.tpl', getMessage('page.update.title'));
    }
}

/**
 * Validates a form which is used to create a page.
 *
 * @param array $fields assoc array from field names to values
 * @return bool|array true if form is valid or assoc array with errors
 */
function validateCreatePageForm($fields) {
    return validatePageForm($fields, true);
}

/**
 * Validates a form which is used to update a page.
 *
 * @param array $fields assoc array from field names to values
 * @return bool|array true if form is valid or assoc array with errors
 */
function validateUpdatePageForm($fields) {
    return validatePageForm($fields, false);
}

/**
 * Validates a page form.
 *
 * @param array $fields assoc array from field names to values
 * @param bool $create  whether this is creation form
 * @return bool|array true if form is valid or assoc array with errors
 */
function validatePageForm($fields, $create)
{
    if (pageHasDuplicates($fields, $create)) {
        return array('identifier' => getMessage('page.error.duplicate.identifierLanguage'));
    }

    return true;
}

/**
 * Returns whether page has duplicates.
 *
 * @param array $fields         assoc array from field names to values
 * @param bool $create          whether this is creation form being validated
 * @return bool true if there are duplicates
 */
function pageHasDuplicates($fields, $create) {
    $id = $_GET['id'];
    $identifier = $fields['identifier'];
    $language = $fields['language'];
    $dao =& getDao('page');
    $escapedIdentifier = $dao->escape($identifier);
    $escapedLanguage = $dao->escape($language);

    $dao->selectAdd();
    $dao->selectAdd('count(*) as _c');

    $dao->whereAdd();
    $dao->whereAdd("(identifier = '$escapedIdentifier')");
    $dao->whereAdd("(language = '$escapedLanguage')");
    if (!$create) {
        $dao->whereAdd("(id != $id)");
    }
    $dao->find(true);
    return $dao->_c > 0;
}

/**
 * Deletes a page by its ID.
 *
 * @param int $id   page ID
 * @return bool whether removal was successful
 */
function deletePageById($id)
{
    global $smarty, $bottomLinks;

    $dao =& staticGet('page', $id);

    return tryDeletePage($dao);
}

/**
 * Deletes a page.
 */
function deletePage()
{
    global $smarty, $bottomLinks;

    setSystemMenuItemBold('managePages');

    if (deletePageById($_GET['id'])) {
        saveReturnUrlToSession('page');
        redirectToReturnUrlOrStandardPageUrl();
    } else {
        $smarty->assign('template', 'error.tpl');
        $smarty->assign('reason', getMessage('page.error.cannotDelete'));
        $smarty->assign('link', getPageListUrl());
    }
}

/**
 * Deletes several pages.
 */
function massDeletePages()
{
    if (isset($_GET['checked'])) {
        foreach ($_GET['checked'] as $id => $on) {
            $dao =& staticGet('page', $id);
            tryDeletePage($dao);
        }
    }
    redirect(getPageListUrl());
}

/**
 * Tryies to delete a page.
 *
 * @param object $dao   object to delete
 * @return true if deletion was successful
 */
function tryDeletePage($dao) {
    if ($dao->fixed) {
        return false;
    }
    $id = $dao->id;
    $identifier = $dao->identifier;
    $layout = getLayout($dao->layout);
    $dao->deleteSubObjects();
    $result = $dao->delete();
    if ($result) {
        $cacheManager = new CacheManager();
        $cacheManager->removePage($identifier, $dao->language);
        foreach ($layout['fields'] as $fieldIdentifier => $v) {
            $cacheManager->removeField($id, $fieldIdentifier);
        }
        $cacheManager->cleanMenuPages();
    }
    return $result;
}

/**
 * Returns URL to list of pages.
 *
 * @param string $colon optional    colon by which to sort
 * @return URL
 */
function getPageListUrl($colon = null) {
    if (empty($colon)) {
        $colon = $_SESSION['sortColon'];
    }
    return buildUrl('listPages'/*, array('sortColon' => $colon)*/);
}

/**
 * If there's a return URL in session, redirects to it. Otherwise, redirects to
 * standard page URL.
 *
 * @param string $colon colon which will be used for sorting
 */
function redirectToReturnUrlOrStandardPageUrl($colon = null) {
    $returnUrl = loadReturnUrlFromSession('page');
    if ($returnUrl) {
        redirect($returnUrl);
    } else {
        redirect(getPageListUrl($colon));
    }
}

/**
 * Returns assoc array from layout identifiers to layout titles plus element
 * for 'all', if requested.
 *
 * @param bool $addNotSelected  if true, 'all' element will be added
 * @return array assoc array from identifier to title of layout
 */
function getLayoutsForSelect($addNotSelected = false) {
    global $layouts;
    
    $result = array();
    if ($addNotSelected) {
        $result[-1] = getMessage('common.all');
    }
    foreach ($layouts as $layout) {
        if ($layout['system']) {
            // skipping system layouts
            continue;
        }
        $result[$layout['identifier']] = $layout['title'];
    }
    return $result;
}

/**
 * Returns a list with names of all menus for all layouts.
 *
 * @global array layouts
 * @return layouts with menu identifiers
 */
function getLayoutsMenus() {
    global $layouts;

    $result = array();
    foreach ($layouts as $layout) {
        $menus = array();
        foreach ($layout['menus'] as $menu) {
            $menus[$menu['identifier']] = $menu['title'];
        }
        $result[$layout['identifier']] = $menus;
    }
    return $result;
}

/**
 * Turns layouts with menus to JSON form.
 *
 * @param array $array the array to process
 * @return the result
 */
function packLayoutsMenus($array) {
    $json = new HTML_AJAX_JSON();
    return $json->encode($array);
}

/**
 * Returns assoc array from menu identifiers to menu titles plus element
 * for 'all', if requested. Menus are taken from the first layout in list which
 * is not admin layout.
 *
 * @global layouts  list of layouts
 * @param string $layoutIdentifier the identifier of layout from which to take
 * menus; if null, then the first layout of all of them will be taken which is
 * not admin layout
 * @param bool $addNotSelected  if true, 'all' element will be added
 * @return array assoc array from identifier to title of menu
 */
function getMenusForSelect($layoutIdentifier, $addNotSelected) {
    global $layouts;

    $menus = array();
    if ($layoutIdentifier !== null) {
        $menus = $layouts[$layoutIdentifier]['menus'];
    } else {
        foreach ($layouts as $layout) {
            if ($layout['system']) {
                // skipping system layouts
                continue;
            }
            $menus = $layout['menus'];
            break;
        }
    }
    
    $result = array();
    if ($addNotSelected) {
        $result[-1] = getMessage('common.all');
    }
    $result[''] = getMessage('common.no');
    foreach ($menus as $menu) {
        $result[$menu['identifier']] = $menu['title'];
    }
    return $result;
}

/**
 * Saves page to session.
 *
 * @param object $dao   object to save
 */
function savePageToSession($dao) {
    $dao->modification_date = getNowDate();
    $array = daoToArray($dao, getPageDescriptor());
    $_SESSION['createdPage'] = $array;
}

/**
 * Loads page from session.
 *
 * @return object page
 */
function loadPageFromSession() {
    $dao =& getDao('page');
    arrayToDao($_SESSION['createdPage'], $dao, getPageDescriptor());
    return $dao;
}

/**
 * Removes a saved page from session.
 */
function removePageFromSession() {
    unset($_SESSION['createdPage']);
}

/**
 * Saves page fields to session.
 *
 * @param array $dao    object to save
 */
function savePageFieldsToSession($container) {
    $_SESSION['createdPageFields'] = $container;
}

/**
 * Loads page fields from session.
 *
 * @return array fields
 */
function loadPageFieldsFromSession() {
    return $_SESSION['createdPageFields'];
}

/**
 * Removes saved page fields from session.
 */
function removePageFieldsFromSession() {
    unset($_SESSION['createdPageFields']);
}

/**
 * First looks for a page in cache, then in DB. If page is found in DB, it's
 * put to cache.
 *
 * @param string $identifier    page identifier
 * @param string $language      page language
 * @return object page
 */
function getPageFromCacheOrDb($identifier, $language) {
    $cacheManager = new CacheManager();
    $page = $cacheManager->getPage($identifier, $language);
    if ($page == null) {
        // cache miss
        $page =& getDao('page');
        $page->findByIdentifierAndLanguage($identifier, $language);
        if (!empty($page->id)) {
            $cacheManager->putPage($page);
        }
    }
    return $page;
}


?>
Return current item: Blandware AtLeap Lite - CMS on PHP