<?php
/*
	DevSaver Web Framework
	Copyright (c) 2002-2016 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com
*/

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}
// dependencies

define("STP_MEDIA_SHOW_LISTING"		, "1");
define("STP_MEDIA_SHOW_DETAILS"		, "2");
define("STP_MEDIA_SHOW_OG"			, "3");

define("STP_MEDIA_TYPE_IMAGE"		, "1");
define("STP_MEDIA_TYPE_YOUTUBE"		, "2");
define("STP_MEDIA_TYPE_VIMEO"		, "3");
define("STP_MEDIA_TYPE_LOCALVIDEO"	, "4");
define("STP_MEDIA_TYPE_AUDIO"		, "5");
define("STP_MEDIA_TYPE_HTML"		, "6");
define("STP_MEDIA_TYPE_GIF"			, "7");

/**
* description
*
* @library	
* @author	
* @since	
*/
class CMedia extends CPlugin{
	
	var $tplvars; 


	//any of this settings can be altered by other modules
	var $media = array(
		"hide"	=> array(
			"list"		=> array(),
			"edit"		=> array(),
			"options"	=> array()
		),

		"path"	=> "./media/",

		"images"	=> array(

			"image"	=> array(
				"width"		=> 1170,
				"height"	=> "",
				"preffix"	=> "../large/",
			),

			"tn"	=> array(
				"width"		=> 720,
				"height"	=> "",
				"preffix"	=> "../tn/",
			),

			"tn2"	=> array(
				"width"		=> 720,
				"height"	=> 480,
				"preffix"	=> "../tn2/",
			),
		),

		"tables"	=> array(
			"table"			=> "plugin:media",
			"table_lang"	=> "plugin:media_lang",
		)
		
	);


	function __construct() {
		//$this->CPlugin($db, $tables , $templates);
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;

		parent::DoEvents();

		if ($_GET["mod"] == "media") {
			$sub = $_GET["sub"];
			$action = $_GET["action"];

			//read the module
			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("media");			

			switch ($sub) {

				case "images":

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->plugins["modules"]->GetModuleInfo($_REQUEST["module_id"]));
					$this->PrepareMediaFields($data->forms);

					$data->functions = array( 
							"onstore" => array(&$this , "StoreRecord"),
//							"ondelete" => array(&$this , "DeleteRecord"),
					);	
					

					return $data->DoEvents();
				break;

				case "mass.upload":
					return $this->MassUploadForm();
				break;

				case "mass.upload.act":
					return $this->MassUploadAction();
				break;

				case "items.delete":
					return $this->MassDelete();
				break;

			}

		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareMediaFields(&$forms) {
		global $_TSM;


		if ($_REQUEST["module_id"] < 2000) {
			$module = $this->plugins["modules"]->GetDefaultModuleInfoById($_REQUEST["module_id"] , false);
			$tabs_file = $this->module->plugins[$module["module_code"]]->forms_path . "dashboard.xml";
		} else {		
			$module = $this->plugins["modules"]->GetModuleInfo($_REQUEST["module_id"] , false);
			$tabs_file = $this->module->plugins[$module["mod_module_code"]]->forms_path . "dashboard.xml";
		}

		$this->AlterSettings();

		if (file_exists($tabs_file)) {
			$tabs = new CConfig($tabs_file);
			$tabs = $tabs->vars["tabs"];

			$forms["forms"]["details"]["tabs"] = $tabs;
			$forms["forms"]["edit"]["tabs"] = $tabs;
			$forms["forms"]["add"]["tabs"] = $tabs;
			$forms["forms"]["list"]["tabs"] = $tabs;


			if ($module["mod_parent"]) {
				$parent = $this->plugins["modules"]->GetModuleInfo($module["mod_parent"],false);
				$_TSM["PUB:MODULE_NAME_PARENT"] = array(
						"title"	=> $parent["mod_name"],
						"id"	=> $parent["mod_id"],
				);
			}

			$_TSM["PUB:MODULE_NAME"]= $module["mod_name"] ? $module["mod_name"] : $module["module_name"];
			$_TSM["PUB:MODULE_LINK"] = $this->plugins["modules"]->PrepareLink($module);
			
		}	

		//update the tables

		$forms["forms"]["edit"]["table"] = $forms["forms"]["add"]["table"] = $forms["table"] = $this->media["tables"]["table"];
		$forms["forms"]["edit"]["table_lang"] = $forms["forms"]["add"]["table_lang"] = $forms["table_lang"] = $this->media["tables"]["table_lang"];


		$this->processEdit($forms["forms"]["add"]);
		$this->processEdit($forms["forms"]["edit"]);		
	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function MassUploadForm() {
		global $_CONF;


		return CPlUpload::NewInstance()
			->Render(
				array(
					"action"		=> "json.php?mod=media&sub=mass.upload.act&module_id={$_GET[module_id]}&item_parent={$_GET[item_parent]}",
					"skin"			=> "Purple",
				)
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function MassUploadAction() {

		$temp = CPlUpload::NewInstance()
			->SetFunction(
				"onComplete",
				array(&$this , "StoreImage")
			)
			->Run();
	}
		
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function StoreImage($path , $name) {
		global $base;

		if ($_REQUEST["module_id"]) {
			$this->AlterSettings();
		}

		$id = $this->db->QueryInsert(
			$this->tables[$this->media["tables"]["table"]],
			array(
				"module_id"		=> $_REQUEST["module_id"],
				"item_parent"	=> $_GET["item_parent"],				
				"item_show"		=> $this->tpl_module["settings"]["set_mass_show"],
				"item_type"		=> "1",
				"item_image"	=> "1",
			)
		);

		$this->db->QueryUpdate(
			$this->tables[$this->media["tables"]["table"]],
			array(
				"item_order"	=> $id
			),
			"item_id={$id}"
		);


		$info = pathinfo($path);

		$name = $info["basename"];

		if ($info["extension"]) {		
			$name = str_replace("." . $info["extension"] , "" , $info["basename"]);
		}


		$this->db->QueryInsert(
			$this->tables[$this->media["tables"]["table_lang"]],
			array(
				"module_id"		=> $_GET["module_id"],
				"item_id"		=> $id,
				"lang_id"		=> $this->tpl_module["lang_id"],
				"item_title"	=> $this->tpl_module["settings"]["set_mass_name"] ? $name : "",
			)
		);

		//copy the image to the final folder

		$image = Image::newInstance();

		//copy the base image to the full 
		CFile::Copy(
			$path , 
			"../upload/" . $this->media["path"] . "full/{$id}.jpg"
		);

		foreach ($this->media["images"] as $key => $val) {
			$image->read($path)
				->DetectAction($val["width"] , $val["height"])
				->save(
					str_replace(
						"/../" , 
						"/" , 
						"../upload/" . $this->media["path"] . $val["preffix"] . "/{$id}.jpg"
					)
				);
		}
		
		$image->Destroy();

		CFile::Remove($path);

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function StoreRecord($record) {



		if ($record["item_type"] == "3") {
			$info = CHTTP::NewInstance()
				->Get("https://vimeo.com/api/v2/video/" . $record["item_vimeo"] . ".json")
				->JSon(); 

			if (is_array($info["0"]) && $info["0"]["thumbnail_large"]) {

				$this->db->QueryUpdate(
					$this->tables[$this->media["tables"]["table"]],
					array(
						"item_vimeo_cover"	=> $info["0"]["thumbnail_large"]
					),
					"item_id={$record[item_id]}"
				);
			}
		}

	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function processList(&$form) {

		if ($_REQUEST["module_id"]) {
			$this->AlterSettings();

			$form["fields"]["item_image"]["path"] = $this->media["path"];


			$form["table"] = $this->media["tables"]["table"];
			$form["table_lang"] = $this->media["tables"]["table_lang"];


			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("media");			


			switch ($this->tpl_module["settings"]["set_media_height"]) {
				case "3":
					$form["fields"]["item_image"]["width"] = "300";
				break;

				default:
				case "2":
					$form["fields"]["item_image"]["width"] = "150";
				break;

				case "1":
					$form["fields"]["item_image"]["width"] = "75";
				break;
			}		
		}
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function processEdit(&$form) {

		$sets = array(
			"author"	=> array("subtitle_copyright" , "item_author" , "subtitle" , "item_link_type", "item_link_module" , "item_link_global" , "item_link_link" , "item_link_target")
		);

		if ($_REQUEST["module_id"]) {



			//$this->AlterSettings();
			//update path
			$form["fields"]["box"]["1"]["fields"]["item_image"]["path"] = str_replace(
				"./media/" , 
				$this->media["path"],
				$form["fields"]["box"]["1"]["fields"]["item_image"]["path"]
			);

			$form["fields"]["box"]["1"]["fields"]["item_video"]["path"] = str_replace(
				"./media/" , 
				$this->media["path"],
				$form["fields"]["box"]["1"]["fields"]["item_video"]["path"]
			);

			$form["fields"]["box"]["1"]["fields"]["item_gif"]["path"] = str_replace(
				"./media/" , 
				$this->media["path"],
				$form["fields"]["box"]["1"]["fields"]["item_gif"]["path"]
			);

			$form["fields"]["box"]["1"]["fields"]["item_audio"]["path"] = str_replace(
				"./media/" , 
				$this->media["path"],
				$form["fields"]["box"]["1"]["fields"]["item_audio"]["path"]
			);


			if (is_array($this->media["hide"]["edit"]) && count($this->media["hide"]["edit"])) {
				foreach ($this->media["hide"]["edit"] as $k => $v) {

					if ($sets[$v]) {
						CForm::DeleteFields($form, $sets[$v]);
					} else {					
						CForm::DeleteFields($form, $v);
					}
				}				
			}

			if (is_array($this->media["hide"]["options"]["item_show"])) {
				foreach ($this->media["hide"]["options"]["item_show"] as $key => $val) {
					unset($form["fields"]["box"]["1"]["fields"]["item_show"]["options"][$val]);
				}
			}
			
			if (is_array($this->media["hide"]["options"]["item_type"])) {
				foreach ($this->media["hide"]["options"]["item_type"] as $key => $val) {
					unset($form["fields"]["box"]["1"]["fields"]["item_type"]["options"][$val]);
				}				
			}

		
			//set the main image title if has both width & height 
			if ($this->media["images"]["image"]["width"] && $this->media["images"]["image"]["height"]) {
				$form["fields"]["box"]["1"]["fields"]["item_image"]["title"] .= " (" .$this->media["images"]["image"]["width"] . " x " .$this->media["images"]["image"]["height"] . "px)";
			} 


			foreach ($this->media["images"] as $key => $val) {

				switch ($key) {
					case "image":
						$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["resize"]["width"] = $val["width"];
						$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["resize"]["height"] = $val["height"];
						$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["resize"]["preffix"] = $val["preffix"];
					break;

					default:
						$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"][$key] = $val;
					break;
				}				
			}

			if (!$this->media["images"]["tn"]) unset($form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["tn"]);
			if (!$this->media["images"]["tn2"]) unset($form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["tn2"]);
			

			//sql tables
			$form["table"] = $this->media["tables"]["table"];
			$form["table_lang"] = $this->media["tables"]["table_lang"];
				
		}

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AlterSettings() {

		if (!$_REQUEST["module_id"] && $_GET["module_id"]) {
			$_REQUEST["module_id"] = $_GET["module_id"];
		}
		

		if ($_REQUEST["module_id"] < 2000) {
			$module = $this->plugins["modules"]->GetDefaultModuleInfoById($_REQUEST["module_id"] , false);
		} else {			
			$module = $this->plugins["modules"]->GetModuleInfo($_REQUEST["module_id"] , false);
		}

		$settings = $this->plugins[$module["module_code"]]->media;


		if (is_array($settings["tables"]) && $settings["tables"]["table"] && $settings["tables"]["table_lang"]) {
			$this->media["tables"]["table"] = $settings["tables"]["table"];
			$this->media["tables"]["table_lang"] = $settings["tables"]["table_lang"];
		}

		if ($settings["path"]) {
			$this->media["path"] = $settings["path"];
		}


		if (is_array($settings["images"])) {
			$this->media["images"] = $settings["images"];
		} else {
						
			//deprecated, willbe removed in time
			//main image / resize
			if (is_array($settings["image"])) {
				if (!$settings["image"]["preffix"]) {
					$settings["image"]["preffix"] = $this->media["images"]["image"]["preffix"];
				}

				$this->media["images"]["image"] = $settings["image"];

			}

			//first thumbnail
			if (is_array($settings["tn"])) {
				if (!$settings["tn"]["preffix"]) {
					$settings["tn"]["preffix"] = $this->media["images"]["tn"]["preffix"];
				}
				
				$this->media["images"]["tn"] = $settings["tn"];
			}
			
			//second thumbnail
			if (is_array($settings["tn2"])) {
				if (!$settings["tn2"]["preffix"]) {
					$settings["tn2"]["preffix"] = $this->media["images"]["tn2"]["preffix"];
				}

				$this->media["images"]["tn2"] = $settings["tn2"];
			}
		}


		if (is_array($settings["hide"])) {

			if (is_array($settings["hide"]["list"])) {
				$this->media["hide"]["list"] = $settings["hide"]["list"];
			}

			if (is_array($settings["hide"]["edit"])) {
				$this->media["hide"]["edit"] = $settings["hide"]["edit"];
			}			

			if (is_array($settings["hide"]["options"])) {
				$this->media["hide"]["options"] = $settings["hide"]["options"];
			}			

		}


	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function MassDelete() {


		if ($_GET["module_id"]) {
			$this->AlterSettings();

			if ($_POST["item_id"]) {
				$this->db->Query(
					"DELETE FROM %s WHERE item_id IN (%s)" , 
					array(
						$this->tables[$this->media["tables"]["table"]] , 
						implode("," , $_POST["item_id"])
					)
				);

				$this->db->Query(
					"DELETE FROM %s WHERE item_id IN (%s)" , 
					array(
						$this->tables[$this->media["tables"]["table_lang"]] , 
						implode("," , $_POST["item_id"])
					)
				);
			}
		}

		return "1";
	}
	
	
}

?>