<?php
	class ArticlesModel {

		public function addArticle( $datas ) {
			$ins = array();
			$ins["article_name"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_name"] ) );
			$ins["article_category_id"]=sprintf( "%d" , $datas["article_category_id"] );
			if (isset( $datas["article_ctstamp"] ))
				$ins["article_ctstamp"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_ctstamp"] ) );

			if (isset( $datas["article_publication_tstamp"] ))
				$ins["article_publication_tstamp"]=($datas["article_publication_tstamp"]) ?
					sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_publication_tstamp"] ) ) : "null";

			if (isset( $datas["article_depublication_tstamp"] ))
				$ins["article_depublication_tstamp"]=($datas["article_depublication_tstamp"]) ?
					sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_depublication_tstamp"] ) ) : "null";

			if (isset( $datas["article_url"] ))
				$ins["article_url"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_url"] ) );

			if (isset( $datas["article_is_active"] )) $ins["is_active"]=($datas["article_is_active"]) ? "true" : "false";
			if (isset( $datas["article_is_memberonly"] )) $ins["is_memberonly"]=($datas["article_is_memberonly"]) ? "true" : "false";
			if (isset( $datas["article_is_subscriberonly"] )) $ins["is_subscriberonly"]=($datas["article_is_subscriberonly"]) ? "true" : "false";

			$ins["article_tech_mtstamp"]=sprintf( "%d" , fo3_time() );

			$booleans = array( "is_url_used" , "is_active" , "is_public" , "is_deleted" , "is_memberonly" );
			foreach ($booleans as $b)
				if (isset( $datas[$b] )) $ins[$b]=($datas[$b]) ? "true" : "false";

			FNTH_db_free_result(
				FNTH_db_query(
					FNTH_db_generate_insert_query( "articles" , $ins ) ) );
			$query = sprintf( "select currval('articles_article_id_seq') as num" );
			$row = FNTH_db_get_row( $query );
			return $row["num"];
		}

		public function getForumTopicIdForArticleId( $article_id , $create_if_not_existing = false ) {
			$query = sprintf( "select comment_forum_topic_id from larticles where article_id=%d limit 1",$article_id);
			$forum_topic_id = FNTH_db_get_field( $query , "comment_forum_topic_id" );
			if (!$create_if_not_existing) return $forum_topic_id;
			if (!$forum_topic_id) {
				$article = $this->getArticleFromId( $article_id );
				$larticle = $this->getLanguageArticle( $article_id , $GLOBALS["langcode"] );
				require_once( $GLOBALS["site_root"] . "/includes/models/Forum.inc.php" );
				$fm = new ForumModel();
				$aliasname = "cikk-hozzaszolasok";
				$parent_forum_topic_id = $fm->getForumTopicIdFromAlias( $aliasname );
				$ins = array();
				$ins["forum_topic_parentid"]=$parent_forum_topic_id;
				$ins["forum_topic_level"]=2;
				$ins["ctstamp"]="now()";
				$ins["forum_topic_ordering"]=$fm->getNextTopicOrderingOnParent( $parent_forum_topic_id );
				$ins["forum_topic_title"]=$larticle["larticle_title"];
				$ins["forum_topic_aliasname"]=fo3_generate_alias( $larticle["larticle_title"] );
				$ins["is_public"]="true";
				$ins["is_active"]="true";
				$ins["is_admin_acknowledged"]="true";
				$forum_topic_id = $fm->addTopic( $ins );
				$query = sprintf( "update larticles set comment_forum_topic_id=%d where article_id=%d",
					$forum_topic_id , $article_id );
				FNTH_db_free_result( FNTH_db_query( $query ) );
			}
			return $forum_topic_id;
		}


		public function addLanguageArticle( $article_id , $datas ) {
			$ins["article_id"]=sprintf( "%d" , $article_id );
			$ins["site_language_id"]=sprintf( "%d" , $datas["site_language_id"] );
			$ins["larticle_title"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_title"] ) );
			if (isset( $datas["larticle_ctstamp"] ))
				$ins["larticle_ctstamp"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_ctstamp"] ) );
			if (isset( $datas["larticle_publication_tstamp"] ))
				$ins["larticle_publication_tstamp"]=($datas["larticle_publication_tstamp"]) ?
					sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_publication_tstamp"] ) ) : "null";

			if (isset( $datas["larticle_depublication_tstamp"] ))
				$ins["larticle_depublication_tstamp"]=($datas["larticle_depublication_tstamp"]) ?
					sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_depublication_tstamp"] ) ) : "null";
			
			$ins["larticle_tech_mtstamp"]=sprintf( "%d" , fo3_time() );

			$ins["larticle_lead"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_lead"] ) );
			$ins["larticle_body"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_body"] ) );
			if (isset( $datas["larticle_extra_head"] )) $ins["larticle_extra_head"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_extra_head"] ) );
			if (isset( $datas["larticle_url"] )) $ins["larticle_url"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["larticle_url"] ) );
			
			$booleans = array( "is_url_used" , "is_active" , "is_public" , "is_deleted" , "is_memberonly" );
			foreach ($booleans as $b)
				if (isset( $datas[$b] )) $ins[$b]=($datas[$b]) ? "true" : "false";
			
			FNTH_db_free_result(
				FNTH_db_query(
					FNTH_db_generate_insert_query( "larticles" , $ins ) ) );
			$query = sprintf( "select currval('larticles_larticle_id_seq') as num" );
			$row = FNTH_db_get_row( $query );
			return $row["num"];
		}
		
		public function updateArticle( $article_id , $datas ) {
			$upd = array();
			$upd["article_name"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_name"] ) );
			$upd["article_category_id"]=sprintf( "%d" , $datas["article_category_id"] );
			if (isset( $datas["article_publication_tstamp"] ))
				$upd["article_publication_tstamp"]=($datas["article_publication_tstamp"]) ?
					sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_publication_tstamp"] ) ) : "null";

			if (isset( $datas["article_depublication_tstamp"] ))
				$upd["article_depublication_tstamp"]=($datas["article_depublication_tstamp"]) ?
					sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_depublication_tstamp"] ) ) : "null";
		
			if (isset( $datas["article_ordering_tstamp"] ))
				$upd["article_ordering_tstamp"]=sprintf( "'%s'" , FNTH_db_addslashes( $datas["article_ordering_tstamp"] ) );
			
			$upd["article_tech_mtstamp"]=sprintf( "%d" , fo3_time() );

			if (isset( $datas["article_is_active"] )) $upd["is_active"]=($datas["article_is_active"]) ? "true" : "false";
			if (isset( $datas["article_is_memberonly"] )) $upd["is_memberonly"]=($datas["article_is_memberonly"]) ? "true" : "false";
			if (isset( $datas["article_is_subscriberonly"] )) $upd["is_subscriberonly"]=($datas["article_is_subscriberonly"]) ? "true" : "false";
			FNTH_db_free_result(
				FNTH_db_query(
					FNTH_db_generate_update_query( "articles" , $upd,
					sprintf( "article_id=%d" , $article_id ) ) ) );
			return $article_id;
		}

		protected function removeLeadPicture( $article_id ) {
			$query = sprintf( "select article_leadpicture from articles where article_id=%d" , $article_id );
			$old_leadpicture = FNTH_db_get_field( $query , "article_leadpicture" );
			if ($old_leadpicture) {
				$fullpath = $GLOBALS["site_root"].$old_leadpicture;
				if (file_exists( $fullpath )) unlink( $fullpath );
			}
		}

		public function updateLeadPicture( $article_id , $file ) {
			if (!isset( $file["name"] )) return false;
			if (!isset( $file["type"] )) return false;
			if (!isset( $file["tmp_name"] )) return false;
			if (!isset( $file["error"] )) return false;
			if (!isset( $file["size"] )) return false;
			if ($file["error"]) return false;
			if (!$file["size"]) return false;

			// real file uploaded
			// -- remove original picture
			$this->removeLeadPicture( $article_id );

			// -- copy new leadpicture
			$newpath = sprintf( "%s/media/images/leadpic/%d.jpg" , $GLOBALS["site_www"] , $article_id );
			$fullpath = $GLOBALS["site_root"].$newpath;
			$cmd = sprintf( "convert %s %s" , $file["tmp_name"] , $fullpath );
			shell_exec( $cmd );

			// -- update articles table
			$upd = array();
			$upd["article_leadpicture"]=sprintf( "'%s'" , FNTH_db_addslashes( $newpath ) );
			$q = FNTH_db_generate_update_query( "articles" , $upd , sprintf( "article_id=%d" , $article_id ) );
			FNTH_db_free_result( FNTH_db_query( $q ) );
		}

		public function clearLeadPicture( $article_id ) {
			$this->removeLeadPicture( $article_id );
			FNTH_db_free_result( FNTH_db_query(
				sprintf( "update articles set article_leadpicture=null where article_id=%d" , $article_id ) ) );
		}

		protected function prepareArticle( $article ) {
			$article["article_timestamp"] = (isset( $article["article_publication_tstamp"] )) ?
				$article["article_publication_tstamp"] : $article["article_ctstamp"];
			$article["article_tdate"]=fo3_format_textual_date_to_screen( $article["article_timestamp"] );
			$article["article_date"]=fo3_format_date_to_screen( $article["article_timestamp"] );
			$article["article_time"]=fo3_format_date_to_screen( $article["article_timestamp"] );
			return $article;
		}

		public function getArticleFromId( $article_id ) {
			$query = sprintf( "select * from articles where article_id=%d" , $article_id );
			$row = FNTH_db_get_row( $query );
			$row = $this->prepareArticle( $row );
			if (isset( $row["is_active"] )) $row["is_active"]=($row["is_active"]=="t");
			if (isset( $row["is_memberonly"] )) $row["is_memberonly"]=($row["is_memberonly"]=="t");
			if (isset( $row["is_subscriberonly"] )) $row["is_subscriberonly"]=($row["is_subscriberonly"]=="t");
			return $row;
		}

		protected function prepareLanguageArticle( $larticle ) {
			$larticle["larticle_timestamp"] = (isset( $larticle["larticle_publication_tstamp"] )) ?
				$larticle["larticle_publication_tstamp"] : $larticle["larticle_ctstamp"];
			$larticle["larticle_tdate"]=fo3_format_textual_date_to_screen( $larticle["larticle_timestamp"] );
			$larticle["larticle_date"]=fo3_format_date_to_screen( $larticle["larticle_timestamp"] );
			$larticle["larticle_time"]=fo3_format_date_to_screen( $larticle["larticle_timestamp"] );
			$larticle["is_url_used"]=($larticle["is_url_used"]=="t");
			return $larticle;
		}

		public function getLanguageArticleUrlFromArticleName( $article_name , $site_language_id = 0 ) {
			if (!$site_language_id) $site_language_id=$GLOBALS["langcode"];
			$query = sprintf( "select larticle_url from larticles where article_id in (select article_id from articles where article_name='%s') and site_language_id=%d", FNTH_db_addslashes( $article_name ) , $site_language_id );
			return FNTH_db_get_field( $query , "larticle_url" );
		}

		public function getLanguageArticle( $article_id , $site_language_id ) {
			$query = sprintf( "select * from larticles where site_language_id=%d and article_id=%d",
				$site_language_id , $article_id );
			$retval = FNTH_db_get_row( $query );
			$retval = $this->prepareLanguageArticle( $retval );
			return $retval;
		}

		public function getLanguageArticleFromLarticleId( $larticle_id ) {
			$query = sprintf( "select * from larticles where larticle_id=%d",$larticle_id );
			$retval = FNTH_db_get_row( $query );
			$retval["is_url_used"]=($retval["is_url_used"]=="t");
			return $retval;
		}

		public function setLanguageArticle( $article_id , $site_language_id , $data = array() ) {
			$query=sprintf( "select * from larticles where site_language_id=%d and article_id=%d",
				$site_language_id , $article_id );
			$row = FNTH_db_get_row( $query );

			$d = array();
			$d["site_language_id"]=sprintf( "%d" , $site_language_id );
			$d["article_id"]=sprintf( "%d" , $article_id );
			$d["larticle_tech_mtstamp"]=sprintf( "%d" , fo3_time() );
			if (isset( $data["larticle_title"] )) $d["larticle_title"]=sprintf( "'%s'" , FNTH_db_addslashes( $data["larticle_title"] ) );
			if (isset( $data["larticle_lead"] )) $d["larticle_lead"]=(isset( $data["larticle_lead"] )) ? sprintf( "'%s'" , FNTH_db_addslashes( $data["larticle_lead"] ) ) : "null";
			if (isset( $data["larticle_body"] )) $d["larticle_body"]=sprintf( "'%s'" , FNTH_db_addslashes( $data["larticle_body"] ) );
			if (isset( $data["larticle_url"] )) $d["larticle_url"]=sprintf( "'%s'" , FNTH_db_addslashes( $data["larticle_url"] ) );
			if (isset( $data["is_url_used"] )) $d["is_url_used"]=($data["is_url_used"]) ? "true" : "false";
			$q = ($row) ?
				FNTH_db_generate_update_query( "larticles" , $d ,
					sprintf("site_language_id=%d and article_id=%d",$site_language_id , $article_id ) ) :
				FNTH_db_generate_insert_query( "larticles" , $d );
			FNTH_db_free_result( FNTH_db_query( $q ) );
		}

		public function unsetLanguageArticle( $article_id , $site_language_id ) {
			$query = sprintf( "delete from larticles where site_language_id=%d and article_id=%d",
				$site_language_id , $article_id );
			FNTH_db_free_result( FNTH_db_query( $query ) );
		}

		public function getLanguageArticles( $article_id ) {
			$query = sprintf( "select * from larticles where article_id=%d" , $article_id );
			$ds = FNTH_db_get_resultset( $query );
			$retval=array();
			foreach ($ds as $row) $retval[$row["site_language_id"]]=$row;
			return $retval;
		}

		public function getViewArticlesFromIds( $article_ids , $site_language_id = 0 , $associative = false ) {
			if (!$site_language_id) $site_language_id=$GLOBALS["langcode"];
			$retval = array();
			foreach ($article_ids as $article_id) {
				$item = array(
					"article" => $this->getArticleFromId( $article_id ),
					"larticle" => $this->getLanguageArticle( $article_id , $site_language_id )
				);
				if ($associative) {
					$retval[$article_id]=$item;
				} else {
					$retval[]=$item;
				}
			}
			return $retval;
		}

		public function setLanguageArticles( $article_id , $datas ) {
			// FNTH_da( $datas );
			foreach ($datas as $site_language_id => $data) {
				$this->setLanguageArticle( $article_id , $site_language_id , $data );
			}
		}
		public function deleteArticle( $article_id ) {
			FNTH_db_free_result(
				FNTH_db_query( sprintf( "select sp_delete_article( %d )" , $article_id ) ) );
		}

		public function explodeLead( $article_body = "" ) {
			$retval = explode( "<hr class=\"hrlead\" />" , $article_body );
			return $retval;
		}

		public function explodeBody( $article_body = "" ) {
			$retval = array();

			$len = strlen( $article_body );
			$bsep = "<div class=\"divpagebreak\">";
			$esep = "</div>";

			$offset = 0;
			$body = "";
			$subtitle = "";

			$pos = strpos( $article_body , $bsep , $offset );

			while ($pos!==false) {
				$body = substr( $article_body , $offset , $pos - $offset );
				$pos+=strlen( $bsep );
				$epos = strpos( $article_body , $esep , $pos );

				if ($epos===false) return false;
				$retval[]=array(
					"subtitle" => $subtitle,
					"body" => $body );
				$subtitle = substr( $article_body , $pos , $epos - $pos );
				$offset = $epos;
				$pos = strpos( $article_body , $bsep , $offset );
			}
			$body = substr( $article_body , $offset );
			$retval[]=array(
				"subtitle" => $subtitle,
				"body" => $body );
			return $retval;
		}

		public function getArticleIdFromURL( $url , $site_language_id ) {
			$pn = 0;
			// extract url
			$e = explode( "/" , $url );
			$len = count( $e );
			if ($len>=2) {
				$x = $e[$len-2];
				if (is_numeric( $x )) {
					$pn = $x-1;
					array_pop( $e );
					array_pop( $e );
					array_push( $e , "" );
					$url = implode( "/" , $e );
				}
			}
		
			$query = sprintf( "select article_id from larticles where larticle_url='%s' and site_language_id=%d",
				FNTH_db_addslashes( $url ),
				$site_language_id );
			$retval = FNTH_db_get_field( $query , "article_id" );
			if (!$retval) return false;
			return array( "article_id" => $retval , "pagenum" => $pn );
		}

		public function getLatestArticleFromCategory( $category , $site_language_id ) {
			$category_filter = (is_array( $category )) ? sprintf( "in (%s)" , implode( "," , $category ) ) : sprintf( "=%d",$category );
			$query = sprintf( "select * from articles where article_category_id %s and article_publication_tstamp<now() order by article_publication_tstamp desc limit 1",
				$category_filter );
			$retval = FNTH_db_get_row( $query );
			$query = sprintf( "select * from larticles where article_id=%d and site_language_id=%d" , $retval["article_id"] , $site_language_id );
			$retval["larticle"]=$this->prepareLanguageArticle( FNTH_db_get_row( $query ) );
			return $retval;
		}

		public function getLatestArticlesFromCategories( $categories , $site_language_id = 0 ) {
			$retval = array();
			foreach ($categories as $category) {
				$retval[]=$this->getLatestArticleFromCategory( $category , $site_language_id );
			}
			return $retval;
		}

		public function isUrlUsed( $url , $exclude_article_ids = array() ) {
			$filters = array();
			$filters["is_url_used"]="is_url_used";
			if (!empty( $exclude_article_ids )) {
				$filters["exclude"]=sprintf( "article_id not in (%s)",implode( "," , $exclude_article_ids ));
			}

			$filters["url"]=sprintf( "article_url='%s'" , FNTH_db_addslashes( $url ) );
			$where_clause = " where " . implode( " and " , $filters );
			$query = sprintf( "select count(*) as num from articles %s" , $where_clause );
			$retval = FNTH_db_get_field( $query , "num" );
			if ($retval>0) return true;

			// regenerate where clause
			$filters["url"]=sprintf( "larticle_url='%s'" , FNTH_db_addslashes( $url ) );
			$where_clause = " where " . implode( " and " , $filters );
			$query = sprintf( "select count(*) as num from larticles %s" , $where_clause );
			$retval = FNTH_db_get_field( $query , "num" );
			if ($retval>0) return true;
			return false;
		}

		public function addArticleConnection( $p ) {
			$ins = array();
			$ins["source_article_id"]=sprintf( "%d" , $p["source_article_id"] );
			$ins["target_article_id"]=sprintf( "%d" , $p["target_article_id"] );
			$ins["bidirectional"]=($p["bidirectional"]) ? "true" : "false";
			FNTH_db_free_result( FNTH_db_query(
				FNTH_db_generate_insert_query( "article_connections" , $ins ) ) );
			return FNTH_db_get_field( sprintf( "select currval('article_connections_article_connection_id_seq') as num" ) , "num" );
		}
		
		public function updateArticleConnection( $uid , $p ) {
			$ins = array();
			$ins["source_article_id"]=sprintf( "%d" , $p["source_article_id"] );
			$ins["target_article_id"]=sprintf( "%d" , $p["target_article_id"] );
			$ins["bidirectional"]=($p["bidirectional"]) ? "true" : "false";
			FNTH_db_free_result( FNTH_db_query(
				FNTH_db_generate_update_query( "article_connections" , $ins , sprintf( "article_connection_id=%d" , $uid ) ) ) );
			return $uid;
		}

		public function deleteArticleConnection( $uid ) {
			FNTH_db_free_result( FNTH_db_query(
				sprintf( "delete from article_connections where article_connection_id=%d" , $uid ) ) );
		}

		public function getConnectedArticles( $uid , $langcode = 1 ) {
			$query = sprintf( "select target_article_id as article_id from article_connections where source_article_id=%d
				union
				select source_article_id as article_id from article_connections where target_article_id=%d and bidirectional" , $uid , $uid );
			$article_ids = FNTH_db_get_column( $query , "article_id" );
			if (empty( $article_ids )) return $article_ids;
			$retval = array();
			foreach ($article_ids as $article_id) {
				$retval[]=$this->getLanguageArticle( $article_id , $langcode );
			}
			return $retval;
		}
	}

?>
