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

// dependencies

/**
* 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()
		),

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

		"image"	=> array(
			"width"		=> 1170,
			"height"	=> ""
		),

		"tn"	=> array(
			"width"		=> 720,
			"height"	=> ""
		),
		"tn2"	=> array(
			"width"		=> 720,
			"height"	=> 480
		),

		"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->PrepareFields($data->forms["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 PrepareFields(&$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";
		}

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

			$forms["details"]["tabs"] = $tabs;
			$forms["edit"]["tabs"] = $tabs;
			$forms["add"]["tabs"] = $tabs;
			$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);
			
		}	
		
	}
	


	/**
	* 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"]) {
			$module = $this->plugins["modules"]->GetModuleInfo($_REQUEST["module_id"] , false);
			$settings = $this->plugins[$module["module_code"]]->media;

			$this->AlterSettings($settings);
		}

		$id = $this->db->QueryInsert(
			$this->tables[$this->media["tables"]["table"]],
			array(
				"module_id"		=> $_GET["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::newInstance()
			->Read($path)
			->ResizeFit( 
				ImageConst::MAX_WIDTH , 
				ImageConst::MAX_HEIGHT 
			)
			->Save(
				"../upload/" . $this->media["path"] . "full/{$id}.jpg", 
				90
			)
			->DetectAction($this->media["image"]["width"] , $this->media["image"]["height"])
			->Save(
				"../upload/" . $this->media["path"] . "large/{$id}.jpg", 
				90
			)
			->DetectAction($this->media["tn"]["width"] , $this->media["tn"]["height"])
			->Save(
				"../upload/" . $this->media["path"] . "tn/{$id}.jpg", 
				90
			)
			->DetectAction($this->media["tn2"]["width"] , $this->media["tn2"]["height"])
			->Save(
				"../upload/" . $this->media["path"] . "tn2/{$id}.jpg", 
				90
			)
			->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["plugin:media"],
					array(
						"item_vimeo_cover"	=> $info["0"]["thumbnail_large"]
					),
					"item_id={$record[item_id]}"
				);
			}
		}

	}
	


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

		if ($_REQUEST["module_id"]) {
			$module = $this->plugins["modules"]->GetModuleInfo($_REQUEST["module_id"] , false);
			$settings = $this->plugins[$module["module_code"]]->media;

			$this->AlterSettings($settings);

			$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"]) {


			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;

			$this->AlterSettings($settings);
			//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);
					}
				}				
			}

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

			$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["resize"]["width"] = $this->media["image"]["width"];
			$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["resize"]["height"] = $this->media["image"]["height"];				


			//first thumbnail
			$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["tn"]["width"] = $this->media["tn"]["width"];
			$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["tn"]["height"] = $this->media["tn"]["height"];

			//second thumbnail
			$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["tn2"]["width"] = $this->media["tn2"]["width"];
			$form["fields"]["box"]["1"]["fields"]["item_image"]["thumbnails"]["tn2"]["height"] = $this->media["tn2"]["height"];


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

	}

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

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


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

		//main image / resize
		if (is_array($settings["image"])) {
			$this->media["image"] = $settings["image"];
		}

		//first thumbnail
		if (is_array($settings["tn"])) {
			$this->media["tn"] = $settings["tn"];
		}
		
		//second thumbnail
		if (is_array($settings["tn2"])) {
			$this->media["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"];
			}			
		}

	}

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

		if ($_REQUEST["module_id"]) {
			$module = $this->plugins["modules"]->GetModuleInfo($_REQUEST["module_id"] , false);
			$settings = $this->plugins[$module["module_code"]]->media;

			$this->AlterSettings($settings);

			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";
	}
	
	
}

?>