<?php
class NewsController extends Controller{
	
	public $layout = 'column2';
	
	public function actions(){

        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
		
		
		
    }

    public function init() {
        if(Yii::app()->params['styles_type'] == 'new'){
            $this->layout = 'sidebar';
        }
    }
	
	public function actionList(){
		$this->pageTitle = Yii::t("main", "1017_news");
        $this->breadcrumbs = array(Yii::t("main", "1017_news"));

		$pageSize = 18;
		$page = 0;

		if (Yii::app()->request->isAjaxRequest) {
			$page = (int)$_REQUEST['lastPage'] + 1;
		}

		$newsList = '';

		try {
			$criteria = new CDbCriteria();
			$criteria->order  = 'pubDate DESC';
			$criteria->limit  = $pageSize;
			$criteria->offset = $page * $pageSize;

			$newsData = FxstreetNews::model()->findAll($criteria);

			foreach ($newsData as $news) {
				$pubTimestamp = strtotime($news->pubDate);
				if (!$pubTimestamp) $pubTimestamp = time();

				$newsList .= '<div class="newsBlock">
					<a href="/news/details/id/' . $news->id . '/date/' . $pubTimestamp . '">
						<div class="nTitle">' . CHtml::encode($news->title) . '</div>
						<div class="nBody">' . strip_tags($news->description) . '...</div>
						<div class="nDate"><span class="icon-106clock"></span><div>' . date('m/d/Y H:i', $pubTimestamp) . '</div></div>
					</a>
				</div>';
			}
		} catch (Exception $e) {
			Yii::log('FxstreetNews list error: ' . $e->getMessage(), CLogger::LEVEL_ERROR);
			if (isset($_GET['dev'])) {
				echo '<pre>DB Error: ' . htmlspecialchars($e->getMessage()) . '</pre>';
				Yii::app()->end();
			}
		}

		if (Yii::app()->request->isAjaxRequest) {
			echo ($newsList == '') ? 'empty' : $newsList;
			die();
		}

		$this->render('news', array('newsList' => $newsList, 'page' => $page));
	}
	
	public function actionAdd(){

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump('333');die();
        }*/

		// $allowLnags = array('en'=>'www.investing.com','cn'=>'cn.investing.com','ru'=>'ru.investing.com','es'=>'es.investing.com','ar'=>'sa.investing.com','vn'=>'vn.investing.com');
		$allowLnags = array('en'=>'https://www.investing.com/server/server.php?username=BMFNPrime&password=BHYr8vDzi_Poy',
                            'cn'=>'https://cn.investing.com/server/server.php?username=BMFNPrime&password=XM6oZiQa_Gpd',
                            'ru'=>'https://ru.investing.com/server/server.php?username=BMFNPrime&password=vweNTAI_By',
                            'es'=>'https://es.investing.com/server/server.php?username=BMFNPrime&password=SRGQ59Qf_knh',
                            'ar'=>'https://sa.investing.com/server/server.php?username=BMFNPrime&password=7midgWk0Yd_Do',
                            'vn'=>'https://vn.investing.com/server/server.php?username=BMFNPrime&password=2aTDIQ13bl_4vX');
		if(isset($_GET['lang']) && in_array($_GET['lang'], array_keys($allowLnags))){
			$link = $allowLnags[$_GET['lang']];
		}else{
			$link = $allowLnags['en'];
		}
		// $xmlstring = file_get_contents('https://'.$link.'/server/server.php?username=BMFNPrime&password=BHYr8vDzi_Poy');
		 $xmlstring = file_get_contents($link);

		if(isset($_GET['dev'])){
		    //var_dump($xmlstring, 'https://'.$link.'/server/server.php?username=BMFNPrime&password=BHYr8vDzi_Poy', 'SERVER_ADDR: '.$_SERVER["SERVER_ADDR"]);die();

		  //  var_dump($xmlstring, 'https://www.investing.com/server/server.php?username=BMFNPrime&password=BHYr8vDzi_Poy', 'SERVER_ADDR: '.$_SERVER["SERVER_ADDR"]);
		    die();
        }

		//if($xmlstring != 'ip not allowed' && $xmlstring!='Not Authorized!'){
			$xml = simplexml_load_string($xmlstring, null, LIBXML_NOCDATA); 
			foreach($xml->NewsItems->Item as $news){ 
				$tmpNews = (array)$news;
				$result[] = array('date'=>$tmpNews['NewsDate'], 'title'=>$tmpNews['Title'], 'body'=>str_replace(array('Investing.com - ', 'Investing.com &ndash; '), array('',''), strip_tags($tmpNews['Body'], '<p><strong><table><tr><td><th><tbody><thead><tfoot>')));
			}
			//var_dump($_GET['lang'],$link, $result, json_encode($result));die();
			echo json_encode($result);die();  
		/* }else{
			echo 'no access';die();
		} */
	}
	
	public function actionDetails(){
		$params = array('empty' => 1);

		if (isset($_GET['id'])) {
			try {
				$news = FxstreetNews::model()->findByPk((int)$_GET['id']);

				if ($news !== null) {
					$pubTimestamp = strtotime($news->pubDate);
					if (!$pubTimestamp) $pubTimestamp = time();

					$params = array();
					$params['title'] = CHtml::encode($news->title);
					$params['date']  = date('m/d/Y H:i', $pubTimestamp);
					$params['body']  = $news->full_content;

					$this->pageTitle = Yii::t("main", "1017_news");
					$this->breadcrumbs = array(
						Yii::t("main", "1017_news") => array('/news/list.html'),
						$params['title']
					);
				}
			} catch (Exception $e) {
				Yii::log('FxstreetNews details error: ' . $e->getMessage(), CLogger::LEVEL_ERROR);
				if (isset($_GET['dev'])) {
					echo '<pre>DB Error: ' . htmlspecialchars($e->getMessage()) . '</pre>';
					Yii::app()->end();
				}
			}
		}

		$this->render('newsDetail', $params);
	}
	
	public function actionFxNewsList()
	{
		try {
			$newsList = FxstreetNews::getAll(50);

			$result = array();
			foreach ($newsList as $item) {
				$result[] = array(
					'id'           => $item->id,
					'guid'         => $item->guid,
					'title'        => $item->title,
					'link'         => $item->link,
					'image_url'    => $item->image_url,
					'pubDate'      => $item->pubDate,
					'description'  => $item->description,
					'full_content' => $item->full_content,
				);
			}

			header('Content-Type: application/json');
			echo json_encode($result);
		} catch (Exception $e) {
			header('Content-Type: application/json');
			echo json_encode(array('error' => $e->getMessage()));
		}

		Yii::app()->end();
	}

	public function actionEcalendar() {
        $this->pageTitle = Yii::t("main", "928_economic_calendar");
        $this->breadcrumbs = array(Yii::t("main", "928_economic_calendar"));
        
       
       /*  $mod = new Ecalendar();
        if (Yii::app()->request->isAjaxRequest) {
            $mod->attributes = $_REQUEST;
            $ecal = $mod->GetCalendar();
            $pagination = $mod->GetPagination();
            echo json_encode(array('table'=>$ecal,'count'=>$pagination['count']));
            Yii::app()->end();
        }
        $ecal = $mod->GetCalendar();
        $country = $mod->GetCountries();
        $pagination = $mod->GetPagination();
        
        $this->render('eCalendar', array('calendar'=>$ecal,'country'=>$country,'pagination'=>$pagination)); */
		
		$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
		
		// mobile
		$langMob = array('en', 'de', 'es', 'fr', 'it', 'nl', 'pl', 'pt', 'fi', 'se', 'tr', 'gr', 'ru', 'il', 'jp', 'cn');
		$lang = (in_array(Yii::app()->language, $langMob)) ? Yii::app()->language : 'en'; 
		$mobLink = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https://ssltouchecal.forexprostools.com' : 'http://touchecal.forexprostools.com';
		$mobLink = $mobLink.'/?force_lang='.$lang.'&cssFile='.$http.'//'.$_SERVER['SERVER_NAME'].'/assets/css/ec_calendar_mobile.css';
		
		
		// pc
		$pcLink = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https://sslecal2.forexprostools.com' : 'http://ec.forexprostools.com';
		$langPc = array('en'=>1, 'vn'=>1, 'il'=>2, 'ar'=>3, 'sa'=>3, 'es'=>4, 'fi'=>5, 'cn'=>6, 'ru'=>7, 'de'=>8, 'it'=>9, 'tr'=>10, 'jp'=>11, 'br'=>12, 'se'=>13, 'gr'=>14, 'pl'=>15, 'nl'=>16, 'fi'=>17, 'kr'=>18, 'mx'=>49, 'pt'=>50);
		$tmpLangPc = (in_array(Yii::app()->language, array_keys($langMob))) ? $langPc[Yii::app()->language] : 1; 
		$cssFile = $http.'//'.$_SERVER['SERVER_NAME'].'/assets/css/ec_calendar.css';

        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '78.46.17.32') {
            $cssFile = $http.'//'.$_SERVER['SERVER_NAME'].'/assets/css/ec_calendar_efx.css';
        }

		$pcLink = $pcLink.'/?ecoDayBackground=%231a4566&defaultFont=%231a4566&innerBorderColor=%231a4566&borderColor=%23ffffff&columns=exc_flags,exc_currency,exc_importance,exc_actual,exc_forecast,exc_previous&features=datepicker,timezone,timeselector,filters&countries=25,32,6,37,72,22,17,39,14,10,35,43,56,36,110,11,26,12,4,5&calType=week&timeZone=55&lang='.$tmpLangPc.'&cssfile='.$cssFile;

        $this->render('eCalendar', array('mobLink'=>$mobLink, 'pcLink'=>$pcLink));       
    }
}
