<?
////////////////////////////////////////////////////////////////////////////
//
//	Business & Control 2004-2008.
//
//	osztaly neve: class_content.php
//  celja: CMS kezel osztly
//	osztlyvltozk:
//
////////////////////////////////////////////////////////////////////////////


class content extends entitlement{

	var $version='2.2';
	var $limit; // kiolvasand ttelek szma
	var $stripHTMLtag;  // lemen contentbl HTML tagok ki
	var $deafult_content_type=array('page','user','product','newsletter');
	var $thumb=array(width=>100,height=>100);  // ezt lehet feluliratni projektenket EXT_IMG

	var $split=0; 				// lptet: hny ttel per oldal
	var $range=3; 				// lptet: hny szomszdos oldal ltsszon a lptetben

	var $global_types=array(
		'CONTENT_PAGE' 			=> 'page',
		'CONTENT_NEWSLETTER' 	=> 'newsletter',
		'CONTENT_EMAIL' 		=> 'email',
		'CONTENT_USERS' 		=> 'user',
		'WEBSHOP' 				=> 'product',
	);
	var $check_entitlement=0; // ne vegye figyelembe a jogozast
	var $content_type_chain; // array, az elso content type list chain ertekei: user, menu, product kell-e a tipusnak?

	var $lang_id;	// kovetkezo verziba atteres ezzel

//////////////////////////////////////////////////
//												//
//												//
//       			Init	  					//
//												//
//												//
//////////////////////////////////////////////////



function content(){

	global $auth,$SITEGLOBALS;

	if($SITEGLOBALS[CONTENT_MODERATE]){
		$this->moderate=1;
	}

	if(sql_check_field('content','lang')){
		$this->lang_id=$auth->getLangId($_COOKIE['language']?$_COOKIE['language']:$SITEGLOBALS['LANGUAGE']);
		$this->sql_lang=" and lang=$this->lang_id ";
	}

	// ha nem admin, akkor jog ellenorzes megy content_type_id-ra
	if($auth->user_type_id>1){
		$this->check_entitlement=1;
		// es hogy ki vette fel, egymast ne lassak
		if($SITEGLOBALS[DISABLE_OTHER_CONTENT]) $this->create_user_id=$auth->uid;
	}

	$this->user_id=$auth->uid;

}
function initContentTypeFields(){

	$lang=new translator($_COOKIE[language]);

	$fields=array(
		'title'=>$lang->getSingleTranslation('TEXT_TITLE'),
		'blurb'=>$lang->getSingleTranslation('LABEL_BLURB'),
		'img_ext'=>$lang->getSingleTranslation('LABEL_ICON'),
		'date_expire'=>$lang->getSingleTranslation('LABEL_DATE_EXPIRE'),
		'code'=>$lang->getSingleTranslation('TEXT_CODE'),
		'source_url'=>$lang->getSingleTranslation('LABEL_URL')
	);

	//echo "<pre>";print_r($fields);

	return $fields;
}

function makePages($items,$o) {
	$pages=ceil($items/($this->split?$this->split:1));
	if(!$pages) return;

	$sight_min=$o-$this->range; if($sight_min<0) $sight_min=0;
	$sight_max=$o+$this->range; if($sight_max>=$pages) $sight_max=$pages-1;

	for($i=$sight_min; $i<=$sight_max; $i++) $sight[$i].=$i+1;

	$this->pages=array(items=>$items, pages=>$pages, sight=>$sight, act=>$o);
	//print'<pre>';print_r($this->pages);print'</pre>';
}

//////////////////////////////////////////////////
//												//
//												//
//       			MODERALAS 					//
//												//
//												//
//////////////////////////////////////////////////


function getContentNotModerate(){

	global $dbi;

	$sql=" select content_id,title as hu,mlct.en, mlct.de, mlct.ua, type, "
		." DATE_FORMAT(date_created,'%d %M %Y') as date_created from content c "
		." left outer join content_type ct on ct.content_type_id=c.content_type_id "
		." left outer join multi_language_content_title mlct on mlct.id = c.content_id "
		." where moderate_by = 0 and type in (select content_type_userdefined_code from content_type_userdefined) ";
//echo $sql;
return ;
	$res=sql_query($sql,$dbi);
	while($r=sql_fetch_assoc($res,$dbi)){
		$data[]=$r;
	}
	return $data;

}


//////////////////////////////////////////////////
//												//
//												//
//       			listak  					//
//												//
//												//
//////////////////////////////////////////////////




function getContentTypeParams($code){

	global $dbi;

	//if(is_numeric($code)) $code=$this->getContentCode($code);

	// default
	$list[]='title';

	$sql="select content_field from content_type_params where content_type_code='$code' order by content_field";
	$res=sql_query($sql,$dbi);
	while(list($field)=sql_fetch_array($res,$dbi)){
		$list[]=$field;
	}

	$this->content_type=$code;

	return $list;
}

/*
function getTipusID($cat){
	global $dbi;
	$sql="select content_type_id from content_type where category_id ='$cat'";
	$res=sql_query($sql,$dbi);
	list($category)=sql_fetch_array($res,$dbi);
	return $category;
}
*/

function getItemsByType($type,$group_val){

	global $dbi;

	switch($type) {
		case 'page':     $table='menu';            $id='x.menu_id';  $name='name';  $count_none=true;
			$join="left outer join (select * from activity_auth where activity_id=1 and id_type='user_type' and id in (0,6)) a on x.menu_id=a.menu_id";
			$where="where a.auth_value=1 or x.inactive=2";
			break;
		case 'product':  $table='webshop_product'; $id='id';       $name='name';   $group='category_id';
			$join="left outer join webshop_product_conn pc on x.id=pc.product_id";
			break;
		case 'user':     $table='users';           $id='id';       $name="concat(firstname,' ',lastname)";  $group='user_type';
			break;
		default:
			// ha content akkor
			// S nincs altipusa, akkor
			$ud_sub_data=$this->getUserDefinedContentTypeOneSubLevel($type,$group_val);
			if($ud_sub_data){
					//echo "<pre>";print_r($ud_sub_data);
					$result=array('name'=>$ud_sub_data[name],'type'=>$ud_sub_data[name],'type_id'=>0);
					return $result;
			}

			//if(!$ud_sub_data) return false;
			//$type=$ud_sub_data[name];
			//$group_val=$ud_sub_data[id];
			//echo "$type ->$group_val";
			//$table='content_type_userdefined';           $id='content_type_userdefined_id';       $name="content_type_userdefined_code";  $group='content_type_userdefined_id';
			//$dd=$this->getContentTypeTree($type);
			//echo "<pre>";print_r($dd);

			return;
		break;
	}

	if($group_val) $where="where $group=$group_val";

	$sql="select $id,$name,count(content_id) from $table x ".
		"left outer join content_type t on $id=type_id and type='$type' ".
		"left outer join content c on c.content_type_id=t.content_type_id ".
		"$join $where group by $id order by $name";

	$res=sql_query($sql,$dbi);

	while(list($id,$name,$count)=sql_fetch_array($res,$dbi))
		if(!($count_none && $this->exclude_linked && $count)) $data[]=array(id=>$id,name=>$name,count=>$count);

	return $data;

}
function getContentCode($id){

	global $dbi;

	if(!is_numeric($id)) return $id;

	// CSAK userdefined code-ra kell nzni
	// alapveto problema, hogy az ajax_content-ben kivalasztasok ID-t adnak vissza.
	// mi CODE alapjan navigalunk a CONTENT tablak kozott, ezrt a visszaforditas SAVENEWCONTENT es CONTENT LIST-nel

	$sql="select content_type_userdefined_code from content_type_userdefined where content_type_userdefined_id=$id";
	$res=sql_query($sql,$dbi);
	list($code)=sql_fetch_array($res,$dbi);
	return $code;
}

function getContentSQL($query,$type,$group,$type_id,$content_id,$country_code=''){

	if($this->debug){
		echo "<b>create sql:</b><br>";
		echo "query: $query<br>";
		echo "type: $type<br>";
		echo "group: $group<br>";
		echo "type_id: $type_id<br>";
		echo "content_id: $content_id<br>";
		echo "strip_tags: $strip_tags<br>";
	}

	if(is_numeric($type)) $type=$this->getContentCode($type);
	$item_name="''";
	$order='date_archive';

	switch($type) {
		case 'page':
			$sql_menu=', m.name ';
			$item_name="name";
			$join="left outer join menu m on type_id=menu_id ";
		break;
		case 'user':
			$item_name="concat(u.firstname,' ',u.lastname) as name,date_created";
			$join="left outer join users u on type_id=u.id ";
			if($group) $and_group="and u.user_type=$group";
		break;
		case 'product':
			$item_name="name";
			$join="left outer join webshop_product p on type_id=p.id "
				."left outer join webshop_product_conn pc on p.id=pc.product_id ";
			if($type_id) $and_type_id="and type_id=$type_id";
			else $and_group="and category_id=$group";
		break;
		case 'newsletter_f':
			$order='date_archive desc';
		break;
	}

	if($this->type_id) $and_type_id="and type_id=$this->type_id";
	if($this->create_user_id) $and_type_id="and create_user_id=$this->create_user_id";


	switch($query) {
		case 'item_name':
			$sql="select $item_name from content c ".
				"inner join content_type t on c.content_type_id=t.content_type_id ".
				$join.
				"where content_id=$content_id";
		break;
		case 'list':
			if($this->getCreateUser) {
				$field=',owner.login';
				$join.='left join users owner on create_user_id=owner.id ';
			}
			if($this->order) $order=$this->order;
			$sql="select distinct c.content_id as id,c.title,blurb,c.content,c.date_archive,$item_name,code,img_ext,date_expire$field $this->sql_select_more from content c ".
				"inner join content_type t on c.content_type_id=t.content_type_id ".
				$join.
				"where t.type='$type' $and_group $and_type_id order by $order";
		break;
		case 'list_translator':
			$sql="select c.content_id as id,c.title,ml.$country_code $sql_menu from content c ".
				"inner join content_type t on c.content_type_id=t.content_type_id ".
				"left outer join multi_language_content_title ml on content_id=ml.id ".
				$join.
				"where t.type='$type' $and_group $and_type_id and $country_code is null ".

				"union select c.content_id as id,c.title,ml.$country_code $sql_menu from content c ".
				"inner join content_type t on c.content_type_id=t.content_type_id ".
				"left outer join multi_language_content_title ml on content_id=ml.id ".
				$join.
				"where t.type='$type' $and_group $and_type_id and $country_code is not null ";
		break;
	}

	if($this->debug) echo "<b>CREATE_SQL:</b> $sql<br>";
	return $sql;
}
function getContentList($type,$group='',$show=40,$type_id='', $strip_tags=true){

	if($this->debug){
		echo "<b>list:</b><br>";
		echo "type: $type<br>";
		echo "group: $group<br>";
		echo "show: $show<br>";
		echo "type_id: $type_id<br>";
		echo "strip_tags: $strip_tags<br>";
	}

	global $dbi,$SITEGLOBALS;

	if($this->split) {
		if(!($o=$p[o]) && !($o=$_GET[o])) $o=0;
		$o_item=$o*$this->split;
		$limit=" limit $o_item,$this->split";
	}

	if($scp=$SITEGLOBALS[CONTENT_PARAMS]){
		foreach($scp as $k => $i){
			$sql_sel[] =$k;
		}
		$this->sql_select_more=",".implode(',',$sql_sel);
	}

	if($show==''){$show=999;}

	if(!$group && !$type_id && ($type=='product' || $type=='user')) return;
	$sql=$this->getContentSQL('list',$type,$group,$type_id,'');
	if($this->limit) $sql.=" limit $this->limit";
	$sql_limit=$sql.$limit;
	if($this->debug) echo "<b>GETLIST_SQL:</b> $sql<br>";
	$res=sql_query($sql_limit,$dbi);
	while($r=sql_fetch_assoc($res,$dbi)){
		extract($r);
		if($strip_tags) $content=strip_tags($content);
		if(strlen($content)>$show) $content=substr($content,0,$show).'<b>...</b>';
		if($date_archive) $date_archive=date("Y-m-d",strtotime($date_archive));
		// kiskepet keresnk, ha nincs item
		if(!$item){
			$item=$this->checkMainImage($id,$img_ext);
		}

		// paramsok es ertekeikcheckMainImage
		if($this->getCreateUser){
			$d[login]=$login;
		}
		if(is_array($scp)){
			foreach($scp as $k => $i){
				$d[$k]=${$k};
			}

		}
		if(!is_array($d)) $d=array();

		$data[]=array_merge(compact(id,title,blurb,content,date_archive,item,code,img_ext,date_expire,create_user,name),$d);

	}
	//print"<pre>";print_r($data);

	if($this->split) {
		$res1=sql_query($sql,$dbi);
		$items=sql_num_rows($res1,$dbi);
		$this->makePages($items,$o);
	}

	return $data;
}

// lista legyujtes alap es user defined contentekre
// title, datum
function getContentShortListByCode($code,$striphtmltag=''){

	global $dbi;

	if(!$striphtmltag) $striphtmltag=1;

	$types=$this->getContentTypeTree($code);

	$sql="";

}
function getNameOfTypeId($type,$content_id){

	global $dbi;

	$sql=$this->getContentSQL('item_name',$type,'','',$content_id);
	$res=sql_query($sql,$dbi);

	list($item)=sql_fetch_array($res,$dbi);
	return $item;
}
function getContentLinksByType($type) {
	global $dbi;
	$sql="select content_id as id,code,title from content c ".
		"inner join content_type t on c.content_type_id=t.content_type_id ".
		"where t.type='$type' order by date_archive";
	$res=sql_query($sql,$dbi);
	while($a=sql_fetch_assoc($res,$dbi))
		$data[]=$a;
	return $data;

}
function getPageContent($menu_id) {

	global $dbi;

	if(!$menu_id) return 0;

	$sql="select c.content_id,c.title,c.content,c.date_archive from content c ".
		"inner join content_type t on c.content_type_id=t.content_type_id where t.type_id=$menu_id and type='page' $this->sql_lang";
	$res=sql_query($sql,$dbi);
	list($id,$title,$content,$date_archive)=sql_fetch_array($res,$dbi);
	if(!$id) return false;

	if($date_archive) $date=date("Y-m-d",strtotime($date_archive));
	if($this->lang_id){
		$data=array(title=>$title,content=>$content,date_archive=>$date);
	}else{
		$l=new translator('',1);
		$data=array(title=>$l->getContentTitle($id),content=>$l->getContentContent($id),date_archive=>$date);
	}

	return $data;
}

/**
 * @todo Lorand:a type nem hlyesg
 */
function getUserContent($user_id,$type) {

	global $dbi;

	$sql="select c.content_id,c.title,c.content,c.date_archive from content c inner join content_type t on c.content_type_id=t.content_type_id where t.type_id=$user_id and type='$type'";
	$res=sql_query($sql,$dbi);
	while(list($id,$title,$content,$date_archive)=sql_fetch_array($res,$dbi)){
		$data = array(id=>$id,title=>$title,content=>$content,date_archive=>$date);
	}

	return $data;
}
function getContentType($content_type_id){

	global $dbi;

	$sql="select type, type_id from content_type where content_type_id=$content_type_id";
	$res=sql_query($sql,$dbi);
	list($type,$type_id)=sql_fetch_array($res,$dbi);
	$type_data=array(type=>$type,type_id=>$type_id);

	return $type_data;

}
function getContentByType($type, $param=false){

	global $dbi,$selected_lang;

	// azrt nem j kiszedni, mert akkor simn a CODE_ot figja kirni, neknk
	// meg szuksegunk van a MAGYAR feliratara mindenkepp
	// mashogy megoldani, ha nem akarjuk a trasnlate-en keresztul futtatni


	// WHERE
	if($param['date_expire']) $cnd[] = " (date_expire >= '".date("Y-m-d H:i:s",time())."' or date_expire is null )";
	if($param['date_start']) $cnd[] = " (date_start <= '".date("Y-m-d H:i:s",time())."' or date_start is null) ";
	if($param['create_user_id'])  $cnd[] = " ( create_user_id=".$param['create_user_id']." ) ";

	if(is_array($cnd)) $cond=" and ".implode(" and ",$cnd);

	$tr = new translator($selected_lang,0);
	$type_name=$tr->getSingleTranslation("CONTENT_TYPE_$type", 'content');

	// param letiltja ezeket a mezoket
	// igy az sql-t nem terheljuk a lehivasokkal
	$blurb=',blurb'; 			if($param['noblurb']){							unset($blurb);		unset($param['noblurb']);}
	$content=',content';		if($param['nocontent']){						unset($content);	unset($param['nocontent']);}
	$date=',date_archive';		if($param['nodate']){							unset($date); 		unset($param['nodate']);}
	$img_ext=',img_ext';		if($param['noimage'] && !$param[randomimg]){	unset($img_ext); 	}

	// ezzel nem csinaltunk semmit
	unset($param[randomimg]);
	unset($param['noimage']);

	if(!$param['order']) $order=' order by date_archive desc ';
	else{
		$order=' order by '.$param['order'];
		unset($param['order']);
	}

	if($param['random']){
		$order=" ORDER BY RAND() ";
		unset($param['random']);
	}
	if($this->limit) $limit="limit $this->limit";

	// SQL SELECT
	if(is_array($param)){
		foreach($param as $k => $i){
			if($i) $sql_sel[] =$k;
		}
		if(is_array($sql_sel)) $sql_select=",".implode(',',$sql_sel);
	}

	$sql="select content_id as id,title $blurb $content $img_ext $date $sql_select from content c inner join content_type t on t.content_type_id=c.content_type_id where type='$type' $cond $this->sql_lang $order $limit";
	$res=sql_query($sql,$dbi);
	while($a=sql_fetch_assoc($res,$dbi)){
		if($this->stripHTMLtag){
			$a[blurb]=strip_tags($a[blurb]);
			$a[content]=strip_tags($a[content]);
		}
		if($a[img_ext]){
			$a[icon]=$this->checkMainImage($a[id],$a[img_ext]); // es itt a valtozokat is tombbol kell kiszedni!!! ez elfelejtodott!!!
		}
		$a[type]=$type_name; // itt a nyers CODE jott ki, ami faszsag. userek azt fogjak olvasgatni???
		$data[]=$a;
	}

	return $data;
}
function getContentByCode($code){
	global $dbi;
	$sql="select content_id as id,title,blurb,code,content,img_ext from content where code='$code'";
	$res=sql_query($sql,$dbi);
	$a=sql_fetch_assoc($res,$dbi);
	$a[picture]=$this->checkMainImage($a[id],$a[img_ext]);
	$a[clearblurb]=strip_tags($a[blurb]);
	return $a;
}
function getContentIdByCode($code){
	global $dbi;
	$sql="select content_id from content where code='$code'";
	$res=sql_query($sql,$dbi);
	list($id)=sql_fetch_row($res,$dbi);
	return $id;
}
function getContentTypesOnlyList() {

	global $SITEGLOBALS,$auth;

	// siteglobals manage the list

	$data=array();
	if($auth->user_data[type]==1){
		foreach($this->global_types as $global=>$type){
			if($SITEGLOBALS[$global]) $data[]=$type;
			$this->getContentTypeChain($type);
		}
	}

	// additional user defines CONTENT_TYPES

	if($userdefined=$this->getUserDefinedContentTypeTopLevel()){
		$data=array_merge($data,$userdefined);
	}

	return $data;
}
function getContentTypeChain($type){

	global $dbi;

	switch($type){
		case 'page':
			$chain='menu';
		break;;
		case 'user':
			$chain='user';
		break;;
		case 'product':
			$chain='product';
		break;;
		default:
			// hogy ne akadjon ki a tobbi projekt!!
			if(sql_check_field('content_type_userdefined','chain_user')){
				$chain_user=' chain_user ';
			}
			if(sql_check_field('content_type_userdefined','chain_menu')){
				$chain_menu=', chain_menu ';
			}
			if(sql_check_field('content_type_userdefined','chain_product')){
				$chain_product=',chain_product ';
			}
			if(!$chain_user && !$chain_menu && !$chain_product) return false;
			$sql="select $chain_user $chain_menu $chain_product from content_type_userdefined where content_type_userdefined_code = '$type'";
			$res=sql_query($sql,$dbi);
			list($cu,$cm,$cp)=sql_fetch_array($res,$dbi);
		break;
	}

	if($chain) $this->content_type_chain[$type]=$chain;
}
function getUserDefinedContentTypeTopLevel(){

	global $dbi;

	$sql="select content_type_userdefined_id,content_type_userdefined_code from content_type_userdefined where level=1";
	$res=sql_query($sql,$dbi);
	while(list($id,$type)=sql_fetch_array($res,$dbi)) {
		if($this->check_entitlement){
			if($this->checkEntitlement(array('content_type_id'=>$id))) $ud[]=$type;
		}else $ud[]=$type;
		$this->getContentTypeChain($type);
	}
	return $ud;
}
function getUserDefinedContentTypeOneSubLevel($code,$subid){

	global $dbi;

	$data=$this->getContentTypeTree($code,1);
	if(is_array($data)) foreach($data as $item){

		if($item[id]==$subid) return $item;
		//$this->getContentTypeTree($item[name],1);
	}

	return false;
}
function getContentTypeTree($code='',$level='',$check=''){

	// ha nincs $code, akkor teljes fa szerkezet kell!
	// $level jelentse: hny szintre nzi, visszaszmll

	// check, adja vissza, hogy a keresett kod melyik FOAGHOZ tartozik

	global $dbi;

	// hogy ne akadjon ki a tobbi projekt!!
	if(sql_check_field('content_type_userdefined','chain_user')){
		$chain_user=', chain_user ';
	}
	if(sql_check_field('content_type_userdefined','chain_menu')){
		$chain_menu=', chain_menu ';
	}
	if(sql_check_field('content_type_userdefined','chain_product')){
		$chain_product=',chain_product ';
	}

	if($this->check_for_sub) {
		$check_for_sub=',(select 1 from content_type_userdefined_conn where main=id limit 1) has_sub';
	}

	if($check) $this->check_for_topcode=$check; // hogy a rekurzivitas miatt megmaradjon a valtozo

	if($code){
		$sql="select content_type_userdefined_id from content_type_userdefined where content_type_userdefined_code='$code' ";
		$res=sql_query($sql,$dbi) or die($sql);
		list($id)=sql_fetch_array($res,$dbi);
		// ha nincs ilyen kd kiltetni
		if(!$id) return false;
		if($this->check_entitlement){
			if($this->checkEntitlement(array('content_type_id'=>$id))) $ids[]=$id;
		}else $ids[]=$id;
	}else{
		// legyjteni a level 1-et
		$sql="select content_type_userdefined_id,content_type_userdefined_code from content_type_userdefined where level=1 ";
		$res=sql_query($sql,$dbi);
		while(list($id,$name)=sql_fetch_array($res,$dbi)){
			if($this->check_entitlement){
				if($this->checkEntitlement(array('content_type_id'=>$id))) $ids[]=$id;
			}else{
				$ids[]=$id;
				$this->top_level_codes[$id]=$name;
			}
		}
	}

	if($level) $level--;

	if(is_array($ids)) foreach($ids as $key => $item){
		$sql=" select content_type_userdefined_id id, content_type_userdefined_code $chain_user $chain_menu $chain_product $check_for_sub from content_type_userdefined ct "
			." inner join content_type_userdefined_conn ctc on ct.content_type_userdefined_id=ctc.sub "
			." where main=$item";
		$res=sql_query($sql,$dbi);
		while(list($id,$name,$cu,$cm,$cp,$has_sub)=sql_fetch_array($res,$dbi)){
			if($name==$this->check_for_topcode) $this->topcode=$this->top_level_codes[$item];
			$this->getContentTypeTree($name);

			// chain
			if($cu) $chain='user';
			if($cm) $chain='menu';
			if($cp) $chain='product';

			if(!$this->check_entitlement || $this->checkEntitlement(array('content_type_id'=>$id))){
				$tree[]=compact(id,name,chain,has_sub);
			}
			unset($chain);
		}
	}
	//echo "<pre>";print_r($tree);
	return $tree;

}

function getParentTypes($type,$reset=true) {
	global $dbi;
	if($reset) $this->parents=array($type);

	$sql="select c_main.content_type_userdefined_code from content_type_userdefined c_sub ".
		"left join content_type_userdefined_conn on c_sub.content_type_userdefined_id=sub ".
		"left join content_type_userdefined c_main on main=c_main.content_type_userdefined_id ".
		"where c_sub.content_type_userdefined_code='$type'";
	$res=sql_query($sql,$dbi);
	list($main)=sql_fetch_array($res,$dbi);
	if($main) {
		$this->parents[]=$main;
		$this->getParentTypes($main,false);
	}
}
function getContentForEachUserDefinedContentType($code,$limit='',$striphtmltag='') {
	$types=$this->getContentTypeTree($code);

	//if(!$types) return false;
	$data=array();

	$this->limit=$limit?$limit:20;
	$this->stripHTMLtag=$striphtmltag?$striphtmltag:0;

	if(is_array($types)) foreach($types as $i => $t) {
		$a=$this->getContentByType($t[name]); // ha id kell: $this->checkContentTypeExists($t[name])
		if(is_array($a)) $data=array_merge($data,$a);
	}
	return $data;
}

function getMetaData($id){

	$this->checkMetaFolder();

	$arr=array();

	$file=PATH."meta/".$id."_description.txt";

	$handle=fopen($file,"a+");
	$descr = fread($handle, filesize($file)?filesize($file):1);
	fclose($handle);

	$file=PATH."meta/".$id."_keywords.txt";
	$handle=fopen($file,"a+");
	$keyw = fread($handle, filesize($file)?filesize($file):1);
	fclose($handle);

	$arr=array('meta_descr'=>$descr,'meta_keyw'=>$keyw);

	return $arr;

}

function saveMeta($id,$d,$k){

	$this->checkMetaFolder();

	$file=PATH."meta/".$id."_description.txt";
	$handle=fopen($file,"w+");
	fwrite($handle, $d);
	fclose($handle);

	$file=PATH."meta/".$id."_keywords.txt";
	$handle=fopen($file,"w+");
	fwrite($handle, $k);
	fclose($handle);

}

function checkMetaFolder(){
	if(!is_dir(PATH.'meta')){
		mkdir(PATH.'meta');
	}
}

function getContentData($id,$param=''){

	if(!$id) return false;

	global $dbi;

	$l=new translator();

	// szedjuk mar le a userdefined content type-ok mezoit is!!
	$f=$this->getContentExtraFields($this->content_type);
	if(!is_array($param)) $param=array();
	if(is_array($f)) $param=array_merge($param,array_flip($f));

	if(is_array($param)){
		foreach($param as $k => $i){
			if($k!='meta') $sql_sel[] =$k;
			else $this->getMeta=1;
		}
		$sql_select=",".implode(',',$sql_sel);
	}

	$sql="select c.content_id as id,c.content_type_id as type_id,title,content,user_id as uid,date_archive as archive,max(timestamp) as create_date $sql_select from content c left outer join content_history h on c.content_id=h.content_id where c.content_id=$id group by c.content_id,title,content,user_id";
	$res=sql_query($sql,$dbi);
	if($d=sql_fetch_assoc($res,$dbi)){

		extract($d);

		if($uid){
			$u=new user();
			$udata=$u->getUserData($uid);
			$author=$udata[loginname];
		}
		if($archive) $archive=date("Y-m-d",strtotime($archive));
		if($date) $date=date("Y. M d.",strtotime($date));

		if(!$this->lang_id){
			$title=$l->getContentTitle($id);
			$content=$l->getContentContent($id);
		}

		if($this->stripHTMLtag){
			$content=strip_tags($content);
			$blurb=strip_tags($blurb);
		}

		$data=array(
			id			=>$id,
			type_id		=>$type_id,
			title		=>$title,
			content		=>$content,
			date		=>$date,
			author		=>$author,
			date_archive=>$archive,
			date_expire	=>$date_expire,
			blurb		=>$blurb,
			img_ext		=>$img_ext,
			source_url	=>$source_url,
			code		=>$code,
			icon		=>$this->checkMainImage($id,$img_ext)
		);

		if($this->getMeta){
			$data=array_merge($data,$this->getMetaData($id));
		}

		if(is_array($param)){
			foreach($param as $k => $i){
				$data[$k]=${$k};
			}
		}

	}

	return $data;
}
function checkMainImage($id,$ext) {

	if(!$ext || !$id) return false;

	$name=$this->makeNewsFileName($id);
	$name.=".".$ext;
	if(file_exists(PATH.IMAGE_NEWS.$name)) return $name;
	else return false;

}

function getUtolsoHirek($db=''){

	global $dbi;

	$u=new user;

	$sql_where=" where date_archive > now() and content_type_id=2 ";

	if($db){
		$darab=$db-1;
		$sql_order="  ";
	}

	$sql="select c.content_id,title,content,user_id,max(timestamp) from content c left outer join content_history h on c.content_id=h.content_id $sql_where group by c.content_id,title,content,user_id";
	$res=sql_query($sql,$dbi);
	while(list($id,$title,$text,$author_id,$date)=sql_fetch_array($res,$dbi)){
		if($author_id) $udata=$u->getUserData($author_id);
		$author=$udata[loginname];
		$hirek[]=array(id=>$id,title=>$title,content=>$text,author=>$author,date=>date("Y. M d. H:i",strtotime($date)));
		if($db){
			if(!$darab) break;
			$darab--;
		}

	}

	return $hirek;

}
function getAuthor($id){

	global $dbi;

	$sql="select user_id from content_history where content_id=$id order by timestamp";
	$res=sql_query($sql,$dbi);
	if(list($user_id)=sql_fetch_array($res,$dbi)) return $user_id;
}
function getLastContentId() {
	global $dbi;
	$sql="select max(content_id) from content";
	$res=sql_query($sql,$dbi);
	list($id)=sql_fetch_array($res,$dbi);
	return $id+1;
}
function getContentExtraFields($type=''){

	// a content tipus alapjan is keresse ki a lehetseges kodokat
	$extra=array();
	if($type){
		$this->getContentTypeTree('',5,$this->getContentCode($type)); // 5 szint csak eleg!
		$extra=$this->getContentTypeParams($this->topcode?$this->topcode:$type);
	}

	$res=array_merge(array('img_ext','source_url','date_expire','code'),$extra);
	$res=array_flip($res);
	$res=array_flip($res);

	return $res;
}
function checkContentTypeExists($type,$id=''){

	// ellenrzi, hogy a content tipus mr fel van-e vve
	// ez fleg az egyedi content type-okra vonatkozik

	global $dbi;

	if($id){
		$where_id=" and type_id=$id ";
		$insert_id=$id;
	}else{
		$insert_id=" 'null' ";
	}

	$sql="select content_type_id from content_type where type='$type' $where_id";
	$res=sql_query($sql,$dbi);
	$num=sql_num_rows($res,$dbi);
	if(!$num){
		$sql="insert into content_type ( type,type_id) values ('$type',$insert_id)";
		sql_query($sql,$dbi);
		$sql="select content_type_id from content_type where content_type_id=LAST_INSERT_ID()";
		$res=sql_query($sql,$dbi);
	}
	list($content_type_id)=sql_fetch_array($res,$dbi);

	return $content_type_id;
}/*
function checkContentTypeContraTypeID($type,$type_id){

	//

	global $dbi;

	echo "id->".$type_id."<br>";
	echo "type->".$type."<br>";

	// ha a kod egyaltalan nincs a tablaban, akkor nem ide valo
	$sql="select count(*) from content_type_userdefined where content_type_userdefined_code = '$type'";
	echo $sql."<br>";
	$res=sql_query($sql,$dbi);
	list($db)=sql_fetch_array($res,$dbi);

	if(!$type_id) return $type;
	if(!$db) return $type_id;

	$sql="select content_type_userdefined_code from content_type_userdefined where content_type_userdefined_id=$type_id";
	$res=sql_query($sql,$dbi);
	list($code)=sql_fetch_array($res,$dbi);

	if($code){
		if($code!=$type) return $code;
	}
	echo $type."<br>";
	return $type;
}*/
function makeNewsFileName($id) {
	$fn=$id;
	while(strlen($fn)<8) $fn='0'.$fn;
	$fn='n'.$fn;
	return $fn;
}

//////////////////////////////////////////////////
//												//
//												//
//       			TORLES  					//
//												//
//												//
//////////////////////////////////////////////////



function delContent($id){

	global $dbi;

	//kp trlse
	$sql="select img_ext,content_type_id from content where content_id=$id";
	$res=sql_query($sql,$dbi);
	list($ext,$content_type_id)=sql_fetch_array($res,$dbi);

	if($ext){
		$filename=$this->makeNewsFileName($id);
		$pic=PATH.IMAGE_NEWS.$filename.".".$ext;
		if(file_exists($pic)) unlink($pic);
	}

	// content trlse
	$sql="delete from content where content_id=$id";
	sql_query($sql,$dbi);

	// EGYEDI content_type bejegys trlse
	$content_type=$this->getContentType($content_type_id);
	if($content_type[type_id]){
		$sql="select 1 from content where content_type_id='$content_type_id'";
		$res=sql_query($sql,$dbi);
		if(!sql_num_rows($res,$dbi)) {
			$sql="delete from content_type where content_type_id=$content_type_id";
			sql_query($sql,$dbi);
		}
	}

	// history
	$this->saveContentHistory($id);

}

//////////////////////////////////////////////////
//												//
//												//
//       			MENTES  					//
//												//
//												//
//////////////////////////////////////////////////



function saveNewContent($post){

	global $dbi,$auth;

	if(is_numeric($type=$post[content_type])) $type=$this->getContentCode($type); // a KD KELL
	$id=$post[type_id];

	// default content type: email,page, newsletter, user...
	/*
	// ez mar nem kell
	if(!in_array($type,$this->deafult_content_type)) {
		$type=$this->checkContentTypeContraTypeID($type,$id);
	}
	*/
	$content_type_id=$this->checkContentTypeExists($type,$id);

	//id
	$sql="select max(content_id) from content";
	$res=sql_query($sql,$dbi);
	list($id)=sql_fetch_array($res,$dbi);
	$id++;

	//kp
	if($_FILES['image']['name']) {
		$filename=$this->makeNewsFileName($id);

		$params=array(dst_file_name=>IMAGE_NEWS.$filename, x=>$this->thumb[width], $y=>$this->thumb[height]);
		$gal=new gallery;
		$gal->uploadPicture($params);

		$post[img_ext]=$gal->ext;
	}
	elseif($file=$_FILES['file']['name']) {
		$filename=$this->makeNewsFileName($id);
		$post[img_ext]=strtolower(substr(strrchr($file,'.'),1));
		move_uploaded_file($_FILES['file']['tmp_name'],IMAGE_NEWS."$filename.$post[img_ext]");
	}

	$extra=$this->getContentExtraFields($type);
	foreach($extra as $k => $v)
		if($post[$v]){
			$sql_f[]=$v;
			$sql_v[]="'$post[$v]'";
			if($v=='date_archive'){
				$date_archive=1;
			}

		}
		if(!$date_archive){
				$sql_f[]='date_archive';
				$sql_v[]="'".date("Y-m-d H:i:s")."'";
		}
		// ne irjuk felul
		/*else{
			$post[$v]='null';
		}*/
	$sql_field=",".implode(",",$sql_f);
	$sql_value=",".implode(",",$sql_v);
	$sql="insert into content (	content_id,		content,			content_type_id,	create_user_id 	$sql_field) ".
		"values (				$id,			'$post[content]',	'$content_type_id',	$auth->uid 		$sql_value)";

	sql_query($sql,$dbi);

	$this->saveContentHistory($id);

	return $id;
}
function saveContentHistory($content_id){

	global $dbi;

	if(!$this->user_id) die('nincs user id');
	$sql="insert into content_history (content_id,user_id) values ($content_id,$this->user_id)";
	sql_query($sql,$dbi);
}


//////////////////////////////////////////////////
//												//
//												//
//       			UPDATE  					//
//												//
//												//
//////////////////////////////////////////////////


function updateContent($post){

	global $dbi;

	$id=$post[content_id];
	if($archive=$post[archive]) $sql_archive=", date_archive='".$archive."' ";

	//kiskep
	if($_FILES['image']['name']) {
		$filename=$this->makeNewsFileName($id);

		$old_pic=IMAGE_NEWS.$filename.".".$post[img_ext];
		if($post[img_ext] && file_exists(PATH.$old_pic) ) unlink(PATH.$old_pic);

		$params=array(dst_file_name=>IMAGE_NEWS.$filename, x=>$this->thumb[width], $y=>$this->thumb[height]);
		$gal=new gallery;
		$gal->uploadPicture($params);

		$post[img_ext]=$gal->ext;
	}
	elseif($file=$_FILES['file']['name']) {
		$filename=$this->makeNewsFileName($id);
		$post[img_ext]=strtolower(substr(strrchr($file,'.'),1));
		move_uploaded_file($_FILES['file']['tmp_name'],IMAGE_NEWS."$filename.$post[img_ext]");
	}

	//tpus-mezk
	$extra=$this->getContentExtraFields($post['type']);

	// META
	if($post['meta_description'] || $post[meta_keywords]){
		$this->saveMeta($id,$post[meta_description],$post[meta_keywords]);
	}
	unset( $extra[array_search('meta',$extra)] );

	foreach($extra as $v) {
		if($post[$v]) $p="'$post[$v]'"; else $p='null';
		$sql_extra.=", $v=$p";
	}

	$sql="update content set title='$post[title]', blurb='$post[blurb]', content='$post[content]' $sql_archive $sql_extra where content_id=$id";
	sql_query($sql,$dbi);

	$this->saveContentHistory($post[content_id]);
}


//////////////////////////////////////////////////
//												//
//												//
//       			MAIL	  					//
//												//
//												//
//////////////////////////////////////////////////



function sendMail($code,$data,$debug=false){

	global $dbi,$SITEGLOBALS;

	//csere-vltozk lekrdezse

	//levl lekrdezse
	$sql="select title,content from content c ".
		"inner join content_type t on c.content_type_id=t.content_type_id ".
		"where type='email' and code='$code'";
	$res=sql_query($sql,$dbi);
	list($subject,$body)=sql_fetch_array($res,$dbi);
	if(!$body) return false;

	//csere
	if($data) {
		$nl2br=array('message');
		$exclude=array('');
		foreach($data as $k => &$v) {
			if(!in_array($k,$exclude)) {
				if(in_array($k,$nl2br)) $v=nl2br($v);
				$body=str_replace("#$k#",$v,$body);
			}
		}
	}

	// ha nincs cimzett akkor csak return
	if(!$data) return array(title=>$subject, content=>$body);

	// email cim
	if(!($email=$data[email])) $email=$data[$data[email_var]];
	if(!$email) {
		if(!($cimzett=$data[cimzett])) $cimzett=$data[$data[cimzett_var]];
		$sql="select email from users where id=$cimzett";
		$res=sql_query($sql,$dbi);
		list($email)=sql_fetch_array($res,$dbi);
	}

	// adat a cmben
	if($this->subject_data) $subject=str_replace('#',"$this->subject_data -",$subject);

	// cc
	$cc = is_array($data[cc]) ? implode(',',$data[cc]) : $data[cc];

	// klds
	$headers="From: $SITEGLOBALS[MAIL_FROM]\n";
	if($cc) $headers.="Cc: $cc\n";
	$headers.="Content-Type: text/html; charset=ISO-8859-2";

	if($debug)
		print"<font color='#00cc33'><b>$email</b></font> <font color='#33ee88'>$cc</font><br><font color='#dd5500'>$subject</font><br>$body<hr>";
	else{
		// utolso paramter a hibavlasz cmzettje mail szervertl
		mail($email,$SITEGLOBALS[SELLER_DATA][company]." - ".$subject,$body,$headers, '-f'.$SITEGLOBALS[MAIL_FROM]);
	}

}

function getSeoName($n){

	global $SITEGLOBALS;
	return str_replace($SITEGLOBALS[REPLACE_CHARS][mit],$SITEGLOBALS[REPLACE_CHARS][mire],$n);

}

function saveDefaultMeta($post){

	if(!is_dir(PATH.'meta')){
		mkdir(PATH.'meta');
	}

	$files=array(
		'title','description','keywords'
	);

	foreach($files as $f){
		$file=PATH."meta/{$f}.txt";
		$handle=fopen($file,'w+');
		fwrite($handle,$post[$f]);
		fclose($handle);
	}
	//echo "<pre>";print_r($post);exit;

}

//////////////////////////////////////////////////
//												//
//												//
//       			Jogozas  					//
//												//
//												//
//////////////////////////////////////////////////


// entitlement osztalyba iranyitva

} // class

?>