<?php
/**
 * Adodis Blog package
 * @author J-Extension <contact@jextn.com>
 * @link http://www.jextn.com
 * @copyright (C) 2012 - 2013 J-Extension
 * @license GNU/GPL, see LICENSE.php for full license.
**/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.modeladmin');

class AdodisBlogModelBlog extends JModelAdmin
{
		/**
	 * Method to test whether a record can be deleted.
	 */
	protected function canDelete($record)
	{
		$user = JFactory::getUser();

		if ($record->catid) {
			return $user->authorise('core.delete', 'com_adodisblog.blog.'.(int) $record->catid);
		} else {
			return parent::canDelete($record);
		}
	}

	/**
	 * Method to test whether a record can be deleted.
	 */
	protected function canEditState($record)
	{
		$user = JFactory::getUser();

		// Check against the category.
		if (!empty($record->catid)) {
			return $user->authorise('core.edit.state', 'com_adodisblog.blog.'.(int) $record->catid);
		}
		// Default to component settings if category not known.
		else {
			return parent::canEditState($record);
		}
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 */
	public function getTable($type = 'Blog', $prefix = 'AdodisBlogTable', $config = array())
{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the row form.
	 */
	public function getForm($data = array(), $loadData = true)
	{
		jimport('joomla.form.form');

		// Get the form.
		$form	= $this->loadForm('com_adodisblog.blog', 'blog', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		// Modify the form based on access controls.
		if (!$this->canEditState((object) $data)) {
			// Disable fields for display.
			$form->setFieldAttribute('ordering', 'disabled', 'true');
			$form->setFieldAttribute('published', 'disabled', 'true');
			$form->setFieldAttribute('access', 'disabled', 'true');
			$form->setFieldAttribute('language', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is a record you can edit.
			$form->setFieldAttribute('ordering', 'filter', 'unset');
			$form->setFieldAttribute('published', 'filter', 'unset');
			$form->setFieldAttribute('access', 'filter', 'unset');
			$form->setFieldAttribute('language', 'filter', 'unset');
		}

		return $form;
	}

	/**
	 * Method to get a single record.
	 */
	public function getItem($pk = null)
	{
		$item = parent::getItem($pk);

		return $item;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data			= JFactory::getApplication()->getUserState('com_adodisblog.edit.blog.data', array());

		if (empty($data)) {
			$data 		= $this->getItem();

			// Prime some default values.
			if ($this->getState('blog.id') == 0) {
				$app 	= JFactory::getApplication();
				$data->set('catid', JRequest::getInt('catid', $app->getUserState('com_adodisblog.blogs.filter.category_id')));
			}
		}

		return $data;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 */
	protected function prepareTable(&$table)
	{
		jimport('joomla.filter.output');
		$date 						= JFactory::getDate();
		$user 						= JFactory::getUser();

		if (empty($table->id)) {
			// Set ordering to the last item if not set
			if (empty($table->ordering)) {
				$db 				= JFactory::getDbo();
				$db->setQuery('SELECT MAX(ordering) FROM #__adodisblog_blogs');
				$max 				= $db->loadResult();

				$table->ordering 	= $max+1;
			}
		} else {
			// Set the values
			$table->modified_date	= $date->toMySQL();
			$table->modified_by		= $user->get('username');
		}
	}

	/**
	 * A protected method to get a set of ordering conditions.
	 */
	protected function getReorderConditions($table)
	{
		$condition		= array();
		$condition[]	= 'catid = '.(int) $table->catid;
		$condition[]	= 'published >= 0';

		return $condition;
	}

	public function reorder($pks, $delta = 0)
	{
		// Clear the component's cache
		$cache = JFactory::getCache();
		$cache->clean('com_adodisblog');

		return parent::reorder($pks, $delta);
	}

	public function mailtoAdmin( $email, $name, $catid, $published )
	{
		$app				= JFactory::getApplication();
		$config				= JComponentHelper::getParams('com_adodisblog');
		$id					= $catid;
		$urladmin			= JURI::ROOT().'administrator/index.php?option=com_adodisblog&view=blog&layout=edit&id='.$id;
		$urladmin 			= '<a href="'.$urladmin.'" target="_blank">'.$urladmin.'</a>';
		$urlsite			= 'http://'.$_SERVER['SERVER_NAME'].JRoute::_('index.php?option=com_adodisblog&view=blog&id='.$id);
		$urlsite 			= '<a href="'.$urlsite.' " target="_blank">'.$urlsite.'</a>';
		$to					= $app->getCfg('mailfrom');
		$sett_to			= $config->get('emailid');

		if ( $sett_to == 'admin@emailid.com' || $sett_to == '' ) {
			$to				= $app->getCfg('mailfrom');  //outputs mailfrom
		} else {
			$to				= $sett_to;
		}

		$from				= $email;
		$name				= $name;
		$site				= $app->getCfg('sitename'); //outputs sitename

		$sender 			= array( $from, $name );
		$mailer 			= & JFactory::getMailer();
		$mailer->setSender( $sender );
		$mailer->addRecipient( $to );

		$temp_obj 			= $this->getSettings();
		$template 			= $temp_obj->mail_admin_temp;

		if($published==1){
			$publish 		= "Published";
		}
		if($published==0){
			$publish 		= "unpublished";
		}

		$replace_link_a		= "admin-link";
		$replace_link_u		= "site-link";
		$replace_blog		= "blog/comment";
		$replace_uname		= "username";
		$replace_published	= "published/unpublished";
		$template			= str_replace("[".$replace_link_a."]", $urladmin, $template);
		$template			= str_replace("[".$replace_link_u."]", $urlsite, $template);
		$template			= str_replace("[".$replace_blog."]", "Blog", $template);
		$template			= str_replace("[".$replace_uname."]", $name, $template);
		$template			= str_replace("[".$replace_published."]", $publish , $template);
		$message			= $template;

		if($temp_obj->mail_admin_sub) {
			$subject 		= str_replace("[b/c]", "Blog", $temp_obj->mail_admin_sub);
		} else {
			$subject 		= sprintf ( JText::_( 'ADODIS_BLOG_MAIL_SUBJECT' ), $name );
		}

		$subject 			= html_entity_decode($subject, ENT_QUOTES);
		$message 			= html_entity_decode($message, ENT_QUOTES);

		$mailer->setSubject( $subject );
		$mailer->setBody( $message );

		$mailer->IsHTML(true);

		if ($mailer->Send() == true) {
			return true;
		} else {
			return false;
		}
	}

	public function mailtoUser( $email, $name, $catid, $published )
	{
		$app				= JFactory::getApplication();
		$config				= JComponentHelper::getParams('com_adodisblog');
		$id					= $catid;
		$urlsite			= 'http://'.$_SERVER['SERVER_NAME'].JRoute::_('index.php?option=com_adodisblog&view=blog&id='.$id);
		$urlsite 			= '<a href="'.$urlsite.' " target="_blank">'.$urlsite.'</a>';
		$from					= $app->getCfg('mailfrom');
		$sett_to			= $config->get('emailid');

		if ( $sett_to == 'admin@emailid.com' || $sett_to == '' ) {
			$from			= $app->getCfg('mailfrom');  //outputs mailfrom
		} else {
			$from			= $sett_to;
		}
		$to					= $email;
		$name				= $name;
		$site				= $app->getCfg('sitename'); //outputs sitename

		$sender 			= array( $from, $name );
		$mailer 			= & JFactory::getMailer();
		$mailer->setSender( $sender );
		$mailer->addRecipient( $to );

		$temp_obj 			= $this->getSettings();
		$template 			= $temp_obj->mail_user_temp;

		if($published==1){
			$publish 		= "Published";
		}
		if($published==0){
			$publish 		= "unpublished";
		}

		$replace_link_u		= "site-link";
		$replace_blog		= "blog/comment";
		$replace_uname		= "username";
		$replace_published	= "published/unpublished";
		$template			= str_replace("[".$replace_link_u."]", $urlsite, $template);
		$template			= str_replace("[".$replace_blog."]", "Blog", $template);
		$template			= str_replace("[".$replace_uname."]", $name, $template);
		$template			= str_replace("[".$replace_published."]", $publish , $template);
		$message			= $template;

		if($temp_obj->mail_admin_sub) {
			$subject 		= str_replace("[b/c]", "Blog", $temp_obj->mail_user_sub);
		} else {
			$subject 		= sprintf ( JText::_( 'ADODIS_BLOG_MAIL_SUBJECT' ), $name );
		}

		$subject 			= html_entity_decode($subject, ENT_QUOTES);
		$message 			= html_entity_decode($message, ENT_QUOTES);

		$mailer->setSubject( $subject );
		$mailer->setBody( $message );

		$mailer->IsHTML(true);

		if ($mailer->Send() == true) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Get the category name.
	 */
	protected function getCategoryName( $catid )
	{
		if ($catid) {
			$db			= $this->getDbo();
			$query		= $db->getQuery(true);
			$query->select('title');
			$query->from('`#__categories`');
			$query->where('`id`='.$db->quote($catid));
			$db->setQuery((string)$query);
			$name		= $db->loadResult();

			if ($db->getErrorNum()) {
				$this->setError($db->getErrorMsg());
				return false;
			}
		} else {
			$name		= JText::_('COM_BANNERS_NOCATEGORYNAME');
		}

		return $name;
	}

	public function getSettings()
	{
		$id				= 1;
		$settings  		= JTable::getInstance('Settings', 'AdodisBlogTable');
		$settings->load($id);

		return $settings;
	}

	public function AddToJoomSocial($ur, $id, $title, $content, $created)
	{
		$data 				= new stdClass();
		$data->id 			= null;
		$data->actor 		= $ur;
		$data->title 		= $title;
		if(strlen($content)>200){
			$content 		= substr($content,0,200)."...";
			} else {
				$content 	= $content;
				}
		$cr					='<a href="'.JRoute::_(AdodisBlogHelperRoute::getBlogRoute($id)).'">Read Full Blog</a>';
		$data->content 		= $cr." ".$content;
		$data->app 			= 'com_adodisblog';
		$data->created 		= $created;
		$db 				= JFactory::getDBO();
		$db->insertObject( '#__community_activities', $data, id );
	}

	public function AddToK2($ur, $id, $title, $content, $created)
	{
		$k2CatId 			= $this->getK2CategoryId();
		if(empty($k2CatId)){
			$k2CatId 		= $this->AddToK2Category();
		}
		$data 				= new stdClass();
		$data->id 			= null;
		$data->created_by 	= $ur;
		$data->title 		= $title;
		$data->published 	= 1;
		if(strlen($content)>200){
			$content 		= substr($content,0,200)."...";
			} else {
				$content	= $content;
				}
		$cr					='<a href="'.JRoute::_(AdodisBlogHelperRoute::getBlogRoute($id)).'">Read Full Blog</a>';
		$data->introtext 	= $cr." ".$content;
		$data->created 		= $created;
		$data->catid 		= $k2CatId;
		$data->access 		= 1;
		$data->ordering 	= 1;

		$db 				= JFactory::getDBO();
		$db->insertObject( '#__k2_items', $data, id );
	}

	public function AddToK2Category()
	{
		$dataC 					= new stdClass();
		$dataC->id 				= null;
		$dataC->name  			= 'adodisblog';
		$dataC->alias 			= 'adodisblog';
		$dataC->description 	= '<p>The blogs which is posted in Adodis Blog will comes under this Category.</p>';
		$dataC->published 		= 1;
		$dataC->access 			= 1;
		$dataC->ordering 		= 1;
		$dataC->params			= '{"inheritFrom":"0","theme":"","num_leading_items":"2","num_leading_columns":"1","leadingImgSize":"Large","num_primary_items":"4","num_primary_columns":"2","primaryImgSize":"Medium","num_secondary_items":"4","num_secondary_columns":"1","secondaryImgSize":"Small","num_links":"4","num_links_columns":"1","linksImgSize":"XSmall","catCatalogMode":"0","catFeaturedItems":"1","catOrdering":"","catPagination":"2","catPaginationResults":"1","catTitle":"1","catTitleItemCounter":"1","catDescription":"1","catImage":"1","catFeedLink":"1","catFeedIcon":"1","subCategories":"1","subCatColumns":"2","subCatOrdering":"","subCatTitle":"1","subCatTitleItemCounter":"1","subCatDescription":"1","subCatImage":"1","itemImageXS":"","itemImageS":"","itemImageM":"","itemImageL":"","itemImageXL":"","catItemTitle":"1","catItemTitleLinked":"1","catItemFeaturedNotice":"0","catItemAuthor":"1","catItemDateCreated":"1","catItemRating":"0","catItemImage":"1","catItemIntroText":"1","catItemIntroTextWordLimit":"","catItemExtraFields":"0","catItemHits":"0","catItemCategory":"1","catItemTags":"1","catItemAttachments":"0","catItemAttachmentsCounter":"0","catItemVideo":"0","catItemVideoWidth":"","catItemVideoHeight":"","catItemAudioWidth":"","catItemAudioHeight":"","catItemVideoAutoPlay":"0","catItemImageGallery":"0","catItemDateModified":"0","catItemReadMore":"1","catItemCommentsAnchor":"1","catItemK2Plugins":"1","itemDateCreated":"1","itemTitle":"1","itemFeaturedNotice":"1","itemAuthor":"1","itemFontResizer":"1","itemPrintButton":"1","itemEmailButton":"1","itemSocialButton":"1","itemVideoAnchor":"1","itemImageGalleryAnchor":"1","itemCommentsAnchor":"1","itemRating":"1","itemImage":"1","itemImgSize":"Large","itemImageMainCaption":"1","itemImageMainCredits":"1","itemIntroText":"1","itemFullText":"1","itemExtraFields":"1","itemDateModified":"1","itemHits":"1","itemCategory":"1","itemTags":"1","itemAttachments":"1","itemAttachmentsCounter":"1","itemVideo":"1","itemVideoWidth":"","itemVideoHeight":"","itemAudioWidth":"","itemAudioHeight":"","itemVideoAutoPlay":"0","itemVideoCaption":"1","itemVideoCredits":"1","itemImageGallery":"1","itemNavigation":"1","itemComments":"1","itemTwitterButton":"1","itemFacebookButton":"1","itemGooglePlusOneButton":"1","itemAuthorBlock":"1","itemAuthorImage":"1","itemAuthorDescription":"1","itemAuthorURL":"1","itemAuthorEmail":"0","itemAuthorLatest":"1","itemAuthorLatestLimit":"5","itemRelated":"1","itemRelatedLimit":"5","itemRelatedTitle":"1","itemRelatedCategory":"0","itemRelatedImageSize":"0","itemRelatedIntrotext":"0","itemRelatedFulltext":"0","itemRelatedAuthor":"0","itemRelatedMedia":"0","itemRelatedImageGallery":"0","itemK2Plugins":"1","catMetaDesc":"","catMetaKey":"","catMetaRobots":"","catMetaAuthor":""}';

		$db 					= JFactory::getDBO();
		$db->insertObject( '#__k2_categories', $dataC, id );

		$k2CatId 				= $this->getK2CategoryId();
		return $k2CatId;

	}

	public function getK2CategoryId()
	{
		$db 			= JFactory::getDBO();
		$query 			= 'SELECT cy.id FROM #__k2_categories AS cy WHERE cy.name like \'adodisblog\'';
		$db->setQuery( $query );
		$catid			= $db->loadResult();
		return $catid;
	}

	function deleteBlogAndComment()
	{
		$postvalue 	= JRequest::get('post');
		$checked 	= $postvalue['cid'];
		$string 	= implode(",",$checked);
		$db			= $this->getDbo();
		$query		= $db->getQuery(true);
        $query->clear();
		$query->delete(' #__adodisblog_blogs ');
		$query->where(' id IN ( ' . $string . ' )' );
		$db->setQuery((string)$query);
		$blog 		= $db->query();
		$db_c		= $this->getDbo();
		$query_c	= $db_c->getQuery(true);
        $query_c->clear();
		$query_c->delete(' #__adodisblog_comments ');
		$query_c->where(' blog_id IN ( ' . $string . ' )' );
		$db_c->setQuery((string)$query_c);
		$comment 	= $db_c->query();

        if (!$blog) {
            JError::raiseError(500, $db->getErrorMsg());
        	return false;
        } else {
        	return true;
		}
	}
}
?>
