<commit_before><?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
// 
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function wikiplugin_tracker_info()
{
	return array(
		'name' => tra('Tracker'),
		'documentation' => 'PluginTracker',
		'description' => tra('Create a form in a wiki page to populate a tracker'),
		'tags' => array( 'basic' ),			
		'prefs' => array( 'feature_trackers', 'wikiplugin_tracker' ),
		'body' => tra('Confirmation message after posting form'),
		'icon' => 'pics/icons/application_form.png',
		'params' => array(
			'trackerId' => array(
				'required' => true,
				'name' => tra('Tracker ID'),
				'description' => tra('Numeric value representing the tracker ID'),
				'filter' => 'digits',
				'default' => '',
			),
			'fields' => array(
				'required' => false,
				'name' => tra('Fields'),
				'description' => tra('Colon-separated list of field IDs to be displayed. Example: 2:4:5  If empty, all fields will be shown'),
				'default' => '',
			),
			'action' => array(
				'required' => false,
				'name' => tra('Action'),
				'description' => tra('Label on the submit button. Default is "Save".'),
				'separator' => ':',
				'default' => 'Save'
			),
			'showtitle' => array(
				'required' => false,
				'name' => tra('Show Title'),
				'description' => tra('Display the title of the tracker (not shown by default)'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'showdesc' => array(
				'required' => false,
				'name' => tra('Show Description'),
				'description' => tra('Show the tracker\'s description (not shown by default)'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'showmandatory' => array(
				'required' => false,
				'name' => tra('Mark Mandatory'),
				'description' => tra('Indicate mandatory fields with an asterisk (shown by default).'),
				'filter' => 'alpha',
				'default' => 'y',
						'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'showstatus' => array(
				'required' => false,
				'name' => tra('Show Status'),
				'description' => tra('Show the status of the items (not shown by default)'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'embedded' => array(
				'required' => false,
				'name' => tra('Embedded'),
				'description' => tra('Embedded'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'email' => array(
				'required' => false,
				'name' => tra('Email'),
				'description' => tra('To send an email once the tracker item has been created. Format: from').'|'.tra('to').'|'.tra('template'),
				'default' => '',
			),
			'emailformat' => array(
				'required' => false,
				'name' => tra('Email format'),
				'description' => tra('Text or html setting'),				
				'default' => 'text',
			),			
			'url' => array(
				'required' => false,
				'name' => tra('URL'),
				'description' => tra('URL the user is sent to after the form is submitted'),
				'filter' => 'url',
				'separator' => ':',
				'default' => '',
			),
			'target' => array(
				'required' => false,
				'name' => tra('URL Target'),
				'description' => tra('Set the target parameter for the url (determines whether target will open in a new page, etc.'),
				'default' => '',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Blank'), 'value' => '_blank'), 
					array('text' => tra('Parent'), 'value' => '_parent'),
					array('text' => tra('Self'), 'value' => '_self'),
					array('text' => tra('Top'), 'value' => '_top')
				)
			),
			'values' => array(
				'required' => false,
				'name' => tra('Values'),
				'description' => tra('Colon-separated list of default values.for the fields. First value corresponds to first field, second value to second field, etc.'),
				'default' => '',
			),
			'overwrite' => array(
				'required' => false,
				'name' => tra('Overwrite'),
				'description' => tra('Overwrite current field values of the item with the input values'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'sort' => array(
				'required' => false,
				'name' => tra('Sort'),
				'description' => tra('Display columns in the order listed in the fields parameter instead of by field ID (field ID order is used by default'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'preview' => array(
				'required' => false,
				'name' => tra('Preview'),
				'description' => tra('Label for the preview button. Default:').' "'. tra('Preview') . '"',
				'default' => 'Preview',
			),
			'reset' => array(
				'required' => false,
				'name' => tra('Reset'),
				'description' => tra('Label for the reset button, to return all fields to their default values.'),
				'default' => tra('reset'),
			),
			'view' => array(
				'required' => false,
				'name' => tra('View'),
				'description' => tra('View'),
				'default' => '',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Group'), 'value' => 'group'), 
					array('text' => tra('Page'), 'value' => 'page'),
					array('text' => tra('User'), 'value' => 'user')
				)
			),
			'status' => array(
				'required' => false,
				'name' => tra('Status'),
				'description' => tra('Status of the item used in combination with:').' view=user',
				'default' => '',
			),
			'itemId' =>array(
				'required' => false,
				'name' => tra('ItemId'),
				'description' => tra('ItemId allowing for editing an item'),
				'filter' => 'digits',
				'default' => '',
			),
			'ignoreRequestItemId' => array(
				'required' => false,
				'name' => tra('Ignore ItemId'),
				'description' => tra('Do not filter on the parameter itemId if in the url'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'tpl' => array(
				'required' => false,
				'name' => tra('Template File'),
				'description' => tra('Name of the template used to display the tracker items.'),
				'default' => '',
			),
			'wiki' => array(
				'required' => false,
				'name' => tra('Wiki'),
				'description' => tra('Name of the wiki page containing the template to display the tracker items.'),
				'filter' => 'pagename',
				'default' => '',
			),
			'newstatus' => array(
				'required' => false,
				'name' => tra('New Status'),
				'description' => tra('Default status applied to newly created items.'),
				'filter' => 'alpha',
				'default' => '',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Open'), 'value' => 'o'), 
					array('text' => tra('Pending'), 'value' => 'p'),
					array('text' => tra('Closed'), 'value' => 'c')
				)
			),
			'colwidth' => array(
				'required' => false,
				'name' => tra('Width'),
				'description' => tra('Specify the width in pixels or percentage of the first column (the labels) in the tracker form.'),
				'default' => '',
				'accepted' => '## or ##%',
			),
			'autosavefields' => array(
				'required' => false,
				'name' => tra('Autosave fields'),
				'description' => tra('Colon-separated list of field IDs to be automatically filled with values'),
				'filter' => 'digits',
				'separator' => ':',
				'default' => '',
			),
			'autosavevalues' => array(
				'required' => false,
				'name' => tra('Autosavevalue'),
				'description' => tra('Colon-separated values corresponding to autosavefields'),
				'filter' => 'text',
				'separator' => ':',
				'default' => '',
			),
			'registration' => array(
				'required' => false,
				'name' => tra('Registration Fields'),
				'description' => tra('Add registration fields such as Username and Password'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'outputtowiki' => array(
				'required' => false,
				'name' => tra('Output To Wiki'),
				'description' => tra('Output result to a new wiki page with the name taken from the input for the specified fieldId'),
				'filter' => 'digits',
				'default' => '',
			),
			'discarditem' => array(
				'required' => false,
				'name' => tra('Discard After Output'),
				'description' => tra('Used when results are output to a wiki page to discard the tracker item itself once the wiki page is created'),
				'filter' => 'alpha',
				'default' => '',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'outputwiki' => array(
				'required' => false,
				'name' => tra('Template Page'),
				'description' => tra('Name of the wiki page containing the template to format the output to wiki page'),
				'filter' => 'pagename',
				'default' => '',
			),
			'formtag' => array(
				'required' => false,
				'name' => tra('Embed the tracker in a form tag'),
				'description' => tra('If set to Yes, the tracker is contained in a <form> tag and has action buttons'),
				'filter' => 'alpha',
				'default' => 'y',
				'options' => array(
					array('text' => '', 'value' => ''),
					array('text' => tra('Yes'), 'value' => 'y'),
					array('text' => tra('No'), 'value' => 'n')
				)
			),
		),
	);
}

function wikiplugin_tracker_name($fieldId, $name, $field_errors)
{
	foreach($field_errors['err_mandatory'] as $f) {
		if ($fieldId == $f['fieldId'])
			return '<span class="highlight">'.$name.'</span>';
	}
	foreach($field_errors['err_value'] as $f) {
		if ($fieldId == $f['fieldId'])
			return '<span class="highlight">'.$name.'</span>';
	}
	return $name;
}

function wikiplugin_tracker($data, $params)
{
	global $tikilib, $userlib, $user, $group, $page, $smarty, $prefs, $trklib, $captchalib;
	$parserlib = TikiLib::lib('parser');

	static $iTRACKER = 0;
	++$iTRACKER;
	if (isset($params['itemId']) && empty($params['itemId']))
		return;
	include_once('lib/trackers/trackerlib.php');
	$default = array('overwrite' => 'n', 'embedded' => 'n', 'showtitle' => 'n', 'showdesc' => 'n', 'sort' => 'n', 'showmandatory'=>'y', 'status' => '', 'registration' => 'n', 'emailformat' => 'text');
	$params = array_merge($default, $params);
	$item = array();
	
	extract ($params, EXTR_SKIP);

	if ($prefs['feature_trackers'] != 'y') {
		return $smarty->fetch("wiki-plugins/error_tracker.tpl");
	}
	if (empty($trackerId) || !($tracker = $trklib->get_tracker($trackerId))) {
		return $smarty->fetch("wiki-plugins/error_tracker.tpl");
	}
	if ($t = $trklib->get_tracker_options($trackerId)) {
		$tracker = array_merge($tracker, $t);
	}
	if (empty($trackerId) && !empty($view) && $view == 'user' && $prefs['userTracker'] == 'y') { // the user tracker item
		$utid = $userlib->get_tracker_usergroup($user);
		if (!empty($utid) && !empty($utid['usersTrackerId'])) {
			$itemId = $trklib->get_item_id($utid['usersTrackerId'], $utid['usersFieldId'], $user);
			$trackerId = $utid['usersTrackerId'];
			$usertracker = true;
		}
	} elseif (!empty($trackerId) && !empty($view) && $view == 'user') {// the user item of a tracker
		$itemId = $trklib->get_user_item($trackerId, $tracker, null, null, strlen($status) == 1 ? $status : '');
		$usertracker = true;
	} elseif (!empty($trackerId) && !empty($view) && $view == 'page' && !empty($_REQUEST['page']) && (($f = $trklib->get_field_id_from_type($trackerId, 'k', '1%')) || ($f = $trklib->get_field_id_from_type($trackerId, 'k', '%,1%')) || ($f =  $trklib->get_field_id_from_type($trackerId, 'k')))) {// the page item
		$itemId = $trklib->get_item_id($trackerId, $f, $_REQUEST['page']);
	} elseif (!empty($trackerId) && !empty($_REQUEST['view_user'])) {
		$itemId = $trklib->get_user_item($trackerId, $tracker, $_REQUEST['view_user']);
	} elseif (!empty($_REQUEST['itemId']) && (empty($ignoreRequestItemId) || $ignoreRequestItemId != 'y')) {
		$itemId = $_REQUEST['itemId'];
		$item = $trklib->get_tracker_item($itemId);
		$trackerId = $item['trackerId'];
	} elseif (!empty($view) && $view == 'group') {
		$gtid = $userlib->get_grouptrackerid($group);
		if(isset($gtid['groupTrackerId'])) {
			$trackerId = $gtid['groupTrackerId'];
			$itemId = $trklib->get_item_id($trackerId, $gtid['groupFieldId'], $group);
			$grouptracker = true;
		}
	}
	if (!isset($trackerId)) {
		return $smarty->fetch("wiki-plugins/error_tracker.tpl");
	}

	if (!isset($action)) {
		$action = array('Save');
	}
	if (!is_array($action)) {
		$action = array( $action );
	}
	if (isset($preview)) {
		if (empty($preview)) {
			$preview = 'Preview';
		}
	} else {
		unset($_REQUEST['tr_preview']);
	}
	if (isset($reset)) {
		if (empty($reset)) {
			$reset = 'reset';
		}
	} else {
		unset($_REQUEST['tr_reset']);
	}
	$smarty->assign('showmandatory',  empty($wiki) && empty($tpl)? 'n': $showmandatory); 
	if (!empty($wiki)) {
		if (preg_match('/^wiki:(.+)$/', $wiki, $wiki_matches)) {
			$wiki = $wiki_matches[1];
		}

		$wiki = trim($wiki);
	}

	if (!isset($params['formtag'])) {
		$params['formtag'] = 'y';
	}

	$fields_prefix = 'ins_';

	if (isset($values)) {
		if (!is_array($values)) {
			$values = $parserlib->quotesplit(':', $values);
			foreach ($values as $i=>$v) {
				$values[$i] = preg_replace('/^"(.*)"$/', '$1', $v);
			}
		}
	}
	if (isset($_REQUEST['values'])) {
		if (is_array($_REQUEST['values'])) {
			foreach ($_REQUEST['values'] as $i=>$k) {
				$_REQUEST['values'][$i] = urldecode($k);
			}
		} else {
			$_REQUEST['values'] = urldecode($_REQUEST['values']);
		}
	}

	$perms = $tikilib->get_perm_object($trackerId, 'tracker', $tracker, false);
	
	if (empty($_SERVER['SCRIPT_NAME']) || strpos($_SERVER['SCRIPT_NAME'], 'tiki-register.php') === false) {
		if (!empty($itemId) && $tracker['writerCanModify'] == 'y' && isset($usertracker) && $usertracker) { // user tracker he can modify
		} elseif (!empty($itemId) && $tracker['writerCanModify'] == 'y' && $user && (($itemUser = $trklib->get_item_creator($trackerId, $itemId)) == $user || ($tracker['userCanTakeOwnership'] == 'y' && empty($itemUser)))) {
		} elseif (!empty($itemId) && isset($grouptracker) && $grouptracker) {
		} else {
			if ($perms['tiki_p_create_tracker_items'] == 'n' && empty($itemId)) {
				return '<b>'.tra("You do not have permission to insert an item").'</b>';
			} elseif (!empty($itemId)) {
				$item_info = $trklib->get_tracker_item($itemId);
				if (!(($perms['tiki_p_modify_tracker_items'] == 'y' and $item_info['status'] != 'p' and $item_info['status'] != 'c') || ($perms['tiki_p_modify_tracker_items_pending'] == 'y' and $item_info['status'] == 'p') ||  ($perms['tiki_p_modify_tracker_items_closed'] == 'y' and $item_info['status'] == 'c'))) { 
					if ($tracker['writerGroupCanModify'] == 'y' && in_array($trklib->get_item_group_creator($trackerId, $itemId), $tikilib->get_user_groups($user))) {
						global $group;
						$smarty->assign_by_ref('ours', $group);
					} else 
						return '<b>'.tra("You do not have permission to modify an item").'</b>';
				}
			}
		}
	}
	if (!empty($itemId)) {
		global $logslib; include_once('lib/logs/logslib.php');
		$logslib->add_action('Viewed', $itemId, 'trackeritem', $_SERVER['REQUEST_URI']);
	}

	if (isset($_REQUEST['removeattach']) && $tracker['useAttachments'] == 'y') {
		$owner = $trklib->get_item_attachment_owner($_REQUEST['removeattach']);
		if ($perms['tiki_p_admin_trackers'] == 'y' || ($user && $user == $owner)) {
			$trklib->remove_item_attachment($_REQUEST["removeattach"]);
			unset($_REQUEST['removeattach']);
		}
	}
	if (isset($_REQUEST['removeImage']) && !empty($_REQUEST['trackerId']) && !empty($_REQUEST['itemId']) && !empty($_REQUEST['fieldId']) && !empty($_REQUEST['fieldName'])) {
		$img_field = array('data' => array());
		$img_field['data'][] = array('fieldId' => $_REQUEST['fieldId'], 'type' => 'i', 'name' => $_REQUEST['fieldName'], 'value' => 'blank');
		$trklib->replace_item($_REQUEST['trackerId'], $_REQUEST['itemId'], $img_field);
	}
	$back = '';
	$js = '';

	$thisIsThePlugin = isset($_REQUEST['iTRACKER']) && $_REQUEST['iTRACKER'] == $iTRACKER;

	if (!isset($_REQUEST["ok"]) || $_REQUEST["ok"]  == "n" || !$thisIsThePlugin || isset($_REQUEST['tr_preview'])) {
		$field_errors = array('err_mandatory'=>array(), 'err_value'=>array());
	
			global $notificationlib; include_once('lib/notifications/notificationlib.php');
			$tracker = $trklib->get_tracker($trackerId);
			$tracker = array_merge($tracker, $trklib->get_tracker_options($trackerId));
			if ((!empty($tracker['start']) && $tikilib->now < $tracker['start']) || (!empty($tracker['end']) && $tikilib->now > $tracker['end']))
				return;
			$outf = array();
			if (!empty($fields)  || !empty($wiki) || !empty($tpl)) {
				if ($registration == 'y' && $prefs["user_register_prettytracker"] == 'y' && !empty($prefs["user_register_prettytracker_tpl"])) {
					$smarty->assign('register_login', $smarty->fetch('register-login.tpl'));
					$smarty->assign('register_email', $smarty->fetch('register-email.tpl'));
					$smarty->assign('register_pass', $smarty->fetch('register-pass.tpl'));
					$smarty->assign('register_pass2', $smarty->fetch('register-pass2.tpl'));
					$smarty->assign('register_passcode', $smarty->fetch('register-passcode.tpl'));
					$smarty->assign('register_groupchoice', $smarty->fetch('register-groupchoice.tpl'));
					$smarty->assign('register_antibot', $smarty->fetch('antibot.tpl'));
					$wiki = $prefs["user_register_prettytracker_tpl"];
				}
				if (!empty($wiki)) {
					$outf = $trklib->get_pretty_fieldIds($wiki, 'wiki', $outputPretty);
				} elseif (!empty($tpl)) {
					$outf = $trklib->get_pretty_fieldIds($tpl, 'tpl', $outputPretty);
				} elseif (!empty($fields)) {
					$outf = preg_split('/ *: */', $fields);
				}
				if (!empty($_REQUEST['autosavefields'])) {
					$autosavefields = explode(':', $_REQUEST['autosavefields']);
					$autosavevalues = explode(':', $_REQUEST['autosavevalues']);
					if (isset($params['autosavefields'])) {
						$autosavefields = array_merge($autosavefields, $params['autosavefields']);
						$autosavevalues = array_merge($autosavevalues, $params['autosavevalues']);
					}
				}
				if (!empty($autosavefields)) {
					$outf = array_merge($outf, $autosavefields);
				}
			}

			$definition = Tracker_Definition::get($trackerId);
			$item_info = isset($item_info) ? $item_info : array();
			$factory = $definition->getFieldFactory();
			if (empty($outf)) {
				$flds = array('data' => $definition->getFields());
			} else {
				$flds = array('data' => array());
				foreach ($outf as $fieldId) {
					$flds['data'][] = $definition->getField($fieldId);
				}
			}
			$bad = array();
			$embeddedId = false;
			$onemandatory = false;
			$full_fields = array();
			$mainfield = '';

			if ($thisIsThePlugin) {
				/* ------------------------------------- Recup all values from REQUEST -------------- */
				foreach ($flds['data'] as $fl) {
					// First convert track_xx to array (need to be up here before setting autosave fields)
					$incomingTrackName = $fields_prefix . $fl["fieldId"];
					if (isset($_REQUEST[$incomingTrackName])) {
						$_REQUEST['track'][$fl["fieldId"]] = $_REQUEST[$incomingTrackName];
					} else if (isset($_FILES[$incomingTrackName])) {	// also for uploaded files
						foreach ($_FILES[$incomingTrackName] as $lbl => $val) {
							$_FILES['track'][$lbl][$fl["fieldId"]] = $val;
						}
					}
				}
				if (!empty($autosavefields)) {
					foreach ($autosavefields as $i=>$f) {
						if (!$ff = $trklib->get_field($f, $flds['data'])) {
							continue;
						}
						if (!$trklib->fieldId_is_editable($ff, $item_info)) {
							continue;
						}
						if (preg_match('/categories\(([0-9]+)\)/', $autosavevalues[$i], $matches)) {
							if (ctype_digit($matches[1]) && $matches[1] > 0) {
								$filter = array('identifier'=>$matches[1], 'type'=>'descendants'); 
							} else {
								$filter = NULL;
							}
							global $categlib; include_once('lib/categories/categlib.php');
							$categs = $categlib->getCategories($filter, true, false);
							$_REQUEST["ins_$f"][] = $categs[0]['categId'];
						} elseif (preg_match('/preference\((.*)\)/', $autosavevalues[$i], $matches)) {
							$_REQUEST["$ins_id_$f"] = $prefs[$matches[1]];
						} elseif ($ff['type'] == 'e') {
							$_REQUEST["ins_$f"][] = $autosavevalues[$i];
						} else {
							$_REQUEST['track'][$f] = $autosavevalues[$i];
						}
					}
				}
				foreach ($flds['data'] as $k => $field) {
					$handler = $factory->getHandler($field, $item_info);

					if ($handler) {
						$ins_fields['data'][$k] = array_merge($field, $handler->getFieldData($_REQUEST));
					}
				}
				$cpt = 0;
				if (isset($fields)) {<commit_msg>[FIX] autosavefields not saving<commit_after><?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
// 
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function wikiplugin_tracker_info()
{
	return array(
		'name' => tra('Tracker'),
		'documentation' => 'PluginTracker',
		'description' => tra('Create a form in a wiki page to populate a tracker'),
		'tags' => array( 'basic' ),			
		'prefs' => array( 'feature_trackers', 'wikiplugin_tracker' ),
		'body' => tra('Confirmation message after posting form'),
		'icon' => 'pics/icons/application_form.png',
		'params' => array(
			'trackerId' => array(
				'required' => true,
				'name' => tra('Tracker ID'),
				'description' => tra('Numeric value representing the tracker ID'),
				'filter' => 'digits',
				'default' => '',
			),
			'fields' => array(
				'required' => false,
				'name' => tra('Fields'),
				'description' => tra('Colon-separated list of field IDs to be displayed. Example: 2:4:5  If empty, all fields will be shown'),
				'default' => '',
			),
			'action' => array(
				'required' => false,
				'name' => tra('Action'),
				'description' => tra('Label on the submit button. Default is "Save".'),
				'separator' => ':',
				'default' => 'Save'
			),
			'showtitle' => array(
				'required' => false,
				'name' => tra('Show Title'),
				'description' => tra('Display the title of the tracker (not shown by default)'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'showdesc' => array(
				'required' => false,
				'name' => tra('Show Description'),
				'description' => tra('Show the tracker\'s description (not shown by default)'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'showmandatory' => array(
				'required' => false,
				'name' => tra('Mark Mandatory'),
				'description' => tra('Indicate mandatory fields with an asterisk (shown by default).'),
				'filter' => 'alpha',
				'default' => 'y',
						'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'showstatus' => array(
				'required' => false,
				'name' => tra('Show Status'),
				'description' => tra('Show the status of the items (not shown by default)'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'embedded' => array(
				'required' => false,
				'name' => tra('Embedded'),
				'description' => tra('Embedded'),
				'filter' => 'alpha',
				'default' => 'n',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'email' => array(
				'required' => false,
				'name' => tra('Email'),
				'description' => tra('To send an email once the tracker item has been created. Format: from').'|'.tra('to').'|'.tra('template'),
				'default' => '',
			),
			'emailformat' => array(
				'required' => false,
				'name' => tra('Email format'),
				'description' => tra('Text or html setting'),				
				'default' => 'text',
			),			
			'url' => array(
				'required' => false,
				'name' => tra('URL'),
				'description' => tra('URL the user is sent to after the form is submitted'),
				'filter' => 'url',
				'separator' => ':',
				'default' => '',
			),
			'target' => array(
				'required' => false,
				'name' => tra('URL Target'),
				'description' => tra('Set the target parameter for the url (determines whether target will open in a new page, etc.'),
				'default' => '',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Blank'), 'value' => '_blank'), 
					array('text' => tra('Parent'), 'value' => '_parent'),
					array('text' => tra('Self'), 'value' => '_self'),
					array('text' => tra('Top'), 'value' => '_top')
				)
			),
			'values' => array(
				'required' => false,
				'name' => tra('Values'),
				'description' => tra('Colon-separated list of default values.for the fields. First value corresponds to first field, second value to second field, etc.'),
				'default' => '',
			),
			'overwrite' => array(
				'required' => false,
				'name' => tra('Overwrite'),
				'description' => tra('Overwrite current field values of the item with the input values'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'sort' => array(
				'required' => false,
				'name' => tra('Sort'),
				'description' => tra('Display columns in the order listed in the fields parameter instead of by field ID (field ID order is used by default'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'preview' => array(
				'required' => false,
				'name' => tra('Preview'),
				'description' => tra('Label for the preview button. Default:').' "'. tra('Preview') . '"',
				'default' => 'Preview',
			),
			'reset' => array(
				'required' => false,
				'name' => tra('Reset'),
				'description' => tra('Label for the reset button, to return all fields to their default values.'),
				'default' => tra('reset'),
			),
			'view' => array(
				'required' => false,
				'name' => tra('View'),
				'description' => tra('View'),
				'default' => '',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Group'), 'value' => 'group'), 
					array('text' => tra('Page'), 'value' => 'page'),
					array('text' => tra('User'), 'value' => 'user')
				)
			),
			'status' => array(
				'required' => false,
				'name' => tra('Status'),
				'description' => tra('Status of the item used in combination with:').' view=user',
				'default' => '',
			),
			'itemId' =>array(
				'required' => false,
				'name' => tra('ItemId'),
				'description' => tra('ItemId allowing for editing an item'),
				'filter' => 'digits',
				'default' => '',
			),
			'ignoreRequestItemId' => array(
				'required' => false,
				'name' => tra('Ignore ItemId'),
				'description' => tra('Do not filter on the parameter itemId if in the url'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'tpl' => array(
				'required' => false,
				'name' => tra('Template File'),
				'description' => tra('Name of the template used to display the tracker items.'),
				'default' => '',
			),
			'wiki' => array(
				'required' => false,
				'name' => tra('Wiki'),
				'description' => tra('Name of the wiki page containing the template to display the tracker items.'),
				'filter' => 'pagename',
				'default' => '',
			),
			'newstatus' => array(
				'required' => false,
				'name' => tra('New Status'),
				'description' => tra('Default status applied to newly created items.'),
				'filter' => 'alpha',
				'default' => '',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Open'), 'value' => 'o'), 
					array('text' => tra('Pending'), 'value' => 'p'),
					array('text' => tra('Closed'), 'value' => 'c')
				)
			),
			'colwidth' => array(
				'required' => false,
				'name' => tra('Width'),
				'description' => tra('Specify the width in pixels or percentage of the first column (the labels) in the tracker form.'),
				'default' => '',
				'accepted' => '## or ##%',
			),
			'autosavefields' => array(
				'required' => false,
				'name' => tra('Autosave fields'),
				'description' => tra('Colon-separated list of field IDs to be automatically filled with values'),
				'filter' => 'digits',
				'separator' => ':',
				'default' => '',
			),
			'autosavevalues' => array(
				'required' => false,
				'name' => tra('Autosavevalue'),
				'description' => tra('Colon-separated values corresponding to autosavefields'),
				'filter' => 'text',
				'separator' => ':',
				'default' => '',
			),
			'registration' => array(
				'required' => false,
				'name' => tra('Registration Fields'),
				'description' => tra('Add registration fields such as Username and Password'),
				'filter' => 'alpha',
				'default' => 'n',
				'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'outputtowiki' => array(
				'required' => false,
				'name' => tra('Output To Wiki'),
				'description' => tra('Output result to a new wiki page with the name taken from the input for the specified fieldId'),
				'filter' => 'digits',
				'default' => '',
			),
			'discarditem' => array(
				'required' => false,
				'name' => tra('Discard After Output'),
				'description' => tra('Used when results are output to a wiki page to discard the tracker item itself once the wiki page is created'),
				'filter' => 'alpha',
				'default' => '',
			'options' => array(
					array('text' => '', 'value' => ''), 
					array('text' => tra('Yes'), 'value' => 'y'), 
					array('text' => tra('No'), 'value' => 'n')
				)
			),
			'outputwiki' => array(
				'required' => false,
				'name' => tra('Template Page'),
				'description' => tra('Name of the wiki page containing the template to format the output to wiki page'),
				'filter' => 'pagename',
				'default' => '',
			),
			'formtag' => array(
				'required' => false,
				'name' => tra('Embed the tracker in a form tag'),
				'description' => tra('If set to Yes, the tracker is contained in a <form> tag and has action buttons'),
				'filter' => 'alpha',
				'default' => 'y',
				'options' => array(
					array('text' => '', 'value' => ''),
					array('text' => tra('Yes'), 'value' => 'y'),
					array('text' => tra('No'), 'value' => 'n')
				)
			),
		),
	);
}

function wikiplugin_tracker_name($fieldId, $name, $field_errors)
{
	foreach($field_errors['err_mandatory'] as $f) {
		if ($fieldId == $f['fieldId'])
			return '<span class="highlight">'.$name.'</span>';
	}
	foreach($field_errors['err_value'] as $f) {
		if ($fieldId == $f['fieldId'])
			return '<span class="highlight">'.$name.'</span>';
	}
	return $name;
}

function wikiplugin_tracker($data, $params)
{
	global $tikilib, $userlib, $user, $group, $page, $smarty, $prefs, $trklib, $captchalib;
	$parserlib = TikiLib::lib('parser');

	static $iTRACKER = 0;
	++$iTRACKER;
	if (isset($params['itemId']) && empty($params['itemId']))
		return;
	include_once('lib/trackers/trackerlib.php');
	$default = array('overwrite' => 'n', 'embedded' => 'n', 'showtitle' => 'n', 'showdesc' => 'n', 'sort' => 'n', 'showmandatory'=>'y', 'status' => '', 'registration' => 'n', 'emailformat' => 'text');
	$params = array_merge($default, $params);
	$item = array();
	
	extract ($params, EXTR_SKIP);

	if ($prefs['feature_trackers'] != 'y') {
		return $smarty->fetch("wiki-plugins/error_tracker.tpl");
	}
	if (empty($trackerId) || !($tracker = $trklib->get_tracker($trackerId))) {
		return $smarty->fetch("wiki-plugins/error_tracker.tpl");
	}
	if ($t = $trklib->get_tracker_options($trackerId)) {
		$tracker = array_merge($tracker, $t);
	}
	if (empty($trackerId) && !empty($view) && $view == 'user' && $prefs['userTracker'] == 'y') { // the user tracker item
		$utid = $userlib->get_tracker_usergroup($user);
		if (!empty($utid) && !empty($utid['usersTrackerId'])) {
			$itemId = $trklib->get_item_id($utid['usersTrackerId'], $utid['usersFieldId'], $user);
			$trackerId = $utid['usersTrackerId'];
			$usertracker = true;
		}
	} elseif (!empty($trackerId) && !empty($view) && $view == 'user') {// the user item of a tracker
		$itemId = $trklib->get_user_item($trackerId, $tracker, null, null, strlen($status) == 1 ? $status : '');
		$usertracker = true;
	} elseif (!empty($trackerId) && !empty($view) && $view == 'page' && !empty($_REQUEST['page']) && (($f = $trklib->get_field_id_from_type($trackerId, 'k', '1%')) || ($f = $trklib->get_field_id_from_type($trackerId, 'k', '%,1%')) || ($f =  $trklib->get_field_id_from_type($trackerId, 'k')))) {// the page item
		$itemId = $trklib->get_item_id($trackerId, $f, $_REQUEST['page']);
	} elseif (!empty($trackerId) && !empty($_REQUEST['view_user'])) {
		$itemId = $trklib->get_user_item($trackerId, $tracker, $_REQUEST['view_user']);
	} elseif (!empty($_REQUEST['itemId']) && (empty($ignoreRequestItemId) || $ignoreRequestItemId != 'y')) {
		$itemId = $_REQUEST['itemId'];
		$item = $trklib->get_tracker_item($itemId);
		$trackerId = $item['trackerId'];
	} elseif (!empty($view) && $view == 'group') {
		$gtid = $userlib->get_grouptrackerid($group);
		if(isset($gtid['groupTrackerId'])) {
			$trackerId = $gtid['groupTrackerId'];
			$itemId = $trklib->get_item_id($trackerId, $gtid['groupFieldId'], $group);
			$grouptracker = true;
		}
	}
	if (!isset($trackerId)) {
		return $smarty->fetch("wiki-plugins/error_tracker.tpl");
	}

	if (!isset($action)) {
		$action = array('Save');
	}
	if (!is_array($action)) {
		$action = array( $action );
	}
	if (isset($preview)) {
		if (empty($preview)) {
			$preview = 'Preview';
		}
	} else {
		unset($_REQUEST['tr_preview']);
	}
	if (isset($reset)) {
		if (empty($reset)) {
			$reset = 'reset';
		}
	} else {
		unset($_REQUEST['tr_reset']);
	}
	$smarty->assign('showmandatory',  empty($wiki) && empty($tpl)? 'n': $showmandatory); 
	if (!empty($wiki)) {
		if (preg_match('/^wiki:(.+)$/', $wiki, $wiki_matches)) {
			$wiki = $wiki_matches[1];
		}

		$wiki = trim($wiki);
	}

	if (!isset($params['formtag'])) {
		$params['formtag'] = 'y';
	}

	$fields_prefix = 'ins_';

	if (isset($values)) {
		if (!is_array($values)) {
			$values = $parserlib->quotesplit(':', $values);
			foreach ($values as $i=>$v) {
				$values[$i] = preg_replace('/^"(.*)"$/', '$1', $v);
			}
		}
	}
	if (isset($_REQUEST['values'])) {
		if (is_array($_REQUEST['values'])) {
			foreach ($_REQUEST['values'] as $i=>$k) {
				$_REQUEST['values'][$i] = urldecode($k);
			}
		} else {
			$_REQUEST['values'] = urldecode($_REQUEST['values']);
		}
	}

	$perms = $tikilib->get_perm_object($trackerId, 'tracker', $tracker, false);
	
	if (empty($_SERVER['SCRIPT_NAME']) || strpos($_SERVER['SCRIPT_NAME'], 'tiki-register.php') === false) {
		if (!empty($itemId) && $tracker['writerCanModify'] == 'y' && isset($usertracker) && $usertracker) { // user tracker he can modify
		} elseif (!empty($itemId) && $tracker['writerCanModify'] == 'y' && $user && (($itemUser = $trklib->get_item_creator($trackerId, $itemId)) == $user || ($tracker['userCanTakeOwnership'] == 'y' && empty($itemUser)))) {
		} elseif (!empty($itemId) && isset($grouptracker) && $grouptracker) {
		} else {
			if ($perms['tiki_p_create_tracker_items'] == 'n' && empty($itemId)) {
				return '<b>'.tra("You do not have permission to insert an item").'</b>';
			} elseif (!empty($itemId)) {
				$item_info = $trklib->get_tracker_item($itemId);
				if (!(($perms['tiki_p_modify_tracker_items'] == 'y' and $item_info['status'] != 'p' and $item_info['status'] != 'c') || ($perms['tiki_p_modify_tracker_items_pending'] == 'y' and $item_info['status'] == 'p') ||  ($perms['tiki_p_modify_tracker_items_closed'] == 'y' and $item_info['status'] == 'c'))) { 
					if ($tracker['writerGroupCanModify'] == 'y' && in_array($trklib->get_item_group_creator($trackerId, $itemId), $tikilib->get_user_groups($user))) {
						global $group;
						$smarty->assign_by_ref('ours', $group);
					} else 
						return '<b>'.tra("You do not have permission to modify an item").'</b>';
				}
			}
		}
	}
	if (!empty($itemId)) {
		global $logslib; include_once('lib/logs/logslib.php');
		$logslib->add_action('Viewed', $itemId, 'trackeritem', $_SERVER['REQUEST_URI']);
	}

	if (isset($_REQUEST['removeattach']) && $tracker['useAttachments'] == 'y') {
		$owner = $trklib->get_item_attachment_owner($_REQUEST['removeattach']);
		if ($perms['tiki_p_admin_trackers'] == 'y' || ($user && $user == $owner)) {
			$trklib->remove_item_attachment($_REQUEST["removeattach"]);
			unset($_REQUEST['removeattach']);
		}
	}
	if (isset($_REQUEST['removeImage']) && !empty($_REQUEST['trackerId']) && !empty($_REQUEST['itemId']) && !empty($_REQUEST['fieldId']) && !empty($_REQUEST['fieldName'])) {
		$img_field = array('data' => array());
		$img_field['data'][] = array('fieldId' => $_REQUEST['fieldId'], 'type' => 'i', 'name' => $_REQUEST['fieldName'], 'value' => 'blank');
		$trklib->replace_item($_REQUEST['trackerId'], $_REQUEST['itemId'], $img_field);
	}
	$back = '';
	$js = '';

	$thisIsThePlugin = isset($_REQUEST['iTRACKER']) && $_REQUEST['iTRACKER'] == $iTRACKER;

	if (!isset($_REQUEST["ok"]) || $_REQUEST["ok"]  == "n" || !$thisIsThePlugin || isset($_REQUEST['tr_preview'])) {
		$field_errors = array('err_mandatory'=>array(), 'err_value'=>array());
	
			global $notificationlib; include_once('lib/notifications/notificationlib.php');
			$tracker = $trklib->get_tracker($trackerId);
			$tracker = array_merge($tracker, $trklib->get_tracker_options($trackerId));
			if ((!empty($tracker['start']) && $tikilib->now < $tracker['start']) || (!empty($tracker['end']) && $tikilib->now > $tracker['end']))
				return;
			$outf = array();
			if (!empty($fields)  || !empty($wiki) || !empty($tpl)) {
				if ($registration == 'y' && $prefs["user_register_prettytracker"] == 'y' && !empty($prefs["user_register_prettytracker_tpl"])) {
					$smarty->assign('register_login', $smarty->fetch('register-login.tpl'));
					$smarty->assign('register_email', $smarty->fetch('register-email.tpl'));
					$smarty->assign('register_pass', $smarty->fetch('register-pass.tpl'));
					$smarty->assign('register_pass2', $smarty->fetch('register-pass2.tpl'));
					$smarty->assign('register_passcode', $smarty->fetch('register-passcode.tpl'));
					$smarty->assign('register_groupchoice', $smarty->fetch('register-groupchoice.tpl'));
					$smarty->assign('register_antibot', $smarty->fetch('antibot.tpl'));
					$wiki = $prefs["user_register_prettytracker_tpl"];
				}
				if (!empty($wiki)) {
					$outf = $trklib->get_pretty_fieldIds($wiki, 'wiki', $outputPretty);
				} elseif (!empty($tpl)) {
					$outf = $trklib->get_pretty_fieldIds($tpl, 'tpl', $outputPretty);
				} elseif (!empty($fields)) {
					$outf = preg_split('/ *: */', $fields);
				}
				if (!empty($_REQUEST['autosavefields'])) {
					$autosavefields = explode(':', $_REQUEST['autosavefields']);
					$autosavevalues = explode(':', $_REQUEST['autosavevalues']);
					if (isset($params['autosavefields'])) {
						$autosavefields = array_merge($autosavefields, $params['autosavefields']);
						$autosavevalues = array_merge($autosavevalues, $params['autosavevalues']);
					}
				}
				if (!empty($autosavefields)) {
					$outf = array_merge($outf, $autosavefields);
				}
			}

			$definition = Tracker_Definition::get($trackerId);
			$item_info = isset($item_info) ? $item_info : array();
			$factory = $definition->getFieldFactory();
			if (empty($outf)) {
				$flds = array('data' => $definition->getFields());
			} else {
				$flds = array('data' => array());
				foreach ($outf as $fieldId) {
					$flds['data'][] = $definition->getField($fieldId);
				}
			}
			$bad = array();
			$embeddedId = false;
			$onemandatory = false;
			$full_fields = array();
			$mainfield = '';

			if ($thisIsThePlugin) {
				/* ------------------------------------- Recup all values from REQUEST -------------- */
				foreach ($flds['data'] as $fl) {
					// First convert track_xx to array (need to be up here before setting autosave fields)
					$incomingTrackName = $fields_prefix . $fl["fieldId"];
					if (isset($_REQUEST[$incomingTrackName])) {
						$_REQUEST['track'][$fl["fieldId"]] = $_REQUEST[$incomingTrackName];
					} else if (isset($_FILES[$incomingTrackName])) {	// also for uploaded files
						foreach ($_FILES[$incomingTrackName] as $lbl => $val) {
							$_FILES['track'][$lbl][$fl["fieldId"]] = $val;
						}
					}
				}
				if (!empty($autosavefields)) {
					foreach ($autosavefields as $i=>$f) {
						if (!$ff = $trklib->get_field($f, $flds['data'])) {
							continue;
						}
						if (!$trklib->fieldId_is_editable($ff, $item_info)) {
							continue;
						}
						if (preg_match('/categories\(([0-9]+)\)/', $autosavevalues[$i], $matches)) {
							if (ctype_digit($matches[1]) && $matches[1] > 0) {
								$filter = array('identifier'=>$matches[1], 'type'=>'descendants'); 
							} else {
								$filter = NULL;
							}
							global $categlib; include_once('lib/categories/categlib.php');
							$categs = $categlib->getCategories($filter, true, false);
							$_REQUEST["ins_$f"][] = $categs[0]['categId'];
						} elseif (preg_match('/preference\((.*)\)/', $autosavevalues[$i], $matches)) {
							$_REQUEST["$ins_id_$f"] = $prefs[$matches[1]];
						} elseif ($ff['type'] == 'e') {
							$_REQUEST["ins_$f"][] = $autosavevalues[$i];
						} else {
							$_REQUEST["ins_$f"] = $autosavevalues[$i];
						}
					}
				}
				foreach ($flds['data'] as $k => $field) {
					$handler = $factory->getHandler($field, $item_info);

					if ($handler) {
						$ins_fields['data'][$k] = array_merge($field, $handler->getFieldData($_REQUEST));
					}
				}
				$cpt = 0;
				if (isset($fields)) {
{'fraction_non_alphanumeric': 0.23260695949800342, 'fraction_numerical': 0.00127780946948089, 'mean_word_length': 3.7543935777825994, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 785, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2751422', 'n_tokens_mistral': 17925, 'n_tokens_neox': 15175, 'n_words': 3217}