<?php
/**
 * blogList
 *
 * @category	Anova
 * @package
 * @author 		selvaraj_47ag04
 * @copyright 	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2008-12-19
 **/
class blogList extends AnovaHandler
	{
		public $paging_arr;
		public $search_page = false;

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function setSearchPage()
			{
				$this->search_page = true;
			}
		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function  storeSearchFields()
			{
				$allowed_fields_arr = array(
										'subject'=>$this->fields_arr['subject'],
										'dname'=>$this->fields_arr['dname'],
										'date_limits_to'=>$this->fields_arr['date_limits_to'],
										);
				$allowed_fields_arr = serialize($allowed_fields_arr);

				if($this->CFG['user']['user_id'] != 0)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['advanced_search'].' SET'.
								' blog = '.$this->dbObj->Param('blog').' WHERE'.
								' user_id = '.$this->dbObj->Param('user_id');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($allowed_fields_arr, $this->CFG['user']['user_id']));
							if (!$rs)
								trigger_db_error($this->dbObj);
					}
				else
					{
							$_SESSION['advanced_search_values_for_blogs'] = 	$allowed_fields_arr;
					}

					//to fix search top box value populate..
					$_SESSION['subject'] = $this->fields_arr['subject'];
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function  populateSearchFields()
			{
				if($this->fields_arr['so']=='adv')
					{
						if($this->CFG['user']['user_id'] != 0)
							{
								$sql = 'SELECT blog FROM '.$this->CFG['db']['tbl']['advanced_search'].
										' WHERE user_id='.$this->dbObj->Param('user_id');

								$stmt = $this->dbObj->Prepare($sql);
								$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
									if (!$rs)
										trigger_db_error($this->dbObj);

								if($row = $rs->FetchRow())
									{
										if($row['blog'])
											{
												$search_fields_arr = unserialize($row['blog']);

												$this->fields_arr = array_merge($this->fields_arr, $search_fields_arr);
											}
									}
							}
						else
							{
								if(isset($_SESSION['advanced_search_values_for_blogs']) and !empty($_SESSION['advanced_search_values_for_blogs']))
									{
											$search_fields_arr = unserialize($_SESSION['advanced_search_values_for_blogs']);
											$this->fields_arr = array_merge($this->fields_arr, $search_fields_arr);
									}
							}
							//to fix search top box value populate..
							$_SESSION['subject'] = $this->fields_arr['subject'];
					}
			}

		/**
		 * blogList::buildSortQuery()
		 *
		 * @return
		 **/
		public function buildSortQuery()
			{
				$this->sql_sort = $this->fields_arr['orderby_field'].' '.$this->fields_arr['orderby'];
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function  buildConditionQuery()
			{
				$this->sql_condition = 'status=\'Active\' AND usr_status=\'Ok\'';
				if($this->getFormField('pg'))
					{
						if($this->getFormField('pg')=='newblog')
							{
								$this->setFormField('orderby_field', 'date_added');
								$this->setFormField('orderby', 'DESC');
							}
						if($this->getFormField('pg')=='mostviewblog')
							{
								$this->sql_condition .= ' AND total_views > 0';
								$this->setFormField('orderby_field', 'total_views');
								$this->setFormField('orderby', 'DESC');
							}

						$this->paging_arr[] = 'pg';
					}
				if($this->getFormField('cid'))
					{
						$this->sql_condition .= ' AND blog_category_id = \''.addslashes($this->getFormField('cid')).'\'';
						$this->paging_arr[] = 'cid';
					}
				if ($this->CFG['admin']['ignore_user'])
					{
						$this->sql_condition .= ' AND NOT EXISTS (SELECT 1 FROM '.$this->CFG['db']['tbl']['user_ignored'].' AS ui WHERE ui.user_id='.$this->CFG['user']['user_id'].' AND ui.ignored_id=b.user_id)';
					}
				//for simple search
				if($this->fields_arr['search_blog_subject'] && ($this->fields_arr['search_blog_subject'] != $this->LANG['search_for_blog_subject']))
					{
						$this->sql_condition .= ' AND '.getSearchRegularExpressionQuery($this->fields_arr['search_blog_subject'], 'subject');
						if($this->getFormField('search_blog_subject')!='')
						$this->paging_arr[] = 'search_blog_subject';
					}
				//for advanced search
				if($this->fields_arr['subject'])
					{
						$this->sql_condition .= ' AND '.getSearchRegularExpressionQuery($this->fields_arr['subject'], 'subject');
						$this->paging_arr[] = 'subject';
					}
				if ($this->fields_arr['dname'])
					{
						$this->sql_condition .= ' AND u.'.$this->getUserTableField('display_name').' LIKE \''.addslashes($this->fields_arr['dname']).'%\'';
						$this->paging_arr[] = 'dname';
					}
				if ($this->fields_arr['uname'])
					{
						$this->sql_condition .= ' AND u.'.$this->getUserTableField('name').' LIKE \''.addslashes($this->fields_arr['uname']).'%\'';
						$this->paging_arr[] = 'uname';
					}
				if ($this->fields_arr['uid'])
					{
						$this->sql_condition .= ' AND b.user_id=\''.$this->fields_arr['uid'].'\'';
						$this->paging_arr[] = 'uid';
					}
				if ($this->fields_arr['category'])
					{
						$this->sql_condition .= ' AND blog_category_id='.$this->fields_arr['category'];
						$this->paging_arr[] = 'category';
					}

				switch($this->fields_arr['date_limits_to'])
					{
						case $this->LANG['search_option_today']:
							$date_condtion = 'date( b.date_added ) = date( now( ) )';
							break;
						case $this->LANG['search_option_oneday']:
							$date_condtion = 'DATE_ADD(b.date_added, INTERVAL 1 DAY) >= NOW()';
							break;
						case $this->LANG['search_option_oneweek']:
							$date_condtion = 'DATE_ADD(b.date_added, INTERVAL 7 DAY) >= NOW()';
							break;
						case $this->LANG['search_option_onemonth']:
							$date_condtion = 'DATE_ADD(b.date_added, INTERVAL 1 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_threemonths']:
							$date_condtion = 'DATE_ADD(b.date_added, INTERVAL 3 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_sixmonths']:
							$date_condtion = 'DATE_ADD(b.date_added, INTERVAL 6 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_oneyear']:
							$date_condtion = 'DATE_ADD(b.date_added, INTERVAL 1 YEAR) >= NOW()';
							break;
						default:
							$date_condtion = 'b.date_added <= NOW()';
							break;
					}
					if($this->getFormField('date_limits_to')!='')
						$this->paging_arr[] = 'date_limits_to';
					$this->sql_condition .= ' AND '.$date_condtion;
			}

		/**
		 * blogList::showBlogsList()
		 *
		 * @return
		 **/
		public function showBlogsList()
			{
				$i = 0;
				$showBlogsList_array = array();
				while($row = $this->fetchResultRecord())
					{
						$i++;

						$clsOddOrEvenQuestion = 'clsEvenQuestion';
						if ($i%2)
							$clsOddOrEvenQuestion = 'clsOddQuestion';

						$row['date_added'] = ($row['date_added'] != '') ? getTimeDiffernce($row['date_added']) : '';

						$name = $row['display_name'];
						$message = strip_tags($row['message']);
						$message = (strlen($message)>$this->CFG['admin']['short_description_size'])?(substr($message, 0, $this->CFG['admin']['short_description_size']-1).' ..'):($message);

						$showBlogsList_array[$i]['record'] =  $row;
						$showBlogsList_array[$i]['clsOddOrEvenQuestion'] =  $clsOddOrEvenQuestion;
						$showBlogsList_array[$i]['wrappedsubject'] =  wordWrapManual($row['subject'], $this->CFG['admin']['blog']['line_length'], $this->CFG['admin']['blog']['total_length']);
						$showBlogsList_array[$i]['wrappedmessage'] =  wordWrapManual($message, $this->CFG['admin']['blog']['line_length'], $this->CFG['admin']['blog']['total_length']);
						$showBlogsList_array[$i]['strippedname'] =  stripString($name, $this->CFG['username']['short_length']);
						$showBlogsList_array[$i]['blogcategoryname'] =  $this->getBlogCategory($row['blog_category_id']);
						$showBlogsList_array[$i]['accept_comments_yes_no'] =  ($row['accept_comments']=='Yes')?$this->LANG['common_yes_option']:$this->LANG['common_no_option'];
						$showBlogsList_array[$i]['blog_url'] =  getBlogUrl('blogcomment', '?title='.$row['seo_title'], $row['seo_title'].'/');
						$showBlogsList_array[$i]['blog_post_url'] =  getBlogUrl('blogcomment', '?title='.$row['seo_title'].'&amp;post=1', $row['seo_title'].'/?post=1');
						$showBlogsList_array[$i]['user_url'] =  getMemberUrl($row['user_id'], $row['name']);

						$showBlogsList_array[$i]['separator_class'] = 'clsNoLeftBgPadngMrgn';
						if((chkVideoModuleAllowed('blog') AND $row['video_id'])
							OR (chkAudioModuleAllowed('blog') AND $row['audio_id'])
							OR (chkExternalVideoModuleAllowed('blog') AND $row['external_video_id'])
							OR (chkExternalAudioModuleAllowed('blog') AND $row['external_audio_id']))
							{
								$showBlogsList_array[$i]['separator_class'] = '';
							}

						$showBlogsList_array[$i]['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Blog_'.$row['video_id'], '?pg=Blog_'.$row['video_id']);
						$showBlogsList_array[$i]['ans_view_video']['on_click'] = 'blog_video_'.$row['video_id'];

						$showBlogsList_array[$i]['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Blog_'.$row['audio_id'], '?pg=Blog_'.$row['audio_id']);
						$showBlogsList_array[$i]['ans_view_audio']['on_click'] = 'blog_audio_'.$row['audio_id'];

						$showBlogsList_array[$i]['ext_ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Blog_'.$row['external_video_id'], '?pg=Blog_'.$row['external_video_id']);
		  				$showBlogsList_array[$i]['ext_ans_view_video']['on_click'] = 'external_video_blog_'.$row['external_video_id'];

						$showBlogsList_array[$i]['ext_ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Blog_'.$row['external_audio_id'], '?pg=Blog_'.$row['external_audio_id']);
						$showBlogsList_array[$i]['ext_ans_view_audio']['on_click'] = 'external_audio_blog_'.$row['external_audio_id'];
					}
				return $showBlogsList_array;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function populateCategories()
		    {
				$sql = 'SELECT blog_category_id, blog_category_name FROM '.$this->CFG['db']['tbl']['blog_category'].' WHERE blog_category_status=\'Yes\' ORDER BY blog_category_name';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$populateCategories_array = array();
				if ($rs->PO_RecordCount())
					{
						while($row = $rs->FetchRow()){
							$populateCategories_array[$row['blog_category_id']] = $row['blog_category_name'];
						} // while
					}
				return $populateCategories_array;
		    }

	}

//--------------------Code begins-------------->>>>>//
$blogList = new blogList();
if(!$blogList->chkAllowedModule(array('blog')))
	Redirect2URL(getUrl($CFG['redirect']['dsabled_module_url']['file_name']));

//set blocks
$blogList->setPageBlockNames(array('form_advanced_search', 'selBlogsListBlock'));
/*********** Page Navigation Start *********/
$blogList->setFormField('orderby_field', 'blog_id');
$blogList->setFormField('orderby', 'DESC');
$blogList->setFormField('start', '0');
$blogList->setFormField('pg','');
$blogList->setFormField('cid','');
$blogList->setFormField('search_blog_subject','');
$blogList->setFormField('uname', '');
$blogList->setFormField('dname', '');
$blogList->setFormField('uid', '');
$blogList->setFormField('category', '');
$blogList->setFormField('subject', '');
$blogList->setFormField('date_limits_to', '');
$blogList->setFormField('adv_search', '');
$blogList->setFormField('so', 'min');
$blogList->setFormField('comments', '');

$blogList->search_title['page_title'] = $LANG['page_title'];
$blogList->search_title['href'] = false;
$title = $LANG['page_title'];
$blogList->searchOption_arr = array($LANG['search_option_allresult'] => $LANG['search_option_allresult'],
								  $LANG['search_option_today'] => $LANG['search_option_today'],
								  $LANG['search_option_oneday'] => $LANG['search_option_oneday'],
								  $LANG['search_option_oneday'] => $LANG['search_option_oneday'],
								  $LANG['search_option_oneweek'] => $LANG['search_option_oneweek'],
								  $LANG['search_option_onemonth'] => $LANG['search_option_onemonth'],
								  $LANG['search_option_threemonths'] => $LANG['search_option_threemonths'],
								  $LANG['search_option_sixmonths'] => $LANG['search_option_sixmonths'],
								  $LANG['search_option_oneyear'] => $LANG['search_option_oneyear']);

$blogList->setMinRecordSelectLimit(2);
$blogList->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$blogList->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);

$blogList->setTableNames(array($CFG['db']['tbl']['blogs'].' AS b LEFT JOIN '.$CFG['db']['tbl']['users'].' AS u ON b.user_id=u.'.$CFG['users']['user_id']));
$return_fields = array('blog_id', 'subject', 'seo_title', 'message', 'accept_comments', 'blog_category_id', 'total_comments', 'total_views', 'b.user_id', 'status', 'UNIX_TIMESTAMP(date_added) as date_added', 'video_id', 'audio_id', 'external_video_id', 'external_audio_id');

if($blogList->getUserTableField('name'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('name').' AS name';
	}
if($blogList->getUserTableField('display_name'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('display_name').' AS display_name';
	}
if($blogList->getUserTableField('email'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('email').' AS email';
	}
if($blogList->getUserTableField('image_path'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('image_path').' AS image_path';
	}
if($blogList->getUserTableField('gender'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('gender').' AS gender';
	}
if($blogList->getUserTableField('usr_status'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('usr_status').' AS usr_status';
	}
if($blogList->getUserTableField('user_access'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('user_access').' AS user_access';
	}
if($blogList->getUserTableField('user_id'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('user_id').' AS img_user_id';
	}
if($blogList->getUserTableField('t_height'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('t_height').' AS t_height';
	}
if($blogList->getUserTableField('t_width'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('t_width').' AS t_width';
	}
if($blogList->getUserTableField('s_height'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('s_height').' AS s_height';
	}
if($blogList->getUserTableField('s_width'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('s_width').' AS s_width';
	}
if($blogList->getUserTableField('photo_server_url'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('photo_server_url').' AS photo_server_url';
	}
if($blogList->getUserTableField('photo_ext'))
	{
		$return_fields[] = 'u.'.$blogList->getUserTableField('photo_ext').' AS photo_ext';
	}

$blogList->setReturnColumns($return_fields);

$blogList->setFormField('numpg', $CFG['data_tbl']['numpg']);
/************ page Navigation stop *************/

//show default pages
$blogList->setPageBlockShow('selBlogsListBlock');

$blogList->sanitizeFormInputs($_REQUEST);

if ($blogList->getFormField('comments') == 'more')
	{
		$blogList->search_title['page_title'] = $LANG['most_comments_blogs'];
		$blogList->setFormField('orderby_field', 'total_comments');
		$blogList->setFormField('orderby', 'DESC');
	}
if($blogList->isFormPOSTed($_REQUEST, 'adv_search') or $blogList->getFormField('search_blog_subject'))
	{
		$blogList->search_title['page_title'] = '- '.$LANG['search_results'];
		$blogList->search_title['href_text'] = $LANG['blogs'];
		$blogList->search_title['href'] = getBlogUrl('blogs');
	}
if($blogList->isFormPOSTed($_GET, 'added'))
	{
		if($CFG['admin']['blogs_auto_publish']['allowed'])
			$blogList->setCommonSuccessMsg($LANG['manageBlog_msg_success_added']);
		else
			$blogList->setCommonSuccessMsg($LANG['manageBlog_msg_success_added_publish']);
		$blogList->setPageBlockShow('block_msg_form_success');
	}
if($blogList->getFormField('so')=='adv' and !$blogList->isFormPOSTed($_REQUEST, 'adv_search'))
	{
		$blogList->populateSearchFields();
		$blogList->setPageBlockHide('selBlogsListBlock');
		$blogList->setPageBlockShow('form_advanced_search');
	}
if($blogList->isFormGETed($_GET, 'adv_search'))
	{
		$blogList->populateSearchFields();
		$blogList->setAllPageBlocksHide();
		$blogList->setPageBlockShow('selBlogsListBlock');
	}
if($blogList->getFormField('uname')!='')
	{

		$bloglist_name = $blogList->getUsersDisplayName($blogList->getFormField('uname'));
		$title = $bloglist_name.'\'s '.$LANG['page_title'];

		$blogList->search_title['page_title'] = '- '.$bloglist_name.' - '.$LANG['page_title'];
		$blogList->search_title['href_text'] = $LANG['blogs_title_index'];
		$blogList->search_title['href'] = getBlogUrl('blogs');

		if($CFG['user']['user_id'])
			{
				if($CFG['user']['display_name'] == $bloglist_name)
					{
						$title = $LANG['page_mytitle'];
						$blogList->search_title['page_title'] = '- '.$LANG['page_mytitle'];
						$blogList->search_title['href_text'] = $LANG['blogs_title_index'];
						$blogList->search_title['href'] = getBlogUrl('blogs');
					}
			}
	}
if($blogList->isFormGETed($_GET, 'succ'))
	{
		$blogList->setPageBlockShow('block_msg_form_success');
		$blogList->setCommonSuccessMsg($LANG['blog_deleted_successfully']);
	}

if($blogList->isFormPOSTed($_POST, 'adv_search'))
	{
		$blogList->setSearchPage();
		if ($blogList->isValidFormInputs())
			{
				$blogList->storeSearchFields();
			}
		else
			{
				$blogList->setPageBlockHide('selBlogsListBlock');
				$blogList->setPageBlockShow('form_advanced_search');
				$blogList->setPageBlockShow('block_msg_form_error');
				$blogList->setCommonErrorMsg($LANG['err_msg_invalid_search_option']);
			}
	}
if(!$blogList->isFormGETed($_GET, 'search_blog_subject'))
	 {
		   $_SESSION['search_blog_subject'] = $LANG['header_search_for_blog_subject'];
	 }
if($blogList->isFormPOSTed($_POST, 'search'))
	 {
		   $_SESSION['search_blog_subject'] = $blogList->getFormField('search_blog_subject');
		   $blogList->setSearchPage();
	 }
if($blogList->isFormGETed($_GET, 'search_blog_subject'))
	 {
			    if(isset($_SESSION['search_blog_subject']) and $_SESSION['search_blog_subject'])
				    $blogList->setFormField('search_blog_subject', $_SESSION['search_blog_subject']);
	 }
if($blogList->isShowPageBlock('form_advanced_search'))
	{

		$blogList->search_title['page_title'] = '- '.$LANG['advanced_search'];
		$blogList->search_title['href_text'] = $LANG['blogs_title_index'];
		$blogList->search_title['href'] = getBlogUrl('blogs');
	}
//<<<<--------------------Code Ends----------------------//

//--------------------Page block templates begins-------------------->>>>>//

if ($blogList->isShowPageBlock('form_advanced_search'))
	{
		$blogList->form_advanced_search['populateCategories'] = $blogList->populateCategories();
	}
if($blogList->isShowPageBlock('selBlogsListBlock'))
	{
		/****** navigtion continue*********/
		$blogList->buildSelectQuery();
		$blogList->buildConditionQuery();
		$blogList->buildSortQuery();
		$blogList->buildQuery();
		$blogList->executeQuery();

		if($blogList->isResultsFound())
			{
				$blogList->paging_arr[] = 'so';
				if($blogList->getFormField('adv_search'))
					$blogList->paging_arr[] = 'adv_search';
				if($blogList->getFormField('comments'))
					$blogList->paging_arr[] = 'comments';

				$smartyObj->assign('smarty_paging_list', $blogList->populatePageLinksGET($blogList->getFormField('start'), $blogList->paging_arr));
				$blogList->selBlogsListBlock['showBlogsList'] = $blogList->showBlogsList();
			}
		else
			{
				$blogList->site_name_manual =  str_ireplace('VAR_SITENAME', $CFG['site']['name'], $LANG['blogs_no_search_results']);
			}
	}
$blogList->advanced_search_action = getBlogUrl('blogs', '?so=adv', '?so=adv');
//include the header file
$blogList->includeHeader();
//include the content of the page
setTemplateFolder('general/', $CFG['admin']['index']['blog_module']);
$smartyObj->display('blogs.tpl');
//includ the footer of the page
//<<<<<<--------------------Page block templates Ends--------------------//
$blogList->includeFooter();
?>
