<?php
/**
 * @params $_GET['project_id'] - int
 * TODO: not used: @params $_GET['www_files'] - array of file names
 */


error_reporting(E_ALL & ~E_NOTICE);

define('DS', DIRECTORY_SEPARATOR);
define('APP_PATH_ROOT', dirname(__FILE__));
define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');

//session_save_path("../session") ;
session_start();

date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions

if (file_exists(".config.php")) include(".config.php");

SEF('DEBUG_S');
require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('User');
Lib::loadClass('Config');
Lib::loadClass('App');
Lib::loadClass('DB');
Lib::loadClass('S');

// DBG:
ini_set('error_reporting', E_ALL ^ E_NOTICE);
//ini_set('error_reporting', E_ALL);
error_reporting(E_ALL ^ E_NOTICE);
//error_reporting(E_ALL);
ini_set('display_errors', TRUE);


$sync_project_file_command = '/home/plabudda/sync-projekty-files-to-www.sh';
$sync_projekty_tmp_folder = '/home/plabudda/sync-projekty-files-to-www';

{// fetch active projects
	$sql_select = array();
	$sql_where_and = array();

	$sql_select []= "p.`ID`";
	$sql_select []= "p.`M_DIST_TYPE`";
	$sql_select []= "p.`M_DIST_DESC`";
	//$sql_select []= "p.``";

	$sql_project_types = array();
	$sql_project_types []= "'WWW_PRACA'";
	$sql_project_types []= "'WWW_DOKUMENTY'";
	$sql_project_types []= "'WWW_AKTUALNOSCI'";
	$sql_project_types []= "'WWW_AKTUALNOSCI_TV'";
	$sql_where_and []= "p.`M_DIST_TYPE` in (".implode(",", $sql_project_types).")";

	$sql_where_and []= "p.`A_STATUS` in ('NORMAL','WAITING')";

	$projekt_id = V::get('projekt_id', 0, $_REQUEST, 'int');
	if ($projekt_id > 0) {
		$sql_where_and []= "p.`ID`='".$projekt_id."'";
	}

	$sql_select = implode(", ", $sql_select);
	$sql_where = implode("\n and ", $sql_where_and);
	$sql = "select $sql_select
		from `IN7_MK_BAZA_DYSTRYBUCJI` as p
		where
			$sql_where
	";
	$projekty = array();
	$res = DB::query( $sql );
	while ( $r = DB::fetch( $res ) ) {
		$projekty [$r->ID] = $r;
	}

	if ($projekt_id > 0) {
		if (!array_key_exists($projekt_id, $projekty)) {
			die('Error: Projekt nie istnieje lub nie ma statusu WAITING lub NORMAL.');
		}

		$r =& $projekty[$projekt_id];
		$files = PROJEKT__find_folder( $r->ID );
		if (in_array($r->M_DIST_TYPE, array('WWW_AKTUALNOSCI', 'WWW_AKTUALNOSCI_TV'))) {
			$files_add = PROJEKT__find_folder( $r->ID, 'ZDJECIE', array('jpg','png','gif') );
			// TODO: create image files - convert to specified format: 700x700, 150x120
			// name, path, www
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">files_add: ';print_r($files_add);echo'</pre>';
			foreach ($files_add as $f) {
				$tmp_folder_path = $sync_projekty_tmp_folder.'/'.$r->ID;
				if (!is_dir($tmp_folder_path)) {
					mkdir($tmp_folder_path);
				}
				Lib::loadClass('DB_Image');
				$img_ext = end( explode('.', $f['name']) );
				if ($img_ext == 'jpg') $im = imagecreatefromjpeg($f['path']);
				else if ($img_ext == 'png') $im = imagecreatefrompng($f['path']);
				else if ($img_ext == 'gif') $im = imagecreatefromgif($f['path']);

				$sizes_all = array( array('700', '700'), array('150', '120') );
				foreach ($sizes_all as $sizes) {
					$tmp_name = substr($f['name'], 0, -4).'.'.$sizes[0].'x'.$sizes[1].'.'.$img_ext;
					$tmp_path = $tmp_folder_path.'/'.$tmp_name;
					$files []= array('name'=>$tmp_name,'path'=>$tmp_path);
					$im = DB_Image::resize_image_from_data($im, $sizes[0], $sizes[1]);
					if ($img_ext == 'jpg') imagejpeg($im, $tmp_path);
					else if ($img_ext == 'png') imagepng($im, $tmp_path);
					else if ($img_ext == 'gif') imagegif($im, $tmp_path);
				}//end foreach
			}//end foreach
		}
		if (empty($files)) {
			die('Error: Nie odnaleziono plikow Projektu.');
		}
		foreach ($files as $f) {
			echo "file:".$f['name']." ";
			// string exec ( string $command [, array &$output [, int &$return_var ]] )
			$cmd = $sync_project_file_command." ".$r->ID." ".$f['path'];
			$output = array();
			$ret_val = 0;
			exec($cmd, $output, $ret_val);
			$completed = false;
			if ($ret_val == 0) {
				foreach ($output as $out_line) {
					if (strpos($out_line, 'Transfer complete') !== false) {
						$completed = true;
					}
				}//end foreach
			}
			if ($completed) {
				echo "Plik skopiowano.\n";
			} else {
				echo "Error: prawdopodobnie nie udalo sie skopiowac pliku.\n";
				foreach ($output as $out_line) {
					echo $out_line."\n";
				}//end foreach
			}
		}//end foreach
	}
	else {
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">'."<b>projekty:</b>\n";
		//print_r($projekty);
		foreach ($projekty as $k_id => $r) {
			echo " projekt ".$r->ID.":\n";
			if (in_array($r->M_DIST_TYPE, array('WWW_AKTUALNOSCI', 'WWW_AKTUALNOSCI_TV'))) {
				$files = PROJEKT__find_folder( $r->ID, 'ZDJECIE', 'jpg' );
				foreach ($files as $f) {
					echo "  file: ".$f['path']."\n";
				}//end foreach
			}
			$files = PROJEKT__find_folder( $r->ID, $r->M_DIST_TYPE );
			foreach ($files as $f) {
				echo "  file: ".$f['path']."\n";
			}//end foreach
		}//end foreach
		echo'</pre>';
	}

}// fetch active projects


// TODO: @sowa: Call to undefined function ftp_connect()
if(0){// fetch current file list on www
	$ftp_server = 'www.biall.net.pl';
	$ftp_user = 'biallnet';
	$ftp_pass = '100noga';
	$ftp_conn = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
	if (ftp_login($ftp_conn, $ftp_user, $ftp_pass)) {
		ftp_chdir($ftp_conn, 'public_html/PROJEKTY');
	}
	$list = ftp_nlist($ftp_conn, 'public_html/PROJEKTY');
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';
	echo "<b>Pliki na www:</b>\n";
	if (empty($list)) {
		echo'brak plikow';
	} else {
		foreach ($list as $f) {
			echo 'file: '.$f."\n";
		}//end foreach
	}
	echo'</pre>';
}// fetch current file list on www



function PROJEKT__find_folder( $project_id, $type = '', $suffix = 'pdf' ) {
	global $FOLDERS;

	$ret = array();
	//global $FOLDERS;
	// @see .config:$FOLDERS[IN7_MK_BAZA_DYSTRYBUCJI_COLUMN]="/home/samba/PROJEKTY";
	$dir_projekty = $FOLDERS['IN7_MK_BAZA_DYSTRYBUCJI_COLUMN'];
	//$www_projekty = "PROJEKTY/";

echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">IN7_MK_BAZA_DYSTRYBUCJI_COLUMN (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($FOLDERS['IN7_MK_BAZA_DYSTRYBUCJI_COLUMN']);echo'</pre>';

	$pattern = $dir_projekty.'/'.$project_id.'.*';
	$path_projekt = glob( $pattern , GLOB_ONLYDIR );// array glob(pattern [, flags])
	if (empty($path_projekt)) {
		return $ret;
	}
	$path_projekt = reset( $path_projekt );
	$dir_projekt = end( explode('/', $path_projekt) );

	if (is_array($suffix)) {
		$files_projekt_add = array();
		foreach ($suffix as $add_suffix) {
			$files_oferty_pattern = $path_projekt.'/*.'.$add_suffix;
			if ($type) $files_oferty_pattern = $path_projekt.'/*.'.$type.'.*.'.$add_suffix;
			$files_projekt_add = glob( $files_oferty_pattern );// array glob(pattern [, flags])
			foreach ($files_projekt_add as $f) {
				$files_projekt []= $f;
			}//end foreach
		}//end foreach
	} else {
		$files_oferty_pattern = $path_projekt.'/*.'.$suffix;
		if ($type) $files_oferty_pattern = $path_projekt.'/*.'.$type.'.*.'.$suffix;
		$files_projekt = glob( $files_oferty_pattern );// array glob(pattern [, flags])
	}

	foreach ($files_projekt as $v) {
		$f_name = end( explode('/', $v) );
		// TODO: f_www link do akryptu zmieniajacego nazwe pliku na nazwe projektu
		//$f_www = 'http://'.$host.'/'.$www_projekty.'/'.$dir_projekt.'/'.$f_name;
		//$f_www = 'http://'.$host.'/index.php?action=project_file&project='.$project_id.'&f='.$f_name;
		$f_www = '';
		$ret []= array('name'=>$f_name, 'path'=>$v, 'www'=>$f_www);
	}//end foreach

	return $ret;
}
