<?php

if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');


class flashgal
{
  var $user_groups = array();
//  var $modules = array();
  var $module = null;
  var $blocks = array();
  var $pos = 'begin';

  function flashgal($catid = null, $home = null, $permalinkcat = null)
  {
  
    $this->get_user_groups();
    $this->get_modules($catid, $home);
    $this->process_modules($catid, $home, $permalinkcat);
  }

  /* Retrieve user groups  */
  function get_user_groups()
  {
    global $user;

    $query = 'SELECT group_id FROM ' . USER_GROUP_TABLE . ' WHERE user_id = ' . $user['id'] . ';';
    $result = pwg_query($query);
    while ($row = mysql_fetch_assoc($result))
    {
      array_push($this->user_groups, $row['group_id']);
    }
  }

  /* Retrieve module */
  function get_module()
  {
		$module = $this->module;  
		return $module;
  }
  
  
  /* Retrieve modules from table */
  function get_modules($catid = null, $home = null)
  {

    global $page, $user;
	$module_found = false;

	
    $query = '
SELECT *
FROM ' . FLASHGAL_TABLE . '
WHERE users LIKE "%' . $user['status'] . '%"
';

// FAire un test par rapport aux variables $catid et $home
/*
    $script = script_basename();
    if ($script == 'index')
    {
      $query .= isset($page['category']) ?
        'AND on_cats = "true"' :
        'AND on_home = "true"' ;
    }
*/
if ($home)
	$query .= 'AND on_home = "true"' ;
elseif ($catid)
	$query .= 'AND on_cats = "true"' ;

    $query .= '
	ORDER BY pos ASC;';

    $result = pwg_query($query);
    while ($row = mysql_fetch_assoc($result))
    {
		// seulement si aucun module est trouvé.
		if( !$module_found)
		{
			// Besoin de positionner le module par rapport au 'Mainblock'
		    if ($row['type'] == 'MainBlock')
		    {
		    	$this->pos = 'end';
		    	continue;
		    }
		
			// categories actives pour le module
			$row['cats'] = (!empty($row['cats']) ? unserialize($row['cats']) : false);
/*
			if( (empty($page['category']) and $row['on_home'] = "true") 	// Home
				|| ( (isset($page['category']))	and $row['on_cats'] = "true" and (in_array($page['category']['id'], $row['cats'])) )	// category and in module conf
			  )
*/			
			if ( ($home and $row['on_home'] = "true") 	// Home
				|| ( $catid and $row['on_cats'] = "true" and (in_array($catid, $row['cats'])) )	// category and in module conf
			   )
			{
				$this->module = $row;
				// seul le premier correspondant est pris en compte
//				break;
				$module_found = true;
			}
		}
	}
}

  /* Process modules */
  function process_modules($catid = null, $home = null, $permalinkcat = null)
  {
//    foreach ($this->modules as $module)
	if ($this->module != null)
    {
		$module = $this->module;
	    if ($module['type'] == 'MainBlock')
	    {
	    	$this->pos = 'end';
	    	return;
	    }

		if (!empty($module['groups']))
		{
    		$authorized_groups = explode(',', $module['groups']);
    		if (array_intersect($this->user_groups, $authorized_groups) == array()) return;
    	}

    	$datas = (!empty($module['datas']) ? unserialize($module['datas']) : false);
		$block = array();


      $block['ID'] = $module['id'];
      if ($module['show_title'] == 'true')
      {
        $block['TITLE'] = trigger_event('render_flashgal_name', $module['name']);
      }
      if (is_admin())
      {
        $block['U_EDIT'] = PHPWG_ROOT_PATH.'admin.php?page=plugin&amp;section='.FLASHGAL_DIR.'%2Fadmin%2Fadd_module.php&amp;type='.$module['type'].'&amp;edit='.$module['id'];
      }
	  
      $block['TEMPLATE'] = $this->get_template($module['type'].'.tpl', $module['type']);
	  $block['TEMPLATE'] = realpath($block['TEMPLATE']);
	  
	  include(FLASHGAL_PATH . 'modules/' . $module['type']. '/module.inc.php');
	  
	  $block['FLASHNAME'] = FLASHGAL_PATH . 'modules/' . $module['type']. '/'.$module_data['FlashName'];	
	  $block['FLASHVARXML'] = $module_data['FlashvarXML'];

	  set_make_full_url();
//	  $catid = empty($page['category']['permalink']) ? $page['category']['id'] : $page['category']['permalink'];
//	  echo "page['category']['id']=".$catid;
//	  $block['XMLFEED'] = embellish_url(get_root_url().FLASHGAL_PATH.'generate-xml.php?/'.(isset($page['category']) ? 'category'.(isset($catid) ? $catid : '') : 'categories'));
	
//	  $block['XMLFEED'] = embellish_url(get_root_url().FLASHGAL_PATH.'generate-xml.php%3F/'.(isset($page['category']) ? 'category'.(isset($catid) ? $catid : '') : 'categories'));
	  $block['XMLFEED'] = embellish_url(get_root_url().FLASHGAL_PATH.'generate-xml.php?/'.(isset($permalinkcat) ? 'category/'.$permalinkcat : (isset($catid) ? 'category/' . $catid  : 'categories' )));
//	  $block['XMLFEED'] = embellish_url(FLASHGAL_PATH.'generate-xml.php?/'.(isset($permalinkcat) ? 'category/'.$permalinkcat : (isset($catid) ? 'category/' . $catid  : 'categories' )));


	if (isset($module_data['GET_Mode']) && $module_data['GET_Mode'])
		$block['XMLFEED'] = embellish_url(get_root_url().FLASHGAL_PATH.'generate-xml.php?'
							.(isset($permalinkcat) ? 'permalink='.$permalinkcat : (isset($catid) ? 'catid=' . $catid  : 'home' )));


	  unset_make_full_url();

	  $block['HEIGHT']= $module['height'];
	  $block['TRANSPARENT'] = ($module['transparent'] == 'true' ? true : false);
	  $block['FULLSCREEN'] = $module['fullscreen'];
	  $block['BGCOLOR'] = $module['bgcolor'];

	  if ((include(FLASHGAL_PATH . 'modules/' . $module['type'] . '/main.inc.php')) === false) return;
	  
	  $this->set_tpl_block($block, $module);

	}
  }

  /* Set template blocks  */
	function set_tpl_block($block, $module)
	{
	// TIICO : A supprimer car id_line est toujours vide, pas d'utilite de cette partie par rapport a PWG Stuff
	if (!empty($module['id_line']))
    {
      $block['id_line'] = $module['id_line'];
      $block['given_width'] = '';

      if (!empty($this->blocks[$this->pos]))
      {
        $last = end($this->blocks[$this->pos]);
        $key = key($this->blocks[$this->pos]);
        $penul = prev($this->blocks[$this->pos]);

        if (isset($last['id_line']) and $last['id_line'] == $module['id_line'])
        {
          if (isset($penul['id_line']) and $penul['id_line'] == $module['id_line'])
          {
            $i = 3;
            !$block['given_width'] or $i--;
            !$last['given_width'] or $i--;
            !$penul['given_width'] or $i--;

            !$i or $default_width = intval((100 - $block['given_width'] - $last['given_width'] - $penul['given_width']) / $i);

            $penul['WIDTH'] = $penul['given_width'] ? $penul['given_width'] : $default_width;
            $block['WIDTH'] = $block['given_width'] ? $block['given_width'] : $default_width;

            $block['CLASS'] = 'right_block';
            $block['new_line'] = false;
            $block['end_line'] = false;
            $last['end_line'] = true;
            $this->blocks[$this->pos][$key-1] = $penul;
            $this->blocks[$this->pos][$key] = $block;
            $this->blocks[$this->pos][] = $last;
            return;
          }
          else
          {
            if (empty($block['given_width']) and empty($last['given_width']))
            {
              $last['WIDTH'] = 50;
            }
            elseif ($block['given_width']>0)
            {
              $last['WIDTH'] = 100 - $block['given_width'];
            }
            else
            {
              $last['WIDTH'] = $last['given_width'];
            }
            $block['CLASS'] = 'middle_block';
            $last['CLASS'] = 'left_block';
            $block['new_line'] = false;
            $block['end_line'] = true;
            $last['end_line'] = false;
            $this->blocks[$this->pos][$key] = $last;
            $this->blocks[$this->pos][] = $block;
            return;
          }
        }
      }
    }

    $block['new_line'] = true;
    $block['end_line'] = true;
    $block['CLASS'] = 'middle_block';
  	$this->blocks[$this->pos][] = $block;
	}
  
  /* Return template for user template/theme */
  function get_template($file, $modulename = null) {
    global $user, $template;
	
	if (isset($modulename))
	{
		$dir = FLASHGAL_PATH . 'modules/'.$modulename .'/';
		return $dir.$file;
	}
	else
	{
		$dir = FLASHGAL_PATH . 'themes/';
		$themes_file = FLASHGAL_PATH.
						$user['theme'].'/'.
						$file;
  
		if (file_exists($themes_file))
		{
			return $themes_file;
		}
		else
		{
		return $dir.$file;
		}
	}
  }

}

?>