<?php

// import.php - not working, shall be refactor
// ------------------------------------------------------------------------
// Copyright (c) 2005, 2006, 2015 Denis Guinnepain
 
// ------------------------------------------------------------------------
// This file is part of Diamentis

// Diamentis is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.

// Diamentis is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with phpBugTracker; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ------------------------------------------------------------------------

chdir('..');
define('TEMPLATE_PATH', 'admin');
include 'include.php';
global $allow_recoding;
$allow_recoding=true;
require_once("phpmyadmin/config.inc.php");
require_once("phpmyadmin/libraries/charset_conversion.lib.php");
@require_once 'backup.php';

function do_import($project_id) {
	global $db,$t,$STRING,$restricted_projects,$my_key;
		$tables = array(
		'/^#.*/' => '', // if line starts with a comment
		'/^--.*/' => '', // if line starts with a comment
		'/TBL_PREFIX/' => TBL_PREFIX,
		'/TBL_ATTACHMENT/' => TBL_PREFIX.'attachment',
		'/TBL_AUTH_GROUP/' => TBL_PREFIX.'auth_group',
		'/TBL_AUTH_PERM/' => TBL_PREFIX.'auth_perm',
		'/TBL_AUTH_USER/' => TBL_PREFIX.'auth_user',
		'/TBL_BUG_CC/' => TBL_PREFIX.'contacts',
		'/TBL_BUG_DEPENDENCY/' => TBL_PREFIX.'bug_dependency',
		'/TBL_FILE_HISTORY/' => TBL_PREFIX.'file_history',
		'/TBL_BUG_VOTE/' => TBL_PREFIX.'bug_vote',
		'/TBL_COMMENT/' => TBL_PREFIX.'comment',
		'/TBL_CONFIGURATION/' => TBL_PREFIX.'configuration',
		'/TBL_GROUP_PERM/' => TBL_PREFIX.'group_perm',
		'/TBL_PROJECT_STATUS/' => TBL_PREFIX . 'project_status',
		'/TBL_PROJECT_GROUP/' => TBL_PREFIX.'project_group',
		'/TBL_PROJECT_PERM/' => TBL_PREFIX.'project_perm',
		'/TBL_PROJECT/' => TBL_PREFIX.'project',
		'/TBL_SAVED_QUERY/' => TBL_PREFIX.'saved_query',
		'/TBL_USER_GROUP/' => TBL_PREFIX.'user_group',
		'/TBL_USER_PREF/' => TBL_PREFIX.'user_pref',
		'/TBL_ASSIGNATION/' => TBL_PREFIX . 'assignation',
		'/TBL_FILE_INDEX/' => TBL_PREFIX . 'file_index',
		'/TBL_FIELD_CONF/' => TBL_PREFIX . 'field_conf',
		'/TBL_FIELD_TYPE/' => TBL_PREFIX . 'field_type',
		'/TBL_SELECTBOX_VALUE/' => TBL_PREFIX . 'selectbox_value',
		'/TBL_SELECTBOX_OPTION/' => TBL_PREFIX . 'selectbox_option',		
		'/TBL_FILE_STATUS/' => TBL_PREFIX . 'file_status'
		);

	$db->setErrorHandling(PEAR_ERROR_RETURN);
	if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//		   echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
	} else {
	   death("ERROR 01 Import : ", " Possible file upload attack: ");
	}
	if ($_FILES['userfile']['size']>(ATTACHMENT_MAX_SIZE*10)) 
	 {
		death("ERROR 02 Import :",  $STRING['import_too_large']);
	}

            if (@function_exists('bzdecompress')) 
            {
                $file = @fopen($_FILES['userfile']['tmp_name'], 'rb');
                if (!$file)
                {
			death("ERROR 03 Import :",  $STRING['import_problem']);
                }
                $mystring = fread($file, filesize($_FILES['userfile']['tmp_name']));
                 fclose($file);
//                 print "la chaine cryptée vaut " . $mystring . "\n";
                 $mystring=@mcrypt_ecb(MCRYPT_TripleDES,$my_key,$mystring, MCRYPT_DECRYPT);
                 $mystring = bzdecompress($mystring);
//                 print $mystring;die;
            }
            else
            {
		death("ERROR 04 Import :",  $STRING['import_problem']);
            }
	//verify table is the good one with the creation datedate
	if (preg_match("/INSERT INTO TBL_PROJECT VALUES .*,\s(\d+),\s\d,\s\d,\s'TBL_PREFIXfile_prj_id_/",$mystring,$date))
//	if (preg_match("/INSERT INTO TBL_PROJECT VALUES(.*),\s\d,\s\d,\s'TBL_PREFIXfile_prj_id_/",$mystring,$date))
	{
		$previous_date=$db->getOne("SELECT created_date FROM " . TBL_PROJECT . " WHERE project_id = " . $project_id);
		if ($date['1']!=$previous_date)
		{
//			print "date1 vaut " . $date['0'] . " et historic date vaut " . $previous_date;
			death("ERROR 05 Import : it seems this domain has never been hosted on this server",  $STRING['import_problem']);		
		}
	}
        else
        {
		death("ERROR 06 Import : ",  $STRING['import_problem']);
        }
		//verification of manipulation of only the TBL_PREFIX_prj_id
		        $table_project = TBL_PREFIX . "file_prj_id_" . $project_id;
		        // verification only drop table the corresponding project table
		        // verification only insert in corresponding project table
//		        preg_match_all("/(?i:INSERT\s+INTO\s" . TBL_PREFIX . "file_prj_id_(\d+))/",$mystring, $matches);
		        preg_match_all("/" . TBL_PREFIX . "file_prj_id_(\d+)/",$mystring, $matches);
			foreach ($matches['1'] as $k=>$v)
			{
				if ($v!=$project_id)
				{
					death("FATAL ERROR", "Illegal Operation detected at importation");
				}
			}
//		        printarray($matches);die;
		        //verify that new field are only from correct project
		        //verify that new selectbox value are from correct fields and from correct project
	$queries= explode("\n",$mystring);
	$queries = preg_replace(array_keys($tables), array_values($tables),$queries);
	$do_query = '';
	foreach ($queries as $query) 
	{
		// First, collect multi-line queries into one line, then run the query
		$do_query .= chop($query);
		if (empty($do_query) or substr($do_query, -1) != ';') continue;
		$do_query = str_replace('\\\'', '\'\'', $do_query); 		
		$res = $db->query($do_query);		
		if(DB::isError($res))
		{
//			echo ("<br> Error : " . $res->getMessage() . "<br>");
//			print($do_query . "<br>");
		}
		else 
		{
//			echo "query = ".stripslashes($do_query)."<br><br>";		
		}
		$do_query = '';
	}
	$t->assign('back_url', "project.php?op=edit&id=" . $project_id);	
	$t->assign('action',"end_import");
	$t->assign('project_id',$project_id);
	$t->wrap(TEMPLATE_PATH . "/" . 'import.html');
} // end of do_import()

function do_select($project_id)
{
global $t;
	$t->assign('back_url', "project.php?op=edit&id=" . $project_id);	
	$t->assign('action',"select");
	$t->assign('project_id',$project_id);
	$t->wrap(TEMPLATE_PATH . "/" . 'import.html');

}

function do_warning($project_id)
{
global $t;
	$t->assign('back_url', "project.php?op=edit&id=" . $project_id);	
	$t->assign('action',"warning");
	$t->assign('project_id',$project_id);
	$t->wrap(TEMPLATE_PATH . "/" . 'import.html');

}

//$perm->check('Admin');
if (isset($_gv['op'])) {
    switch($_gv['op']) {
	case 'import':
	    if (isset($_pv['id']))
	    {
		    if ($perm->have_project_perm($_pv['id'],'Admin'))
		    {
    			if($_pv['op']=='import') 
    			{
		    		do_import($_pv['id']);
		        }
		        elseif ($_pv['op']=='warning_accepted') 
    			{
		    		do_select($_pv['id']);
		        }
		     }
		    else
		    {
        	        $perm->perm_invalid('AdminProject', $_pv['id']);
		    }
	    }
	    else
	    {
	    	death("ERROR","missing post var");
	    }
	break;
	case 'show':
	default:
	     if ($perm->have_project_perm($_gv['id'],'Admin')) 
	     {
		do_warning($_gv['id']);
	    }
	    else
	    {
                $perm->perm_invalid('AdminProject', $_pv['id']);
	    }
		break;
    }
}
else print("RAF");
?>