<?php
class links_easypost
{
	var $Links;
	var $mydirname;
	var $controller_name;

	/** Constructor
	 *
	**/
	function __construct($mydirname)
	{
		$this->mydirname = $mydirname;
		$this->controller_name = str_replace('links_', '', get_class($this));
		$this->Links = links_Base::getInstance($this->mydirname);
		$this->Links->setControllerName($this->controller_name);
		$this->Links->breadcrumbs();

		if (! $this->Links->post_perm) {
			redirect_header(XOOPS_URL."/", 2, _NOPERM);
			exit();
		}

		//Block Permission Check
		$db = icms_db_Factory::instance();
		$sql = "SELECT bid FROM ". $db->prefix('newblocks') ." WHERE mid=". $this->Links->module_id ." AND func_num=2" ;
		list($bid) = $db->fetchRow($db->query($sql));
		$gperm =& xoops_gethandler('groupperm');
		if (! $gperm->checkRight('block_read', $bid, $this->Links->groups)) {
			redirect_header(XOOPS_URL."/", 2, _NOPERM);
			exit();
		}
	}

	function index()
	{
		$this->Links->basicPostCheck('links_easypost');

		$cid      = isset($_POST['cid'])      ? intval($_POST['cid'])                : 0 ;
		$pcmobile = isset($_POST['pcmobile']) ? intval($_POST['pcmobile'])           : 1 ;
		$url      = isset($_POST['url'])      ? $this->Links->stripSlashesGPC($_POST['url']): '';

		if (empty($cid) || ! in_array($cid, $this->Links->allkeycid)) {
			redirect_header(XOOPS_URL."/", 3, _MD_NO_CATEGORY);
		}

		$ip = xoops_getenv("REMOTE_ADDR");

		// POST TIME GAP CHECK
		$this->Links->clearWhere();
		$this->Links->setWhere('ip', $ip, '=');
		$this->Links->setWhere('status', -3, '=');
		$this->Links->setWhere('date', time()-300, '>');	// 5 minutes
		$count = $this->Links->getCount() ;
		if ($count > 0) {
			redirect_header(XOOPS_URL."/", 3, _MD_TIME_GAP_SMALL);
			exit();
		}

		//URL length check
		if (empty($url) || strlen($url) <= 12) {
			redirect_header(XOOPS_URL."/", 3, _MD_SITETITLE.' '._MD_SUBMIT_ALERT);
			exit();
		}

		//URL control code check
		if (! $this->Links->linksUrlCCCheck($url)) {
			redirect_header(XOOPS_URL."/", 3, _MD_URL_WRONG);
			exit();
		}

		//URL http_request check
		$status_code = check_URI($url);
		if (200 != intval($status_code/100)*100) {
			redirect_header(XOOPS_URL."/", 3, _MD_NO_ADDRESS);
			exit();
		}

		//Checking for duplication
		$this->Links->clearWhere();
		$url_field = ($pcmobile == 1) ? 'url': 'murl';
		$this->Links->setWhere($url_field, $url, '=');
		$count = $this->Links->getCount() ;
		if ($count > 0) {
			redirect_header(XOOPS_URL."/", 3, _MD_ERROREXIST);
			exit();
		}

		// SAVE
		$this->Links->saveEasypost($cid, $ip, $url, $url_field);
		redirect_header(XOOPS_URL."/", 2, _MD_RECEIVED);
	}
}
