Location: PHPKode > projects > Blandware AtLeap Lite - CMS on PHP > atleaplite/include/common.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.
 */

/**
 * Contains some common utilities; used to include some common includes.
 *
 * @package     AtleapLite
 * @author      Roman Puchkovskiy
 * @license     http://www.apache.org/licenses/LICENSE-2.0  Apache License, Version 2.0
 */

/**
 */
require_once 'DB/DataObject.php';

/**
 */
require 'include/constants.php';
require 'include/config.php';
require 'include/global_settings.php';

require 'server_options.php';
require_once 'include/util/logging.php';
require_once 'include/datetime.php';
require_once 'include/descriptors.php';
require_once 'include/util/resource_types.php';
require_once 'include/util/cache_manager.php';
require_once 'include/util/global_properties.php';
require 'include/languages.php';
require_once 'include/util/messages.php';
require_once 'include/util/image_util.php';
require_once 'include/util/language.php';

require_once 'include/session.php';
require_once 'include/security.php';
require_once 'include/convert.php';

require 'include/layouts.php';
require 'include/menus.php';

/**
 * Whether DataObject has already been configured (used to avoid unnecessary
 * configuration)
 *
 * @internal
 */
$configuredDataObject = false;

$layouts = rebuildArray($layouts);

/**
 * Configures DataObject.
 *
 * @global bool whether DataObject has already been configured
 */
function configurateDataObject($dsn)
{
	global $configuredDataObject/*, $dsn*/;

    // Configurate DataObject
	if (!$configuredDataObject) {
        $config = parse_ini_file('dataobject/dataobject.ini',TRUE);
        foreach($config as $class=>$values) {
            if ($class == 'DB_DataObject') {
                // swapping database definition, because DabaObject will not
                // parse ini if DSN has query string
                $values['database'] = $dsn;
            }
            $options = &PEAR::getStaticProperty($class,'options');
            $options = $values;
        }
        $configuredDataObject = true;
        // setting requested debug level
        DB_DataObject::debugLevel(DO_DEBUG_LEVEL);
    }
}

/**
 * Computes application digest. Used to distinguish sessions from different
 * projects on same engine and server.
 *
 * @return string digest
 */
function getServerDigest()
{
    return sha1($_SERVER['SERVER_NAME'] . PROJECT_NAME);
}

/**
 * Separates bottom buttons from truly links.
 *
 * @global array links
 * @global array buttons
 */
function formatBottomLinks()
{
    global $bottomLinks, $bottomButtons;

    $bottomButtons = array();
    foreach ($bottomLinks as $key => $link) {
        if ($link['button']) {
            $bottomButtons[] = $link;
            unset($bottomLinks[$key]);
        }
    }
}

/**
 * Returns array which is mapping from role ID to role title; this mapping
 * contains all roles.
 *
 * @global string database URL
 * @return array mapping from role ID to its title
 */
function getRolesTitles()
{
    global $dsn;

    configurateDataObject($dsn);
    $role = DB_DataObject::factory('role');
    $allRoles = $role->fetchAll();
    $result = array();
    foreach ($allRoles as $curRole) {
        if (!isAdmin() && $curRole->admin) {
            continue;
        }
        if ($curRole->identifier != 'anonymous') {
            $result[$curRole->id] = $curRole->title;
        }
    }
    return $result;
}

/**
 * Obtains user ID by his login.
 *
 * @param string $login optional    user login; if omitted, current user login
 *                                  is taken
 * @return int user ID (or null if not found)
 */
function getUserIdByLogin($login = null)
{
    if (!$login) {
        $login = $_SESSION['login'];
    }
    $user =& DB_DataObject::factory('user');
    $user->login = $login;
    if ($user->find(true) <= 0) {
        return null;
    } else {
        return $user->id;
    }
}

/**
 * Marks a link in the system menu as bold.
 *
 * @param string $id            menu item ID
 * @param bool $value optional  value to set
 */
function setSystemMenuItemBold($id, $value = true)
{
    $systemMenu =& getSystemMenu();

    foreach ($systemMenu as $key => $link) {
        if ($link['id'] == $id) {
            $systemMenu[$key]['bold'] = $value;
        }
    }
}

/**
 * Removes from the system menu all the items which are assigned a given
 * permission.
 *
 * @param string $permId    the identifier of the permission
 */
function removeSystemMenuItemByPermission($permId) {
    $systemMenu =& getSystemMenu();

    foreach ($systemMenu as $key => $link) {
        if ($link['permId'] == $permId) {
            unset($systemMenu[$key]);
        }
    }
}

/**
 * Removes from the browser menu all the items which are assigned a given id.
 *
 * @param string $id    the id of the menu item
 */
function removeBrowserMenuItemById($id) {
    $browserMenu =& getBrowserMenu();

    foreach ($browserMenu as $key => $link) {
        if ($link['id'] == $id) {
            unset($browserMenu[$key]);
        }
    }
}

/**
 * Converts a boolean value to a string value using 'yes' or 'no' for true and
 * false (in localized form).
 *
 * @param bool $ex  value to convert
 */
function yesnoDescr($ex)
{
    if ($ex) {
        $res = getMessage('common.yes');
    } else {
        $res = getMessage('common.no');
    }
    return $res;
}

/**
 * Unescapes GPC for a given array (recursively).
 *
 * @param array $array  array which to unescape
 */
function unescapeGPC($array)
{
    $result = array();
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $result[$k] = unescapeGPC($v);
        } else {
            $result[$k] = stripslashes($v);
        }
    }
    return $result;
}

/**
 * Unescapes GPC for all arrays in which we are interested (currently GET and
 * POST).
 */
function unescapeGPCAll()
{
    if (get_magic_quotes_gpc() == 1) {
        $_POST = unescapeGPC($_POST);
        $_GET  = unescapeGPC($_GET);
    }
}

/**
 * Removes http:// or https:// from the beginning of a string, if exists.
 *
 * @param string $str   string from which to remove
 */
function stripHTTP($str)
{
    $result = $str;
    if (strpos($str, 'http://') !== false) {
        $result = substr($str, strlen('http://'));
    }
    if (strpos($str, 'https://') !== false) {
        $result = substr($str, strlen('https://'));
    }
    return $result;
}

/**
 * Builds an URL to some action or friendly URL. URL may be friendly or not
 * friendly; 'friendlyness' mode is controlled by <b>friendly</b> parameter:
 * if not null and known, URL will be friendly, else result will be ordinary
 * URL.
 *
 * @global string context path
 * @param string $action optional   action; ignored if URL should be friendly;
 * appended as "action=$action"
 * @param array $params optional    params to append to URL; used for two
 * purposes: 1) if URL is not friendly, params from here are appended to
 * result; 2) if URL is friendly, this array contains params for rewriting
 * (for example, if friendly='page', page identifier is taken as
 * $params['identifier'].
 * @param string $friendly optional if this is specified and known, URL will be
 * friendly; this parameter sets 'friendlyness type'; each such type has its own
 * parameters taken from <b>$params</b>:
 * <ul>
 * <li>page - URL for page will be built; page identifier is taken from
 * $param['identifier']</li>
 * <li>newsArchive - URL for news archive will be built</li>
 * <li>resources - URL for page with list of resources will be built</li>
 * <li>resource - URL for resource will be built; resource ID is taken from
 * $param['id']</li>
 * <li>category - URL for category will be built; category ID is taken from
 * $param['id']</li>
 * <li>commodity - URL for commodity will be built; commodity ID is taken from
 * $param['id']</li>
 * </ul>
 * @param bool $absolute optional   if true and URL is not friendly, context
 * path will be added to the beginning of URL
 * @param string $language          the language to override, if null, not
 * overriding
 * @return string URL built
 */
function buildUrl($action = null, $params = array(), $friendly = null,
        $absolute = false, $language = null) {
    global $contextPath;

    if ($language == null) {
        $language = getCurrentLanguage();
    }

    if ($params == null) {
        $params = array();
    }

    if ($contextPath == '/' || $contextPath == '') {
        $contextPrefix = '/';
    } else {
        $contextPrefix = $contextPath . '/';
    }

    if ($friendly == 'page') {
        $identifier = $params['identifier'];
        $result = RW_PREFIX . PAGE_PREFIX . $identifier . '.' . $language . RW_POSTFIX;
    } else if ($friendly == 'newsArchive') {
        $result = RW_PREFIX . NEWS_ARCHIVE_PREFIX . RW_POSTFIX;
    } else if ($friendly == 'resources') {
        $result = RW_PREFIX . RESOURCES_PREFIX . RW_POSTFIX;
    } else if ($friendly == 'resource') {
        $fileName = $params['fileName'];
        $result = RW_PREFIX . RESOURCE_PREFIX . $fileName;
    } else if ($friendly == 'category') {
        $id = $params['id'];
        $result = RW_PREFIX . CATEGORY_PREFIX . $id . RW_POSTFIX;
    } else if ($friendly == 'commodity') {
        $id = $params['id'];
        $result = RW_PREFIX . COMMODITY_PREFIX . $id . RW_POSTFIX;
    } else if ($friendly == 'action') {
        $result = RW_PREFIX . $action . RW_POSTFIX;
    } else {
        $result = SCRIPT_BASE;
        if ($action != null) {
            $params['action'] = $action;
        }
        if ($language != null) {
            $params['language'] = $language;
        }
        $first = true;
        foreach ($params as $key => $value) {
            $result .= (($first ? '?' : '&') . $key . '=' . urlencode($value));
            $first = false;
        }
        if ($absolute) {
            if ($contextPath == '/' || $contextPath == '') {
                $contextPrefix = '/';
            } else {
                $contextPrefix = $contextPath . '/';
            }
            $result = $contextPrefix . $result;
        }
    }
    return $result;
}

function rewriteUrl($url, $params = array(), $friendly = null,
        $absolute = false, $language = null) {
    global $contextPath;

    if ($language == null) {
        $language = getCurrentLanguage();
    }

    if ($params == null) {
        $params = array();
    }

    if ($contextPath == '/' || $contextPath == '') {
        $contextPrefix = '/';
    } else {
        $contextPrefix = $contextPath . '/';
    }


/*    if ($friendly == 'page') {
        $identifier = $params['identifier'];
        $result = RW_PREFIX . PAGE_PREFIX . $identifier . RW_POSTFIX;
    } else if ($friendly == 'newsArchive') {
        $result = RW_PREFIX . NEWS_ARCHIVE_PREFIX . RW_POSTFIX;
    } else if ($friendly == 'resources') {
        $result = RW_PREFIX . RESOURCES_PREFIX . RW_POSTFIX;
    } else if ($friendly == 'resource') {
        $id = $params['id'];
        $result = RW_PREFIX . RESOURCE_PREFIX . $id;
    } else if ($friendly == 'category') {
        $id = $params['id'];
        $result = RW_PREFIX . CATEGORY_PREFIX . $id . RW_POSTFIX;
    } else if ($friendly == 'commodity') {
        $id = $params['id'];
        $result = RW_PREFIX . COMMODITY_PREFIX . $id . RW_POSTFIX;
    } else {*/
/*    var_dump($url);
    var_dump($contextPrefix . RW_PREFIX . PAGE_PREFIX);
    var_dump(startsWith($url, $contextPrefix . RW_PREFIX . PAGE_PREFIX));*/
    if (startsWith($url, $contextPrefix . RW_PREFIX . PAGE_PREFIX)
            && endsWith($url, RW_POSTFIX)) {
        $identifier = substr($url, strlen($contextPrefix . RW_PREFIX . PAGE_PREFIX),
                strlen($url) - strlen($contextPrefix . RW_PREFIX . PAGE_PREFIX));
        $identifier = substr($identifier, 0, strlen($identifier) - strlen(RW_POSTFIX));
        $pos = strrpos($identifier, '.');
        if ($pos === false) {
            // no dot, no language
        } else {
            $identifier = substr($identifier, 0, $pos);
        }
        $result = $contextPrefix . RW_PREFIX . PAGE_PREFIX . $identifier . '.' . $language . RW_POSTFIX;
    } else {
        $result = getUrlBase($url);
        if ($language != null) {
            $params['language'] = $language;
        }
        $params = mergeArrays(getUrlParameters($url), $params);
        $first = true;
        foreach ($params as $key => $value) {
            $result .= (($first ? '?' : '&') . $key . '=' . urlencode($value));
            $first = false;
        }
        if ($absolute) {
            $result = $contextPrefix . $result;
        }
    }
    return $result;
}

/**
 * Builds non-friendly URL adding a parameter that causes filters to be cleared.
 *
 * @param string $action optional   action to use
 * @param array $params optional    mapping of parameter names to their values
 * @return URL built
 * @see buildUrl()
 */
function buildUrlClearingFilters($action = null, $params = array()) {
    $params['clearFilters'] = 'yes';
    return buildUrl($action, $params);
}

/**
 * Exports pager data to smarty instance.
 *
 * @param object $pager     pager object
 * @param object $smarty    smarty instance
 * @param array $data       array of items to be displayed by pager
 */
function exportPagerData(&$pager, &$smarty, &$data) {
    $smarty->assign('manyPages', $pager->numPages() > 1);
    $smarty->assign('data', $data);
    $smarty->assign('dataIsEmpty', $pager->numItems() == 0);
    $smarty->assign('links', $pager->getLinks());
}

/**
 * Exports sort dirs for columns defined by descriptor to smarty instance.
 *
 * @param string $gridName      grid name
 * @param object $smarty        smarty instance
 * @param object $descriptor    descriptor object
 */
function assignSortDirs($gridName, &$smarty, &$descriptor) {
    foreach ($descriptor->getGridFields() as $name) {
        $paramName = 'sortDir' . ucfirst($name);
        $smarty->assign($paramName, 'asc');
    }
    if ($_SESSION['grids'][$gridName]['sortDir'] == 'asc') {
        $obj = $descriptor->dbToObj($_SESSION['grids'][$gridName]['sortColon']);
        if ($obj) {
            $paramName = 'sortDir' . ucfirst($obj);
            $smarty->assign($paramName, 'desc');
        }
    }
}

/**
 * Exports filters state to smarty instance.
 *
 * @param object $smarty        smarty instance
 * @param string $gridName      name of grid
 */
function assignFilters(&$smarty, $gridName) {
    $smarty->assign('filters', $_SESSION['grids'][$gridName]['filters']);
}

/**
 * Issues a redirect and exits script.
 *
 * @param string $url   URL to which to redirect
 */
function redirect($url) {
    HTTP::redirect($url);
    exit;
}

/**
 * Returns array of all permissions existing in system.
 *
 * @return array permission objects ordered by their ID
 */
function &getAllPermissions() {
    $dao =& getDao('permission');
    $dao->orderBy('id');
    return $dao->fetchAll();
}

/**
 * Rebuilds array from ordinal to associative form; 'identifier' is taken from
 * element and used as key in new assoc array.
 *
 * @param array $array  array to process
 */
function rebuildArray($array) {
    $result = array();
    foreach ($array as $e) {
        $result[$e['identifier']] = $e;
    }

    return $result;
}

/**
 * Returns a layout by its identifier.
 *
 * @global array layouts
 * @param string $identifier    layout identifier
 * @return array layout
 */
function getLayout($identifier) {
    global $layouts;

    return $layouts[$identifier];
}

/**
 * Returns title of layout with a given identifier.
 *
 * @param string $identifier    layout identifier
 * @return string layout title
 */
function getLayoutTitle($identifier) {
    $layout = getLayout($identifier);
    return $layout['title'];
}

/**
 * Returns a menu by its identifier.
 *
 * @global array layouts
 * @param string $layoutIdentifier  layout identifier
 * @param string $menuIdentifier    menu identifier
 * @return array menu
 */
function getMenu($layoutIdentifier, $menuIdentifier) {
    global $layouts;

    return $layouts[$layoutIdentifier]['menus'][$menuIdentifier];
}

/**
 * Returns title of menu with a given identifier.
 *
 * @param string $layoutIdentifier  layout identifier
 * @param string $menuIdentifier    menu identifier
 * @return string menu title
 */
function getMenuTitle($layoutIdentifier, $menuIdentifier) {
    $menu = getMenu($layoutIdentifier, $menuIdentifier);
    return $menu ? $menu['title'] : '';
}

/**
 * Returns whether request has a parameter called 'cancel' (which means that
 * form has been cancelled).
 *
 * @return bool whether form was cancelled
 */
function isCancelled() {
    return isset($_REQUEST['cancel']);
}

/**
 * Returns whether request has a parameter called 'back' (which means that
 * button 'Back' was pressed in form).
 *
 * @return bool whether button 'Back' was pressed in form
 */
function isBackPressed() {
    return isset($_REQUEST['back']);
}

/**
 * Searches for object in array which has a given property equal to a given
 * value.
 *
 * @param array $daos       array of objects
 * @param string $property  name of a field in object
 * @param mixed $value      value to compare with field value
 * @return object|null dao or null if nothing found
 */
function findDaoByProperty($daos, $property, $value) {
    $result = null;
    foreach ($daos as $dao) {
        if ($dao->$property == $value) {
            $result = $dao;
            break;
        }
    }
    return $result;
}

/**
 * Returns a new (blank) dao object for a given table.
 *
 * @param string $table     table name
 * @return object blank dao
 */
function &getDao($table) {
    return DB_DataObject::factory($table);
}

/**
 * Returns an object from a given table obtained by a given ID.
 *
 * @param string $table table name
 * @param mixed $id     object ID
 * @return object obtained object
 */
function &staticGet($table, $id) {
    $dao =& getDao($table);
    return $dao->staticGet($id);
}

/**
 * Loads objects from DB respecting filters and sorting state.
 *
 * @param string $table             table name from which to load objects
 * @param object $descriptor        descriptor object
 * @param string $gridName optional if not empty, specifies name of grid
 * @param array $queryInfo optional specifies additional query info:
 * <ul>
 * <li>orderBy - expression (in SQL) by which to order; if empty, value from
 * session (previous sort value) will be used</li>
 * <li>select - array from which SELECT clause will be built; if not specified,
 * SELECT is not restricted</li>
 * <li>additionalSelect - array from which additional SELECT clause will be
 * built. If specified, it's added to usual SELECT. One special behavior:
 * this is added when constructing a 'counting' query too.</li>
 * <li>fields - if not empty, contains mapping from fields names to values
 * they must have on returned objects</li>
 * <li>where - where clause (or its part, at least)</li>
 * <li>limit - maximum number of objects to return</li>
 * <li>offset - index of first object to return</li>
 * </ul>
 * @return array assoc array with two values:
 * <ul>
 * <li>total - total number of objects in DB which satisfy to all conditions
 * except limit/offset restriction</li>
 * <li>rows - objects themselves</li>
 * </ul>
 */
function loadObjects($table, &$descriptor, $gridName = null, $queryInfo = array()) {
    $orderBy = $queryInfo['orderBy'];
    $select = $queryInfo['select'];
    $additionalSelect = $queryInfo['additionalSelect'];
    $fields = $queryInfo['fields'];
    $where = $queryInfo['where'];

    $dao = getDao($table);
    $dao->whereAdd();
    if (!empty($gridName) && $_SESSION['grids'][$gridName]['filters']) {
        foreach ($_SESSION['grids'][$gridName]['filters'] as $colon => $filter) {
            $objColon = $descriptor->dbToObj($colon);
            $trimmedFilter = $dao->escape(trim($filter));
            if ($trimmedFilter != '') {
                if ($descriptor->isSelectField($objColon) && $filter == -1) {
                    continue;
                } 
                if ($descriptor->isSelectField($objColon)) {
                    if ($descriptor->isSelectFieldTypeInt($objColon)) {
                        $curCondition = " $colon = $trimmedFilter ";
                    } else {
                        $curCondition = " $colon = '$trimmedFilter' ";
                    }
                } else {
                    $curCondition = "$colon LIKE '%$trimmedFilter%'";
                }
                $dao->whereAdd($curCondition);
            }
        }
    }

    if (is_array($fields)) {
        foreach ($fields as $field => $value) {
            if ($value === null || $value === '') {
                $dao->whereAdd("$field is null");
            } else {
                $dao->$field = $value;
            }
        }
    }

    if ($where !== null) {
        $dao->whereAdd('(' . $where . ')');
    }

    if (is_array($select)) {
        $dao->selectAdd();
        foreach ($select as $proj) {
            if ($descriptor->isObjField($proj)) {
                $proj = $descriptor->objToDb($proj);
            }
            $dao->selectAdd($proj);
        }
    }

    if (is_array($additionalSelect)) {
        foreach ($additionalSelect as $proj) {
            if ($descriptor->isObjField($proj)) {
                $proj = $descriptor->objToDb($proj);
            }
            $dao->selectAdd($proj);
        }
    }

    $total = null;
    if (isset($queryInfo['limit'])) {
        $copy = clone($dao);
        $dao->selectAdd();
        $dao->selectAdd('count(id) as _____c');
        if (is_array($additionalSelect)) {
            foreach ($additionalSelect as $proj) {
                if ($descriptor->isObjField($proj)) {
                    $proj = $descriptor->objToDb($proj);
                }
                $dao->selectAdd($proj);
            }
        }
        $dao->find(true);
        $total = $dao->_____c;
        $dao =& $copy;
    }

    if ($_SESSION['grids'][$gridName]['sortDir'] == 'desc') {
        $orderBySuffix = ' DESC';
    } else {
        $orderBySuffix = ' ASC';
    }
    if (!$orderBy) {
        if ($_SESSION['grids'][$gridName]['sortColon']) {
            $dao->orderBy($_SESSION['grids'][$gridName]['sortColon'].$orderBySuffix);
        }
    } else {
        $dao->orderBy($orderBy);
    }
    if (isset($queryInfo['limit'])) {
        $limit = $queryInfo['limit'];
        if (isset($queryInfo['offset'])) {
            $offset = $queryInfo['offset'];
            $dao->limit($offset, $limit);
        } else {
            $dao->limit($limit);
        }
    }

    $rows = $dao->fetchAll();
    if ($total === null) {
        $total = count($rows);
    }
    return array('total' => $total, 'rows' => $rows);
}

/**
 * Saves a return URL from GET for some category to session; if it does not
 * exist in GET, it's removed from session.
 *
 * @param string $category  category name
 */
function saveReturnUrlToSession($category) {
    $url = $_GET['returnUrl'];
    if ($url) {
        $_SESSION['returnUrl'][$category] = $url;
    } else {
        unset($_SESSION['returnUrl'][$category]);
    }
}

/**
 * Loads a return URL from session, removes it from there and returns.
 *
 * @param string $category  category name
 * @return return URL
 */
function loadReturnUrlFromSession($category) {
    $url = $_SESSION['returnUrl'][$category];
    unset($_SESSION['returnUrl'][$category]);
    return $url;
}

/**
 * Creates a query info that will instruct to obtain objects currently displayed
 * in pager or, if nothing is displayed, objects that would be displayed on
 * first page.
 *
 * @global int items per page
 * @return array query info
 * @see loadObjects()
 */
function buildDefaultQueryInfo() {
    global $perPage;

    if (isset($_REQUEST[PAGE_ID_VAR])) {
        $pageNumber = $_REQUEST[PAGE_ID_VAR];
    } else {
        $pageNumber = 1;
    }

    $limit = $perPage;
    $offset = ($pageNumber - 1) * $perPage;

    $queryInfo = array('limit' => $limit, 'offset' => $offset);

    return $queryInfo;
}

/**
 * Splits a full 'file name' (in UNIX style) to pair (dir, file).
 *
 * @param string $fullName  full file name
 * @return array 0 => dir, 1 => file
 */
function splitFullName($fullName) {
    $name = strrchr($fullName, '/');
    $name = substr($name, 1);
    $dir = substr($fullName, 0, strlen($fullName) - strlen($name));
    return array($dir, $name);
}

/**
 * Obtains a value from GET or session, then puts it to session and returns.
 *
 * @param string $name  parameter name
 * @return mixed value
 */
function fromGetOrSession($name) {
    $value = null;
    if (isset($_GET[$name])) {
        $value = $_GET[$name];
    } else if (isset($_SESSION[$name])) {
        $value = $_SESSION[$name];
    }
    $_SESSION[$name] = $value;
    return $value;
}

/**
 * Formats file size to human-friendly form (in megabytes, kilobytes and so on,
 * if needed).
 *
 * @param int $size     size to format
 * @param string $b     string that will be appended if size formatted is in
 * bytes
 * @param string $kb    string that will be appended if size formatted is in
 * kilobytes
 * @param string $mb    string that will be appended if size formatted is in
 * megabytes
 */
function smartFileSize($size, $b, $kb, $mb) {
    $k = 1024;
    $m = 1024 * 1024;
    $q = (float) $size / $m;
    if ($q >= 1) {
        return round($q) . ' ' . $mb;
    }
    $q = (float) $size / $k;
    if ($q >= 1) {
        return round($q) . ' ' . $kb;
    }
    return "$size $b";
}

/**
 * Returns the system menu. It's returned by reference.
 *
 * @global array system menu items
 * @return array reference to the system menu
 */
function &getSystemMenu() {
    global $systemMenu;

    return $systemMenu;
}

/**
 * Returns the browser menu. It's returned by reference.
 *
 * @global array browser menu items
 * @return array reference to the browser menu
 */
function &getBrowserMenu() {
    global $browserMenu;

    return $browserMenu;
}


/**
 * Returns all layouts.
 *
 * @global array layouts
 * @return array layouts
 */
function &getLayouts() {
    global $layouts;

    return $layouts;
}

/**
 * Merges two arrays. The result has keys for the union of keys in both arrays.
 * If only one array has a value for a key, it's taken. It both arrays have
 * values for a key, the value from the second array has precedence.
 *
 * @param array $initial    first array
 * @param array $delta      second array
 * @return array merged array
 */
function mergeArrays($initial, $delta) {
    $result = $initial;
    foreach ($delta as $key => $value) {
        $result[$key] = $value;
    }
    return $result;
}

/**
 * Returns true if a string starts with another string.
 *
 * @param string $str       string to check
 * @param string $prefix    prefix to check
 * @return bool true if starts with
 */
function startsWith($str, $prefix) {
    return (strpos($str, $prefix) === 0);
}

/**
 * Returns true if a string ends with another string.
 *
 * @param string $str       string to check
 * @param string $postfix   postfix to check
 * @return bool true if ends with
 */
function endsWith($str, $postfix) {
    if (strlen($postfix) > strlen($str)) {
        return false;
    }
    $prefix = substr($str, 0, strlen($str) - strlen($postfix));
    return ($prefix . $postfix) == $str;
}

/**
 * Returns URL base (everything but query string).
 *
 * @param string $url   the URL
 * @return string URL base
 */
function getUrlBase($url) {
    $pos = strpos($url, '?');
    if ($pos !== false) {
        list($base, $params) = explode('?', $url, 2);
    } else {
        $base = $url;
    }
    return $base;
}

/**
 * Returns URL query parameters as assoc array.
 *
 * @param string $url   the URL
 * @return array assoc array of query parameters
 */
function getUrlParameters($url) {
    $pos = strpos($url, '?');
    if ($pos !== false) {
        list($base, $params) = explode('?', $url, 2);
        $pairs = explode('&', $params);
        $result = array();
        foreach ($pairs as $pair) {
            list($k, $v) = explode('=', $pair, 2);
            $result[$k] = $v;
        }
        return $result;
    } else {
        return array();
    }
}

/**
 * Adds a calendar date element to form with some common configuration.
 *
 * @param object $form  the form
 * @param string $name  element name
 * @param string $title element title
 */
function addCommonCalendarDateElement(&$form, $name, $title) {
    $form->addCalendarDateElement($name, $title, null,
            array('phpDatePattern' => DATE_PATTERN, 
                'calendarDatePattern' => CALENDAR_DATE_PATTERN,
                'imgSrc' => 'images/calendar.gif'));
}

/**
 * Returns a list which contains three members: all, no, yes. It's intended to
 * be used as options in a SELECT. Messages are localized.
 */
function getAllYesNoList() {
    $list = array();
    $list[-1] = getMessage('common.all');
    $list[0] = getMessage('common.no');
    $list[1] = getMessage('common.yes');
    return $list;
}

/**
 * Returns a default base HREF.
 *
 * @global string context path
 * @return base HREF
 */
function defaultBaseHref() {
    global $contextPath;

    $cp = $contextPath;
    if ($cp == '/') {
        $cp = '';
    }

    $url = "http://" . $_SERVER['HTTP_HOST'] . $cp . "/";
    return $url;
}

/**
 * Unescapes BLOB value selected using SELECT. This is currently needed for
 * Postgres only.
 *
 * @global string DSN
 * @param string $blob  the BLOB value
 * @return unescaped BLOB value
 */
function unescapeBlobFromSelect($blob) {
    global $dsn;

    if (startsWith($dsn, 'pgsql://')) {
        $blob = pg_unescape_bytea($blob);
    }

    return $blob;
}

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