<?php
/*======================================================================================
Module: Articles
======================================================================================*/

// Check authorisation
if (!isset($gCms)) exit;
if ( !$this->CheckPermission('Articles: modify articles') ) exit;
$errors = array();

// get parameters
$tabto = preg_replace('/[^0-9a-zA-Z_]/','',$params['tabto']);
$article = isset($params['article']) ? (int)$params['article'] : 0;
$active = 0;
if (isset($params['active'])) $active = $params['active'] ? 1 : 0;
$datetime = (isset($params['datetime_Month']) ? mktime($params['datetime_Hour'], $params['datetime_Minute'], $params['datetime_Second'], $params['datetime_Month'], $params['datetime_Day'], $params['datetime_Year']) : 'time()');
$user_id = isset($params['user_id']) ? (int)$params['user_id'] : get_userid();
$title = isset($params['title']) ? $params['title'] : '';
$short_desc = isset($params['short_desc']) ? $params['short_desc'] : '';
$long_desc = isset($params['long_desc']) ? $params['long_desc'] : '';
$detail_link = isset($params['detail_link']) ? (int)$params['detail_link'] : 0;
$start_date	= (isset($params['start_date_Month']) ? mktime($params['start_date_Hour'], $params['start_date_Minute'], $params['start_date_Second'], $params['start_date_Month'], $params['start_date_Day'], $params['start_date_Year']) : 'time()');
$end_date	= (isset($params['end_date_Month']) ? mktime($params['end_date_Hour'], $params['end_date_Minute'], $params['end_date_Second'], $params['end_date_Month'], $params['end_date_Day'], $params['end_date_Year']) : 'time()');
$availibility = isset($params['availibility']) ? (int)$params['availibility'] : 0;
$price = isset($params['price']) ? (float)str_replace(',','.',$params['price']) : 0.0;
$vat = isset($params['vat']) ? (float)str_replace(',','.',$params['vat']) : 0.0;
$delivery_time = isset($params['delivery_time']) ? $params['delivery_time'] : '';
$shipping_costs = isset($params['shipping_costs']) ? (float)str_replace(',','.',$params['shipping_costs']) : 0.0;
if (isset($params['cart'])) { $cart = $params['cart'] ? 1 : 0; } else { $cart = 0; }
$url = isset($params['url']) ? $params['url'] : '';
$image = '';
$image_del = isset($params['image_del']) ? $params['image_del'] : 0;
$image_text = isset($params['image_text']) ? $params['image_text'] : '';
$gallery_id = isset($params['gallery_id']) ? (int)$params['gallery_id'] : 0;
$return_id = isset($params['return_id']) ? (int)$params['return_id'] : $this->GetPreference('returnid');
$sort_order = isset($params['order']) ? (int)$params['order'] : 0;
$seo_url = isset($params['seo_url']) ? $params['seo_url'] : '';
$meta_title = isset($params['meta_title']) ? $params['meta_title'] : '';
$meta_description = isset($params['meta_description']) ? $params['meta_description'] : '';
$noindex = 0;
if (isset($params['noindex'])) $noindex = $params['noindex'] ? 1 : 0;
$nofollow = 0;
if (isset($params['nofollow'])) $nofollow = $params['nofollow'] ? 1 : 0;
$noarchive = 0;
if (isset($params['noarchive'])) $noarchive = $params['noarchive'] ? 1 : 0;
$noodp = 0;
if (isset($params['noodp'])) $noodp = $params['noodp'] ? 1 : 0;
$notranslate = 0;
if (isset($params['notranslate'])) $notranslate = $params['notranslate'] ? 1 : 0;

#echo '<div style="font-weight:bold;color:red;border:2px solid #f00;padding:5px;">';foreach ($params as $error=>$v) {echo '<p>'.$error.' = '.$v.'</p>';}echo '</div>';exit;

// Save article changes
if (isset($params['submit']) || isset($params['cache']) || isset($params['add']) || isset($params['cacheadd']) || isset($params['apply'])) {
	// Edit article
	if ($article) {
		$sql = 'UPDATE '.cms_db_prefix().'module_articles_articles SET title=?, short_desc=?, long_desc=?, active=?, user_id=?, image_text=?, gallery_id=?, datetime=?, start_date=?, end_date=?, detail_link=?, returnid=?, availibility=?, price=?, vat=?, delivery_time=?, shipping_costs=?, cart=?, url=?, seo_url=?, meta_title=?, meta_description=?, noindex=?, nofollow=?, noarchive=?, noodp=?, notranslate=?, modified=? WHERE entry_id=?';
		$res = $db->Execute($sql,array($title, $short_desc, $long_desc, $active, $user_id, $image_text, $gallery_id, $datetime, $start_date, $end_date, $detail_link, $return_id, $availibility, $price, $vat, $delivery_time, $shipping_costs, $cart, $url, $seo_url, $meta_title, $meta_description, $noindex, $nofollow, $noarchive, $noodp, $notranslate, time(), $article));
		if(!$res) { $errors[] = 'SQL ERROR: ' . $db->ErrorMsg() . '(with ' . $db->sql . ')'; }
		// Update categories
		$db->Execute('DELETE FROM '.cms_db_prefix().'module_articles_category_articles WHERE article_id=?', array($article));
		#print_r($params);exit;
		if (is_array($params['cats'])) {
			foreach ($params['cats'] as $catid) {
				$catid=(int)$catid;
				if ($catid>0) {
					$query = 'INSERT '.cms_db_prefix().'module_articles_category_articles (cat_id,article_id,modified_date) VALUES (?,?,?)';
					$db->Execute($query, array($catid,$article,trim($db->DBTimeStamp(time()), "'")));
				}
			}
		}
		// Modify article content for the search module
		$module = cms_utils::get_search_module();
		if (is_object($module) ) {
			$module->DeleteWords($this->GetName(),$article,'article');
			$text = $title.' '.$short_desc.' '.$long_desc;
			$module->AddWords($this->GetName(), $article, 'article', $text, isset($params['end_date_Month']) ? $end_date : NULL);
		}
		// Send event
		@$this->SendEvent('Articles_ArticleEdited', array('article' => $article, 'title' => $title, 'content' => $long_desc, 'summary' => $short_desc, 'active' => $active, 'start_date' => $start_date, 'end_date' => $end_date));
	// Insert new article
	} else {
		// Insert article
		$sql = 'INSERT INTO '.cms_db_prefix().'module_articles_articles (title, short_desc, long_desc, active, user_id, image_text, gallery_id, datetime, start_date, end_date, detail_link, returnid, availibility, price, vat, delivery_time, shipping_costs, cart, url, sort_order, seo_url, meta_title, meta_description, noindex, nofollow, noarchive, noodp, notranslate, created, modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
		$res = $db->Execute($sql,array($title, $short_desc, $long_desc, $active, $user_id, $image_text, $gallery_id, $datetime, $start_date, $end_date, $detail_link, $return_id, $availibility, $price, $vat, $delivery_time, $shipping_costs, $cart, $url, $sort_order, $seo_url, $meta_title, $meta_description, $noindex, $nofollow, $noarchive, $noodp, $notranslate, time(), time()));
		if(!$res) { $errors[] = 'SQL ERROR: ' . $db->ErrorMsg() . '(with ' . $db->sql . ')'; }
		$article = $db->GetOne('SELECT entry_id FROM '.cms_db_prefix().'module_articles_articles WHERE short_desc = ? ORDER BY entry_id DESC LIMIT 1', array($short_desc));
		// Insert categories
		if (isset($params['cats'])) {
			if (is_array($params['cats'])) {
				foreach ($params['cats'] as $catid) {
					$catid=(int)$catid;
					if ($catid>0) {
						$query = 'INSERT '.cms_db_prefix().'module_articles_category_articles (cat_id,article_id,modified_date) VALUES (?,?,?)';
						$db->Execute($query, array($catid,$article,trim($db->DBTimeStamp(time()), "'")));
					}
				}
			}
		}
		// Add article content to the search module
		if($article) {
			//Update search index
			$module = cms_utils::get_search_module();
			if (is_object($module)) {
				$text = $title.' '.$short_desc.' '.$long_desc;
				$module->AddWords($this->GetName(), $article, 'article', $text, isset($params['end_date_Month']) ? $end_date : NULL);
			}
		}
		// Send event
		if ($article) @$this->SendEvent('Articles_ArticleAdded', array('article' => $article, 'category' => $category, 'datetime' => $datetime, 'title' => $title, 'content' => $long_desc, 'summary' => $short_desc, 'active' => $active, 'start_date' => $start_date, 'end_date' => $end_date));
	}
	// Delete image
	if ($image_del) {
		$filename = $db->GetOne('SELECT image_url FROM '.cms_db_prefix().'module_articles_articles WHERE entry_id = ?', array($article));
		if ($filename) {
			$deldir = cms_join_path($config['image_uploads_path'],'Articles','articles',$article);
			$delfile = cms_join_path($deldir,$filename);
			if (is_file($delfile)) unlink($delfile);			
		}
		$db->Execute('UPDATE '.cms_db_prefix().'module_articles_articles SET image_url = "" WHERE entry_id = ?', array($article));
	}
	// Upload image
	if (is_array($_FILES)) {
		$params_prefix_tmp = explode(',',$_REQUEST['mact']);
		$params_prefix = $params_prefix_tmp[1];
		$iname = $params_prefix.'image';
		$image = isset($_FILES[$iname]) ? $_FILES[$iname]['name']: '';
		#echo $image;exit;
		if ($image) {
			#$base = cms_join_path($config['image_uploads_path'],'Articles'.DIRECTORY_SEPARATOR.'articles');
			$newdir = cms_join_path($config['image_uploads_path'],'Articles','articles',$article);
			$dest = cms_join_path($newdir,basename($image));
			#print_r($_FILES);echo "<br />newdir:'$newdir'<br />dest:'$dest'<br />image:'$image'";exit;
			if (!is_dir($newdir)) {
				if (!mkdir($newdir)) $errors[] = "Error creating dir $newdir";
			}
			if (is_dir($newdir)) {
				if (move_uploaded_file($_FILES[$iname]['tmp_name'],$dest)) { $db->Execute('UPDATE '.cms_db_prefix().'module_articles_articles SET image_url = ? WHERE entry_id = ?', array(basename($image),$article)); }
				else { $errors[] = "Upload failed : Unable to write $dest"; }
			}
		}
		
	}
}

// display errors
#if ($errors) {echo '<div style="font-weight:bold;color:red;border:2px solid #f00;padding:5px;">';foreach ($errors as $e){echo '<p>'.$e.'</p>';}echo '</div>';exit;}

// Redirect
if (isset($params['submit']) || isset($params['add'])) $this->Redirect($id, 'defaultadmin', $returnid, array('tabto'=>$tabto, 'errors' => implode(',',str_replace(',',';',$errors)), 'message' => $this->Lang('changessaved')));
elseif (isset($params['cancel'])) $this->Redirect($id, 'defaultadmin', $returnid, array('tabto'=>$tabto));
else $this->Redirect($id, 'defaultadmin', $returnid, array( 'tabto'=>$tabto, 'article'=>$article ));

// EOF