<?php

class cat {

    var $cat;
    var $cat_name;
    var $module;
    var $data;
    var $templ = 'index.htm';
    var $xml = 'index.xml';
    var $path;
    var $path_name;
    var $breadcrumbs = array();
    var $access;
    var $meta_keywords = array();
    var $meta_description = '';
    var $add_headers = array();
    
    function __construct() {
        global $core_db, $db;
        
        $this->cat = addslashes($_POST['cat']);
        
        if ( !$this->cat ) 
        $this->cat = addslashes($_GET['cat']);
        if ( !$this->cat ) $this->cat = 'index';
        $cat_obj = new cobject( __REAL_CAT_OBJ_ );
        $db2 = $core_db->q( $cat_obj->getSelect( ' AND `cat_id` = "' . $this->cat . '"' ) );
        if ( $db2->r() ) {
        	$cat_obj->lRow( $db2 );	
        	$this->module = $cat_obj->get('module');
        	$this->cat_name = $cat_obj->get('cat_name');
			$this->data = $this->dataParse(htmlspecialchars_decode($cat_obj->get('data')));
			if (!$cat_obj->get('xml') ) {
				$this->xml = $this->searchXml( $cat_obj->get('parent_cat') );
			} else {
				$this->xml = $cat_obj->get('xml');	
			}

			$this->path = $this->getPath();
			if ( $cat_obj->get('meta_keywords') ) {
				$this->addKeywords( $cat_obj->get('meta_keywords') );
			}
			
			if ( $cat_obj->get('meta_description') ) {
				$this->setDescription( $cat_obj->get('meta_description') );
			}
			
			if ( $cat_obj->get('access_group') )  {
				$this->access = explode( ",", $cat_obj->get('access_group') );
            }
	        if (!$this->module) {
	        	$this->module =	'line_menu.php';
	        	$this->data = array('root' => $this->cat );
        	}
        	
        } else {
            header("HTTP/1.1 404 Not Found");
            
            if (defined('_ADMINKA_')) {
                header("Location: "._SITE_ROOT_);
            } else {
                header("Location: "._SITE_ROOT_."404");
            }
            die();
			/*
        	$this->module = 'loginbox.php';
        	$this->cat_name = 'Авторизация';
			$this->path = $this->getPath();
			$this->xml = 'login.xml';	
			*/

        }
        if (!$this->xml) {
        	cdie('XML не определена');	
        }
    }
    
    function checkAccess() {
    	global $auth;
    	if ( !$this->access ) return true;
    	if ( $auth->user_id == _ROOT_USER_ID )  return true;
    	$acc = false;
    	foreach( $auth->groups as $v ) {
    		if (in_array( $v, $this->access ) ) {
    			$acc = true;	
    		}
    	}
    	
    	return $acc;
    	
    }
    
    function dataParse( $data = "" ) {
		
		preg_match_all( '/\$(.*?)=(.*?);/', $data, $r  );
		foreach( $r[1] as $k => $var ) {
			$var = trim($var);
			$ret[$var] = trim($r[2][$k]);	
		}
		return $ret;
    }
    
    function searchXml( $cat ) {
        global $core_db;
        $cat_obj = new cobject( __REAL_CAT_OBJ_ );
		$db2 = $core_db->q( $cat_obj->getSelect( ' AND `cat_id` = "' . $cat . '" ' ) );
		$db2->r();

		if (!$db2->f('xml') ) {
			return $this->searchXml( $db2->f('parent_cat') );
        } else {
			return $db2->f('xml');	
		}
		
    }
    
    function render() {
       /* load module */
       global $R;
       if  ( !$this->checkAccess() ) {
        	$this->module = 'loginbox.php';
        	$this->cat_name = 'Авторизация';
			$this->path = $this->getPath();
			$this->xml = 'login.xml';	
       }
       	   
       if ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) { 
            // Не выполняем всю движку, только модуль и сразу возвращаемся
            if (substr($this->module,-4) == '.php' ) {
            	$module = substr($this->module,0,-4);
            } 
            require_once( _BASE_DIR . 'modules/' . $module .'.php' );
        	$body_module = new $module( $this->data );
        	if ( $body_module->_sys_no_load ) return;
        	return $R->clear($body_module->render( 'body', true));
       }

       $this->parseXml();

	   $this->setModule( 'body', $this->module, $this->data );


       if ( $this->delayed_modules ) {
           foreach( $this->delayed_modules as $arr ) {
        	   $this->setModule( $arr['tpl'], $arr['module'], $arr['data'] );
           }
       }
	   $this->out = $R->set('meta_keywords', implode(', ', $this->meta_keywords), $this->out );
	   $this->out = $R->set('meta_description', $this->meta_description, $this->out );
       
       if ($this->cat != 'index' ) {
              $this->out = $R->set('breadcrumbs', $this->r_breadcrumbs(), $this->out );
       }
	   /*
	   $this->out = $R->set('auto_title', implode(" / ", $this->path_name), $this->out );
	   */
       
	   $this->out = $R->set('auto_title',  $this->path_name[0], $this->out );
       if ( defined('NOINDEX') ) {
            $this->addHeaders('<meta name="robots" content="noindex,nofollow">');
       }
       
	   $this->out = $R->set('add_headers',  implode("\n", $this->add_headers), $this->out );
       
	   return $R->clear( $this->out );
    }
    
     function r_breadcrumbs() {
        global $R;
        
        $tpl = $R->getTpl( 'breadcrumbs.htm', 'body' );
        $tplr = $R->getTpl( 'breadcrumbs.htm', 'row' );
        $tpls = $R->getTpl( 'breadcrumbs.htm', 'sep' );
        $tpll = $R->getTpl( 'breadcrumbs.htm', 'last_row' );
        $first_yes = false;
        if (!$this->breadcrumbs ) {
           foreach( $this->path as $k => $v ) {
             if ($v != 'index') {
                $tit = $this->path_name[$k];   
                $this->breadcrumbs[$v] =  $tit;
             } else {
                $tit = $this->path_name[$k];   
                $this->breadcrumbs[''] =  $tit;
                $first_yes = true;
             }
           }
           $this->breadcrumbs = array_reverse( $this->breadcrumbs, true );
        }   
                
        $cnt = @count( $this->breadcrumbs );

        if (!$first_yes ) {
            $tta[] = $R->set('url', '', $R->set('title', end($this->path_name), $tplr) );
        }
        
        
        
        foreach( $this->breadcrumbs as $k => $v ) {
            $i++;
            if ( $i == $cnt ) {
                $tplr = $tpll;
            }
            
            if ($i == ($cnt-1) ) {
	            $tpl = $R->set('parent_url', $k, $tpl );
	            $tpl = $R->set('parent_title', $v, $tpl);
            }
            
            $tt = $R->set('url', $k, $tplr );
            $tt = $R->set('title', $v, $tt);
            
            $tta[] = $tt;
        }

        if ($cnt == 1 ) {
	            $tpl = $R->set('parent_url', '/', $tpl );
	            $tpl = $R->set('parent_title', 'Главная', $tpl);
        }


        $tpl = $R->set('rows', implode( $tpls, $tta ), $tpl );

        return $R->clear( $tpl );
    }
    
    
    function setModule( $templ, $module, $data = array() ) {
    	global $R, $statistica;

    	if ( !$module ) return;

        if (substr($module,-4) == '.php' ) {
        	$module = substr($module,0,-4);
        } 
        
        require_once( _BASE_DIR . 'modules/' . $module .'.php' );

        $tmptime = microtime( true );
    	$body_module = new $module( $data );

    	if ( $body_module->_sys_no_load ) return;

    	if ($templ == 'body') {
            global $blade;
            $blade->share('module', $body_module);
        }

    	$this->out = $R->set( $templ, $body_module->render( $templ ), $this->out );
        $statistica['modules'][$module] = microtime( true ) - $tmptime;
    }
    
    function parseXml($exec_modules = true) {
    	global $R;
    	$xml = simplexml_load_file( _BASE_DIR . 'xml/'.$this->xml  );

    	$xml = (Array)$xml;
    	$this->templ = $xml['@attributes']['filename'];
    	if ($_GET['frame_mode'] && $xml['@attributes']['frame_filename']) {
    		$this->templ = $xml['@attributes']['frame_filename'];		
    	}
		
		
    	if ( !$this->templ ) cdie( 'Не указан файл шаблона в xml' );
    	unset($xml['@attributes']);

        $this->out = $R->getTpl( $this->templ );

    	foreach( $xml as $templ_set => $module_data ) {
	    	if ( is_object( $module_data  )) {
	    		
	    	foreach( $module_data as $module => $attrs ) {
			    $delay = false;
				$attrs = (Array)$attrs;
				$data = Array();
				if (isset( $attrs['@attributes'] ) ) {
					foreach( $attrs['@attributes'] as $k => $v ) {
						$data[$k] = $v;
                        if ($k == 'delay' && $v == 'true' ) {
                            $delay = true;   
                        }
					}	    
				}
                if ($delay ) {
                    $this->delayed_modules[] = array('tpl' => $templ_set, 'module' => $module, 'data' => $data );
                } else {
    	 		    $this->setModule( $templ_set, $module, $data );
                }
	    	}
    	}
    	}
    	
    }
	
	function getPath() {
		global $core_db;
        $cat_obj = new cobject( __REAL_CAT_OBJ_ );
        $db2 = $core_db->q( $cat_obj->getSelect( ' AND `cat_id` = "' . $this->cat . '"' ) );
		$db2->r();
		$parent_cat = $db2->f('parent_cat');
		if ( !$db2->f('_sys_unvisible') ) {
    		$path[] = $this->cat;
			$this->path_name[] = $db2->f('cat_name');
        }


		while( $parent_cat ) {
			$i++;
	        $db2 = $core_db->q( $cat_obj->getSelect( ' AND `cat_id` = "' . $parent_cat . '"' ) );
			$db2->r();
	
			if ( !$db2->f('_sys_unvisible') ) {
    			$path[] = $parent_cat;
				$this->path_name[] = $db2->f('cat_name');
            }
			
			$parent_cat = $db2->f('parent_cat');
   		    if ($i > 10 ) cdie('Больше 10 вложений в пути.');
		}	
        
		return $path;
	}
	
	function addKeywords($words) {
		if ($words) {
			$this->meta_keywords[] = $words;
		}
	}
		
	function addTitle($words) {
		global $url_arr;
		if ($words) {
			array_unshift( $this->path_name, $words );
			array_unshift( $this->path, implode('/', $url_arr ) );
			return true;
		}
		return false;
	}
    function addCurTitle($words) {
		if ($words) {
			$this->path_name[0] .= ' ' .trim( $words ) ;
			return true;
		}
		return false;
    }

	function setKeywords($words) {
		if ($words) {
			$this->meta_keywords = explode(',', $words );
			return true;
		}
		return false;
	}

	function setDescription($words) {
		if ($words) {
			$this->meta_description = $words;
			return true;
		}
		return false;
	}
    
    function setPath($path) {
		if ($path) {
			$this->breadcrumbs = $path;
			return true;
		}
		return false;
	}


    function addPath($url, $title) {
		if ( $url || $title ) {
			$this->breadcrumbs[$url] = $title;
			return true;
		}
		return false;
	}


    function addHeaders( $title ) {
        if (!in_array($title,  $this->add_headers ) ) {
            $this->add_headers[] = $title;
        }
    }
}    
    
?>