<?php

define("HOME_REGEX", '/^.{0,2}index\.php.{0,2}$/i');

class PHPWS_Breadcrumb
{
    function allowView()
    {
        if(!isset($GLOBALS['BC_allow_view'])) {
            PHPWS_Breadcrumb::initSession();
        }
        $allow_view = unserialize($GLOBALS['BC_allow_view']);
        return in_array($GLOBALS['core']->current_mod, $allow_view);
    }
    
    function getCrumbs($withContainer = TRUE)
    {
        // Remove menu position from query string
        $query = PHPWS_Breadcrumb::cleanQueryString($_SERVER['QUERY_STRING']);

        // Get active menus to find the most relevant way to build the breadcrumb
        $sql = "SELECT menu_id FROM {$GLOBALS['core']->tbl_prefix}mod_menuman_menus WHERE menu_active = 1";
        $activemenus = $GLOBALS['core']->getAll($sql);

        // Select the current page from the menu items table
        $sql = "SELECT menu_item_pid,menu_item_title,menu_item_url,menu_id FROM {$GLOBALS['core']->tbl_prefix}mod_menuman_items WHERE menu_item_url LIKE '$query'";
        foreach($activemenus as $row) {
            $sql .= ' AND menu_id = ' . $row['menu_id'];
        }
        
        // Find the leaf-to-root path from our item in the menu tree
        $rows = array();
        $row = $GLOBALS['core']->getRow($sql);
        if(empty($row)) {
            $sql = "SELECT menu_item_pid,menu_item_title,menu_item_url,menu_id FROM {$GLOBALS['core']->tbl_prefix}mod_menuman_items WHERE menu_item_url LIKE '$query'";
            $row = $GLOBALS['core']->getRow($sql);
        }
        while(!empty($row)) {
            $rows[] = $row;
            $oldrow = $row;
            $sql = "select menu_item_pid, menu_item_title, menu_item_url,menu_id FROM {$GLOBALS['core']->tbl_prefix}mod_menuman_items " .
                   "WHERE menu_item_id={$row['menu_item_pid']} AND menu_id={$row['menu_id']}";
            $row = $GLOBALS['core']->getRow($sql);
            if($row == $oldrow)
                break;
        }
        
        // Build the bread crumbs
        $crumbs = '';
        $home = FALSE;
        for($i = sizeof($rows); $i > 0; $i--) {
            $row = $rows[$i-1];
            if($i < sizeof($rows)) 
                $crumbs .= ' '.PHPWS_Breadcrumb::getSeparator().' ';
            if($i > 1) {
                $crumbs .= PHPWS_Breadcrumb::makeCrumb($row['menu_item_url'], $row['menu_item_title']);
            } else {
                $crumbs .= PHPWS_Breadcrumb::makeCurrentCrumb($row['menu_item_title']);
            }
            if(preg_match(HOME_REGEX, $row['menu_item_url']))
                $home = TRUE;
        }
        if(!$home) {
            if(empty($crumbs)) {
                $crumbs .= ' ' . PHPWS_Breadcrumb::makeHomeCrumb(TRUE);
            } else {
                $crumbs = ' ' . PHPWS_Breadcrumb::makeHomeCrumb() .
                          ' ' . PHPWS_Breadcrumb::getSeparator() . ' ' . $crumbs;
            }
        }
        $crumbs = PHPWS_Breadcrumb::showInitialSeparator() . $crumbs;
        if($withContainer) 
            return PHPWS_Template::processTemplate(array('BREADCRUMBS' => $crumbs),
                                                   "breadcrumb", "container.tpl");
        return $crumbs;
    }

    function cleanQueryString($string)
    {
        $query = split('&amp;MMN', PHPWS_Text::parseOutput($string));
        if(empty($query) || empty($query[0]) || preg_match(HOME_REGEX, $query[0])) {
            return 'index.php';
        } else {
            return '%' . $query[0] . '%';
        }
    }

    function showInitialSeparator()
    {
        if(!isset($GLOBALS['BC_initial_separator'])) {
            PHPWS_Breadcrumb::initSession();
        }
        return $GLOBALS['BC_initial_separator'] ? PHPWS_Breadcrumb::getSeparator() . ' ' : ' ';
    }

    function getSeparator()
    {
        $tags['SEPARATOR'] = PHPWS_Breadcrumb::getSeparatorChar();
        return PHPWS_Template::processTemplate($tags, "breadcrumb", "separator.tpl");
    }

    function getSeparatorChar()
    {
        if(!isset($GLOBALS['BC_separator_char'])) {
            PHPWS_Breadcrumb::initSession();
        }
        return $GLOBALS['BC_separator_char'];
    }

    function makeHomeCrumb($current = FALSE)
    {
        if(!isset($GLOBALS['BC_home_text'])) {
            PHPWS_Breadcrumb::initSession();
        }
        if($current) {
            return PHPWS_Breadcrumb::makeCurrentCrumb($GLOBALS['BC_home_text']);
        } else {
            return PHPWS_Breadcrumb::makeCrumb('index.php', $GLOBALS['BC_home_text']);
        }
    }

    function makeCrumb($href,$text)
    {
        $tags['HREF'] = $href;
        $tags['TEXT'] = $text;
        return PHPWS_Template::processTemplate($tags, "breadcrumb", "crumb.tpl");
    }

    function makeCurrentCrumb($text)
    {
        $tags['TEXT'] = $text;
        return PHPWS_Template::processTemplate($tags, "breadcrumb", "current_crumb.tpl");
    }

    function editSettings()
    {
        PHPWS_Breadcrumb::initSession();

        require_once(PHPWS_SOURCE_DIR . 'core/EZform.php');

        $form = new EZForm('breadcrumb_settings_edit');
        $form->add('module',   'hidden', 'breadcrumb');
        $form->add('breadact', 'hidden', 'save_settings');
        
        $form->add('hometext',  'text', $GLOBALS['BC_home_text']);
        $form->add('separator', 'text', $GLOBALS['BC_separator_char']);
        $form->add('initial_separator', 'checkbox');
        $form->setMatch('initial_separator', $GLOBALS['BC_initial_separator'] == 1);
        $form->add('save', 'submit', 'Save Settings');
        $tags = $form->getTemplate();
        
        $tags['ALLOW_VIEW']       = PHPWS_Form::formMultipleSelect('allow_view',
                                                                   PHPWS_Breadcrumb::getModulesAllowed(),
                                                                   unserialize($GLOBALS['BC_allow_view']),
                                                                   1, NULL, 5);
        $tags['HOMETEXT_LABEL']   = $_SESSION['translate']->it('Home Link Text');
        $tags['SEPARATOR_LABEL']  = $_SESSION['translate']->it('Separator');
        $tags['INITIAL_SEPARATOR_LABEL'] = $_SESSION['translate']->it('Display a separator character before BCN?');
        return PHPWS_Template::processTemplate($tags, 'breadcrumb', 'edit.tpl');
    }

    function initSession()
    {
        $row = $GLOBALS['core']->getRow("SELECT * FROM {$GLOBALS['core']->tbl_prefix}mod_breadcrumb_settings");
        $GLOBALS['BC_separator_char']    = $row['separator'];
        $GLOBALS['BC_initial_separator'] = $row['initial_separator'];
        $GLOBALS['BC_home_text']         = $row['hometext'];
        $GLOBALS['BC_allow_view']        = $row['allow_view'];
    }

    function saveSettings()
    {
        $GLOBALS['BC_home_text']         = $sql['hometext']          = htmlentities($_REQUEST['hometext']);
        $GLOBALS['BC_separator_char']    = $sql['separator']         = htmlentities($_REQUEST['separator']);
        $GLOBALS['BC_initial_separator'] = $sql['initial_separator'] = (isset($_REQUEST['initial_separator']) ? 1 : 0);
        $GLOBALS['BC_allow_view']        = $sql['allow_view']        = serialize($_REQUEST['allow_view']);
        
        $GLOBALS['core']->sqlUpdate($sql, 'mod_breadcrumb_settings');
    }

    function getModulesAllowed()
    {
        $modulesAllowed = $GLOBALS['core']->listModules();
    
        $text = $_SESSION['translate']->it("Select Modules Allowed");
        $options = array($text, "----------------------------------------------");
        array_push($options, "home");
        $modulesAllowed = array_merge($options, $modulesAllowed);

        return $modulesAllowed;
    }
}

?>
