<?php // field_builder.php - Create field
// ------------------------------------------------------------------------
// 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.
// ------------------------------------------------------------------------

include("include.php");

function add_field($project_id, $step, $cmdtype = 'form', $verbose = false) {
	global $t, $db, $QUERY, $me, $STRING;

	// filter project_id
	if ($project_id != 'public')
		$project_id = intval($project_id);
	
	$values = null;
	
	// if step is uncorrect
	if (($step < 1) || ($step > 3)) {		
		death('INVALID PARAMETER VALUE', '01 add_field_manager() : wrong step.');
	}
	
	// compare the new step with the previous step
	// if it's the first time the user add a field or if the sequence isn't correct
	if (!isset($_SESSION['add_field_step']) || ($_SESSION['add_field_step'] != ($step - 1))) {
		$_SESSION['add_field_step'] = 1; // go to first step		
	} else {
		// the sequence is correct
		$_SESSION['add_field_step'] = $step; // the current step is saved
	}
	
	if (isset($_SESSION['new_field']))
		$new_field = &$_SESSION['new_field'];
	else
		$_SESSION['new_field'] = array();
	
	// what are the existing types ?
	$sql = "SELECT * FROM " . TBL_FIELD_TYPE;
	$res = $db->query($sql);
	if(DB::isError($res)) {
		death("DB ERROR", "02 add_field_manager() : error when trying to list all field types.<br>" . $res->getMessage());
	}
	$available_types = fetchall($res);
	
	// for step 2
	$toPrint = array();
	$toPrint['maxlen'] = false;
	$toPrint['int_size'] = false;
	$toPrint['decimal_size'] = false;
	$toPrint['read_only'] = true;
	$toPrint['unique'] = false;
	$toPrint['highlight_url'] = false;
	$toPrint['time_type'] = false;
	$toPrint['SB_List'] = false;
	
	switch(strtolower($cmdtype)) {
		case 'form' :
			switch($step) {
				case 1 :
					$t->assign('available_types', $available_types);					
					break;
				case 3 :
					$temp_sp = &new MPSubProperty($new_field['properties']);					
					$t->assign('new_field_sp', $temp_sp);
				case 2 :
					// get the MPSubProperty class vars
					$sp_vars = get_class_vars('mpsubproperty');
					switch($new_field['field_type_title']) {
						case SELECTBOX_TYPE :
							$toPrint['unique'] = true;
							break;
						case SELECT_TWINBOX_TYPE :
							foreach ($available_types as $k=>$v)
							{
							if ($v['field_type_title']== SELECTBOX_TYPE)
								{
									$sb_type_id=$v['field_type_id'];	
								}
							}
							$sql = "SELECT field_conf_id, title FROM " . TBL_FIELD_CONF . " WHERE field_type_id = $sb_type_id and (project_id=1 or project_id=$project_id)";
							$res2 = $db->query($sql);
							if(DB::isError($res2)) {
								death("DB ERROR", "02 add_field_manager() : error when trying to list all selectBox.<br>" . $res->getMessage());
							}
							
							$available_SB = fetchall($res2);
							$toPrint['SB_List'] = $available_SB;
							break;
						case INTEGER_TYPE :
							$prop_name = 'int_size';
							$toPrint[$prop_name] = true;
							$t->assign("{$prop_name}_limit_msg", sprintf(str_replace("'", "\\'", $STRING['warning_interval_limited']), $sp_vars["{$prop_name}_min"], $sp_vars["{$prop_name}_max"]));
							break;
						case FLOAT_TYPE :
							$prop_name = 'int_size';
							$toPrint[$prop_name] = true;
							$t->assign("{$prop_name}_limit_msg", sprintf(str_replace("'", "\\'", $STRING['warning_interval_limited']), $sp_vars["{$prop_name}_min"], $sp_vars["{$prop_name}_max"]));
							$prop_name = 'decimal_size';
							$toPrint[$prop_name] = true;
							$t->assign("{$prop_name}_limit_msg", sprintf(str_replace("'", "\\'", $STRING['warning_interval_limited']), $sp_vars["{$prop_name}_min"], $sp_vars["{$prop_name}_max"]));
							break;
						case STRING_TYPE :
							$prop_name = 'maxlen';
							$toPrint[$prop_name] = true;
							$t->assign("{$prop_name}_limit_msg", sprintf(str_replace("'", "\\'", $STRING['warning_interval_limited']), $sp_vars["{$prop_name}_min"], $sp_vars["{$prop_name}_max"]));
							$toPrint['highlight_url'] = true;
							break;
						case TIMESTAMP_TYPE :
							// list all time types
							$test = &new MPSubProperty('');							
							$toPrint['time_type'] = $test->_type_enum['time_type'];							
							break;
						default :
							death('ERROR', '04 add_field_manager() : Unknown type name');
					} // end of switch($new_field['field_type_title'])
					$t->assign('toPrint', $toPrint); // assign what to print in the form at step 2
					break;				
			} // end of switch($step)
			
			// assign data
			$t->assign('validate_edit_url', $me . "?id=$project_id&step=" . ($step));
			$t->assign('new_field', $new_field);
			
			$t->wrap("admin/field-add-step{$step}.html");
			break;
		///////////////////////////
		case 'treat' :
			switch($step) {
				case 1 :
					// catch post data and filter it
					$new_field['field_type_title'] = stripslashes($_POST['field_type_title']);
					$new_field['title'] = trim(strip_tags(stripslashes($_POST['title'])));
					$new_field['description'] =  strip_tags(stripslashes($_POST['description']));
					$new_field['default_value'] = stripslashes($_POST['default_value']);
					$new_field['edit_order'] = intval($_POST['edit_order']);
					$new_field['list_order'] = intval($_POST['list_order']);
					
					if (strlen($new_field['title']) == 0) {
					    death('ERROR EMPTY TITLE', '05 add_field_manager() : the field title must not be empty.');
					}
					
					if (strlen($new_field['default_value']) == 0) {
					    death('ERROR EMPTY DEFAULT VALUE', '05b add_field_manager() : the field default value must not be empty.');
					}
					
					//redirection($me . "?op=add_field&id=$project_id&step=" . ($step + 1));
					//die();
					break;
				case 2 :
					// check the posted subproperties
					if (!isset($_POST['sp']) || !is_array($_POST['sp'])) {
						// death('ERROR', '05 add_field_manager() : posted data is uncorrect.');
						$cur_sp = array();
					} else $cur_sp = $_POST['sp'];
					$str_sp = MPSubProperty::convert_array_to_string($cur_sp);
					// check sp validity
					$test_sp = &new MPSubProperty($str_sp);
					// properties
					$new_field['properties'] = $str_sp;
					
					//redirection($me . "?op=add_field&id=$project_id&step=" . ($step + 1));
					//die();
					break;					
				case 3 :					
					//DEBUG
					// println("MPSubProperty : string : $str");
					
					// create a sp object and set its properties : it's a way to check that sp values are correct
					// $cur_sp_obj = &new MPSubProperty($str);
					
					// we have to create the field conf
					/*
					32 :  	['bug_id'] 	['field_conf_id']  	=	 21
					33 : 	['bug_id'] 	['project_id'] 	=	17
					34 : 	['bug_id'] 	['field_type_id'] 	=	0
					35 : 	['bug_id'] 	['field_name'] 	=	bug_id
					36 : 	['bug_id'] 	['title'] 	=	File #
					37 : 	['bug_id'] 	['description'] 	=	File number
					38 : 	['bug_id'] 	['edit_order'] 	=	0
					39 : 	['bug_id'] 	['list_order'] 	=	1
					40 : 	['bug_id'] 	['default_value'] 	=	
					41 : 	['bug_id'] 	['properties'] 	=	int_size=10;read_only=true;internal_system_use=true;
					42 : 	['bug_id'] 	['created_by'] 	=	38
					43 : 	['bug_id'] 	['created_date'] 	=	0
					44 : 	['bug_id'] 	['last_modified_by'] 	=	38
					45 : 	['bug_id'] 	['last_modified_date'] 	=	1094482683
					46 : 	['bug_id'] 	['field_type_title'] 	=	Integer
					47 : 	['bug_id'] 	['field_type_description'] 	=	Accepts only an integer value.
					*/
					
					// some var initializations
					$mpfile = null;
					
					// get or check project_id and make a mpfile object 
					if (!is_int($project_id)) { // if it's the public project
						$mpfile = &new MPFile();
						$mpfile->project_data['project_id']; // get the public project id
					} else {
						$mpfile = &new MPFile($project_id);
					}	
					// useless to add this because the MPFile obj will use its project_id
					$new_field['created_by'] = intval($_SESSION['uid']);
					
					// get the field type id
					$res = $db->getOne('SELECT field_type_id FROM '. TBL_FIELD_TYPE . ' WHERE field_type_title = ' . $db->quote($new_field['field_type_title']));
					if(DB::isError($res)) {
						death("DB ERROR", "06 add_field_manager() : error when trying get field_type_id.<br>" . $res->getMessage());
					}
					$new_field['field_type_id'] = $res;
					
					// DEBUG
					if ($verbose) {
						println('new field conf');
						printarray($new_field);
					}
					
					// insert field conf
					$return = $mpfile->alterFieldConf($new_field, $selectbox_values = null, $action = 'insert', true, $verbose);
					if ($verbose) {
						println("new field conf ID = $return[field_conf_id]");						
					}
					
					// the default value of a selectbox, at creation time is not a sv_id, but a sv_value
					// we have to create thie selectbox value before creating the actual field
					if ($new_field['field_type_title'] == SELECTBOX_TYPE) {
						$sv_array = array(
							array(
								'field_conf_id' => $return['field_conf_id'],
								// if the user didn't enter a default value, set a default value for him, quoted with '*'
								'value' => ((strlen(trim($new_field['default_value'])) == 0)? '*'. $STRING['FIELD_CONF']['Title']['default_value'] . '*' : trim($new_field['default_value'])),
								'order' => 1,
								'description' => '*'. $STRING['FIELD_CONF']['Title']['default_value']. '*'
							)
						);
						$treated_sv = $mpfile->alterSelectBoxValue($sv_array, "insert", $verbose);
						
						// printarray($treated_sv);
						// $default_value = current($treated_sv);
						$new_field['default_value'] = current($treated_sv);
						$update_res = $db->query("UPDATE " . TBL_FIELD_CONF . " SET default_value = " . $db->quote($new_field['default_value']) 
							. " WHERE field_conf_id = " . $db->quote($return['field_conf_id']));
						if (DB::isError($update_res) || ($db->affectedRows() == 0)) {
							death('DB ERROR', "add_field_manager() : unable to update the default_value of field_conf (fid = " . htmlspecialchars($field_conf_id) . ")");
						}
					}
					
					// $mpfile->reloadCache($verbose);
					// then, insert the real field inside the file table
					//$mpfile->alterField($return['field_conf_id'], $action = "create", $verbose);
					$return = MPFile::alterFieldForAll($return['field_conf_id'], 'create', $verbose);
					
					// reset the new field data stored in session
					$_SESSION['new_field'] = array();					
					redirection($me . "?op=" . (($project_id == 'public')? 'edit_public_fields' : "edit_project_fields&id=$project_id"));
					die();
					break;
			} // end of switch($step)
			// goto next step
			redirection($me . "?op=add_field&id=$project_id&step=" . ($step + 1));
			die();
			break;
	} // end of switch($cmdtype)	
} // end of add_field($project_id, $step, $cmdtype = 'form')

$DiaBuilder="fee";
?>
