Example #1
0
function wikiplugin_tracker($data, $params)
{
    global $user, $group, $page, $prefs;
    $parserlib = TikiLib::lib('parser');
    $trklib = TikiLib::lib('trk');
    $userlib = TikiLib::lib('user');
    $tikilib = TikiLib::lib('tiki');
    $smarty = TikiLib::lib('smarty');
    $captchalib = TikiLib::lib('captcha');
    static $iTRACKER = 0;
    ++$iTRACKER;
    if (isset($params['itemId']) && empty($params['itemId'])) {
        return;
    }
    $smarty->assign('trackerEditFormId', $iTRACKER);
    $default = array('overwrite' => 'n', 'embedded' => 'n', 'showtitle' => 'n', 'showdesc' => 'n', 'showfieldsdesc' => 'y', 'sort' => 'n', 'showmandatory' => 'y', 'status' => '', 'transactionFinalStep' => 'y', 'registration' => 'n', 'chosenGroup' => 'Registered', 'validateusers' => '', 'emailformat' => 'text');
    $params = array_merge($default, $params);
    $item = array();
    extract($params, EXTR_SKIP);
    if (empty($transactionName) xor empty($transactionStep)) {
        return '<b>' . tra("You need to define both transaction name and transaction step, or none of the two.") . '</b>';
    } else {
        if (isset($transactionName) && !isset($_SESSION[$transactionName])) {
            $_SESSION[$transactionName] = array();
        }
        if (isset($transactionStep) && !isset($_SESSION[$transactionName][$transactionStep])) {
            $_SESSION[$transactionName][$transactionStep] = array();
        }
        if (!isset($_SESSION[$transactionName]['transactionStep'])) {
            $_SESSION[$transactionName]['transactionStep'] = 0;
        }
        if ($_SESSION[$transactionName]['transactionStep'] != $transactionStep) {
            return;
        }
    }
    if ($prefs['feature_trackers'] != 'y') {
        return $smarty->fetch("wiki-plugins/error_tracker.tpl");
    }
    if (empty($trackerId) || !($definition = Tracker_Definition::get($trackerId))) {
        return $smarty->fetch("wiki-plugins/error_tracker.tpl");
    }
    $tracker = $definition->getInformation();
    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_page_field($trackerId))) {
        // the page item
        $itemId = $trklib->get_item_id($trackerId, $f['fieldId'], $_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");
    }
    //test for validation errors for registration tracker calls
    if (isset($_REQUEST['register']) && ($_REQUEST['register'] == 'Register' || $_REQUEST['register'] == 'register')) {
        $regtracker = $userlib->get_usertrackerid('Registered');
        if ($trackerId == $regtracker['usersTrackerId'] && $_REQUEST['valerror'] !== false) {
            if (is_array($_REQUEST['valerror'])) {
                foreach ($_REQUEST['valerror'] as $valerror) {
                    if (is_a($valerror, 'RegistrationError')) {
                        return false;
                        break;
                    }
                }
            } elseif (is_a($_REQUEST['valerror'], 'RegistrationError')) {
                return false;
            }
        }
    }
    if (!isset($action)) {
        $action = array('Save');
    }
    if (!is_array($action)) {
        $action = array($action);
    }
    $dynamicSave = false;
    if (count($action) == 1 && reset($action) == 'NONE') {
        $action = array();
        $dynamicSave = true;
    }
    if (!isset($action_style)) {
        $action_style = array();
        foreach ($action as $ac) {
            $action_style[] = 'btn btn-primary';
        }
    }
    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 ($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 (empty($item_info)) {
                return '<b>' . tra("Incorrect item") . '</b>';
            }
            $itemObject = Tracker_Item::fromInfo($item_info);
            if (!$itemObject->canModify()) {
                return '<b>' . tra("You do not have permission to modify an item") . '</b>';
            }
        }
    }
    if (!empty($itemId)) {
        $logslib = TikiLib::lib('logs');
        $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 = '';
    $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());
        $notificationlib = TikiLib::lib('notification');
        $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();
        $auto_fieldId = array();
        $hidden_fieldId = array();
        if (!empty($fields) || !empty($wiki) || !empty($tpl)) {
            if ($registration == 'y' && $prefs["user_register_prettytracker"] == 'y' && !empty($prefs["user_register_prettytracker_tpl"])) {
                $registrationlib = TikiLib::lib('registration');
                $smarty->assign('listgroups', $registrationlib->merged_prefs['choosable_groups']);
                $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'));
                if ($prefs['feature_antibot'] == 'y') {
                    $smarty->assign('showantibot', true);
                    $smarty->assign('form', 'register');
                    $smarty->assign('register_antibot', $smarty->fetch('antibot.tpl'));
                }
                $wiki = $prefs["user_register_prettytracker_tpl"];
            }
            if (!empty($wiki)) {
                $outf = $trklib->get_pretty_fieldIds($wiki, 'wiki', $prettyModifier, $trackerId);
            } elseif (!empty($tpl)) {
                $outf = $trklib->get_pretty_fieldIds($tpl, 'tpl', $prettyModifier, $trackerId);
            } elseif (!empty($fields)) {
                $outf = $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)) {
                $auto_fieldId = array_merge($auto_fieldId, $autosavefields);
            }
            foreach ($definition->getFields() as $field) {
                // User and group on autoassign create/modify
                if (($user || $registration == 'y' || isset($_SESSION[$transactionName]) && isset($_SESSION[$transactionName]['registrationName'])) && ($field['type'] == 'u' || $field['type'] == 'g')) {
                    $autoassign = $field['options_map']['autoassign'];
                    if ($autoassign == 1 || $autoassign == 2) {
                        if ($user) {
                            $hidden_fieldId[] = $field['fieldId'];
                        }
                        $userField = $field['fieldId'];
                    }
                }
                // IP and page on autoassign
                if ($field['type'] == 'I' || $field['type'] == 'k') {
                    $autoassign = $field['options_map']['autoassign'];
                    if ($autoassign == 1) {
                        $hidden_fieldId[] = $field['fieldId'];
                    }
                }
                // Auto-increment
                if ($field['type'] == 'q') {
                    $auto_fieldId[] = $field['fieldId'];
                }
            }
            foreach ($auto_fieldId as $k => $v) {
                if (empty($v) || in_array($v, $outf)) {
                    unset($auto_fieldId[$k]);
                } else {
                    $outf[] = $v;
                }
            }
            foreach ($hidden_fieldId as $k => $v) {
                if (empty($v) || in_array($v, $outf)) {
                    unset($hidden_fieldId[$k]);
                } else {
                    $outf[] = $v;
                }
            }
        }
        $definition = Tracker_Definition::get($trackerId);
        $item_info = isset($item_info) ? $item_info : array();
        $factory = $definition->getFieldFactory();
        if (empty($item_info)) {
            $itemObject = Tracker_Item::newItem($trackerId);
        } elseif (!isset($itemObject)) {
            $itemObject = Tracker_Item::fromInfo($item_info);
        }
        if (empty($outf)) {
            $unfiltered = array('data' => $definition->getFields());
        } else {
            $unfiltered = array('data' => array());
            foreach ($outf as $fieldId) {
                $unfiltered['data'][] = $definition->getField($fieldId);
            }
        }
        $flds = array('data' => array());
        foreach ($unfiltered['data'] as $f) {
            if ($itemObject->canModifyField($f['fieldId']) || $registration == 'y' && empty($item_info)) {
                $flds['data'][] = $f;
            }
        }
        // If we create multiple items, get field Ids, default values and separator
        if (!empty($fieldsfill)) {
            $fill_fields = $fieldsfill;
            // Allow for superfluous spaces and ignore them
            $fill_flds = array('data' => array());
            $fill_defaults = array();
            $fill_flds_defaults = array();
            // May be different from fill_defaults if some fields are not editable
            $fieldsfillnames = array();
            if (trim($fieldsfilldefaults) != '') {
                $fill_defaults = preg_split('/ *: */', $fieldsfilldefaults);
            }
            foreach ($fill_fields as $k => $fieldId) {
                if ($itemObject->canModifyField($fieldId)) {
                    $tmp = $definition->getField($fieldId);
                    $fill_flds['data'][] = $tmp;
                    if (isset($fill_defaults[$k])) {
                        $fill_flds_defaults[] = $fill_defaults[$k];
                    } else {
                        $fill_flds_defaults[] = '';
                    }
                    $fieldsfillnames[] = $tmp['name'];
                }
            }
            $fill_line_cant = count($fill_flds['data']);
            if ($fieldsfillseparator == '') {
                $fieldsfillseparator = '|';
            }
        }
        $bad = array();
        $embeddedId = false;
        $onemandatory = false;
        $full_fields = array();
        $mainfield = '';
        if ($thisIsThePlugin) {
            /* ------------------------------------- Recup all values from REQUEST -------------- */
            if (!empty($autosavefields)) {
                foreach ($autosavefields as $i => $f) {
                    if (!($ff = $trklib->get_field($f, $flds['data']))) {
                        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;
                        }
                        $categlib = TikiLib::lib('categ');
                        $categs = $categlib->getCategories($filter, true, false);
                        $_REQUEST["{$fields_prefix}{$f}"][] = $categs[0]['categId'];
                    } elseif (preg_match('/preference\\((.*)\\)/', $autosavevalues[$i], $matches)) {
                        $_REQUEST["{$fields_prefix}{$f}"] = $prefs[$matches[1]];
                    } elseif (isset($transactionName) && preg_match('/#TSTEP\\[(\\d+)\\]\\[(\\d+|name|pass)\\]/', $autosavevalues[$i], $matches)) {
                        $traStep = $matches[1];
                        $traStepInsField = $matches[2];
                        if (preg_match('/\\d+/', $matches[2])) {
                            $traStepInsField = "{$fields_prefix}{$traStepInsField}";
                        }
                        $_REQUEST["{$fields_prefix}{$f}"] = str_replace($matches[0], $_SESSION[$transactionName][$traStep]['request'][$traStepInsField], $autosavevalues[$i]);
                    } elseif ($ff['type'] == 'e') {
                        $_REQUEST["{$fields_prefix}{$f}"][] = $autosavevalues[$i];
                    } else {
                        if (isset($params['levelupfields']) && in_array($f, $params['levelupfields'])) {
                            $current_levelup_val = $trklib->get_item_value($trackerId, $itemId, $f);
                            if ($autosavevalues[$i] <= $current_levelup_val) {
                                continue;
                            }
                        }
                        $_REQUEST["{$fields_prefix}{$f}"] = $autosavevalues[$i];
                    }
                }
            }
            if ($registration == 'y' && isset($userField) && isset($_REQUEST['name'])) {
                $_REQUEST["{$fields_prefix}{$userField}"] = $_REQUEST['name'];
            }
            foreach ($flds['data'] as $k => $field) {
                $handler = $factory->getHandler($field, $item_info);
                if ($handler) {
                    $value_field = $handler->getFieldData($_REQUEST);
                    $ins_fields['data'][$k] = array_merge($field, $value_field);
                    if (isset($ins_fields['data'][$k]['value'])) {
                        // add ins value into field if creating or editing item
                        $flds['data'][$k] = $ins_fields['data'][$k];
                        // to keep user input in case of errors (not only value)
                    }
                }
            }
            $cpt = 0;
            if (isset($fields)) {
                $fields_plugin = $fields;
            }
            if (!isset($itemId) && $tracker['oneUserItem'] == 'y' && $registration != 'y') {
                $itemId = $trklib->get_user_item($trackerId, $tracker);
            }
            if ($embedded == 'y' && isset($_REQUEST['page'])) {
                $ins_fields["data"][] = array('fieldId' => $embeddedId, 'value' => $_REQUEST['page']);
            }
            if (isset($userField) && ($registration == 'y' && isset($_REQUEST['name']) || isset($_SESSION[$transactionName]) && isset($_SESSION[$transactionName]['registrationName']))) {
                $userFieldDef = $definition->getField($userField);
                if (isset($_REQUEST['name'])) {
                    $userFieldDef['value'] = $_REQUEST['name'];
                    if (isset($_SESSION[$transactionName])) {
                        $_SESSION[$transactionName]['registrationName'] = $_REQUEST['name'];
                    }
                } elseif (isset($_SESSION[$transactionName]) && isset($_SESSION[$transactionName]['registrationName'])) {
                    $userFieldDef['value'] = $_SESSION[$transactionName]['registrationName'];
                }
                $ins_fields['data'][] = $userFieldDef;
            }
            $ins_categs = 0;
            // important: non-array ins_categs means categories should remain unchanged
            $parent_categs_only = array();
            foreach ($ins_fields['data'] as $current_field) {
                if ($current_field['type'] == 'e' && isset($current_field['selected_categories'])) {
                    if (!is_array($ins_categs)) {
                        $ins_categs = array();
                    }
                    $ins_categs = array_merge($ins_categs, $current_field['selected_categories']);
                    $parent_categs_only[] = $current_field['options_array'][0];
                }
            }
            $categorized_fields = $definition->getCategorizedFields();
            /* ------------------------------------- End recup all values from REQUEST -------------- */
            /* ------------------------------------- Check field values for each type and presence of mandatory ones ------------------- */
            $field_errors = $trklib->check_field_values($ins_fields, $categorized_fields, $trackerId, empty($itemId) ? '' : $itemId);
            if ($prefs['feature_antibot'] === 'y' && $registration === 'y' && isset($_REQUEST['valerror'])) {
                // in_tracker session var checking is for tiki-register.php
                if (isset($_REQUEST['valerror'])) {
                    $rve = $_REQUEST['valerror'];
                    if (is_array($rve)) {
                        foreach ($rve as $ve) {
                            if (is_a($ve, 'RegistrationError')) {
                                if (isset($ve->field) && $ve->field == 'antibotcode') {
                                    $field_errors['err_antibot'] = 'y';
                                    continue;
                                }
                            }
                        }
                    } elseif (is_a($rve, 'RegistrationError')) {
                        if (isset($rve->field) && $rve->field == 'antibotcode') {
                            $field_errors['err_antibot'] = 'y';
                        }
                    }
                } else {
                    if (!$captchalib->validate()) {
                        $field_errors['err_antibot'] = 'y';
                    }
                }
            }
            // check valid page name for wiki output if requested
            if (isset($outputtowiki) && !empty($outputwiki)) {
                $newpagename = '';
                foreach ($ins_fields["data"] as $fl) {
                    if ($fl["fieldId"] == $outputtowiki) {
                        $newpagename = $fl["value"];
                    }
                    if ($fl["type"] == 'F') {
                        $newpagefreetags = $fl["value"];
                    }
                    $newpagefields[] = $fl["fieldId"];
                }
                if ($newpagename) {
                    if ($prefs['namespace_enabled'] == 'y' && !empty($outputwikinamespace)) {
                        $newpagename = $outputwikinamespace . $prefs['namespace_separator'] . $newpagename;
                    }
                    if ($tikilib->page_exists($newpagename)) {
                        $field_errors['err_outputwiki'] = tra('The page to output the results to already exists. Try another name.');
                    }
                    $page_badchars_display = TikiLib::lib('wiki')->get_badchars();
                    if (TikiLib::lib('wiki')->contains_badchars($newName)) {
                        $field_errors['err_outputwiki'] = tr("The page to output the results to contains the following prohibited characters: %0. Try another name.", $page_badchars_display);
                    }
                } else {
                    unset($outputtowiki);
                }
            }
            if (count($field_errors['err_mandatory']) == 0 && count($field_errors['err_value']) == 0 && empty($field_errors['err_antibot']) && empty($field_errors['err_outputwiki']) && !isset($_REQUEST['tr_preview'])) {
                if (isset($_REQUEST['status'])) {
                    $status = $_REQUEST['status'];
                } elseif (isset($newstatus) && ($newstatus == 'o' || $newstatus == 'c' || $newstatus == 'p')) {
                    $status = $newstatus;
                } elseif (empty($itemId) && isset($tracker['newItemStatus'])) {
                    $status = $tracker['newItemStatus'];
                } else {
                    $status = '';
                }
                $saveThis = array('trackerId' => $trackerId, 'request' => $_REQUEST, 'chosenGroup' => $chosenGroup, 'registration' => $registration, 'registrationTrackerId' => $registrationTrackerId, 'validateusers' => $validateusers, 'status' => $status, 'ins_fields' => $ins_fields, 'itemId' => $itemId, 'ins_categs' => $ins_categs, 'newItemRate' => $newItemRate);
                //-- check if we are in a transaction
                if (isset($transactionName)) {
                    $_SESSION[$transactionName][$transactionStep] = $saveThis;
                    if ($transactionFinalStep == 'y') {
                        //-- final step: commit the transaction of registrations and tracker changes of all the transaction steps
                        foreach ($_SESSION[$transactionName] as $saveStep) {
                            $rid = wikiplugin_tracker_save($saveStep);
                        }
                        unset($_SESSION[$transactionName]);
                        // the tracker transaction can be closed
                    } else {
                        $_SESSION[$transactionName]['transactionStep'] += 1;
                        // switch to the next step
                    }
                } else {
                    // no transaction is used
                    $rid = wikiplugin_tracker_save($saveThis);
                }
                // now for wiki output if desired
                if (isset($outputtowiki) && !empty($outputwiki)) {
                    // note that values will be raw - that is the limit of the capability of this feature for now
                    $newpageinfo = $tikilib->get_page_info($outputwiki);
                    $wikioutput = $newpageinfo["data"];
                    $newpagefields = $trklib->get_pretty_fieldIds($outputwiki, 'wiki', $prettyModifier, $trackerId);
                    $tracker_definition = Tracker_Definition::get($trackerId);
                    foreach ($newpagefields as $lf) {
                        $field = $tracker_definition->getField($lf);
                        $lfpermname = $field['permName'];
                        $wikioutput = str_replace('{$f_' . $lf . '}', $trklib->get_item_value($trackerId, $rid, $lf), $wikioutput);
                        $wikioutput = str_replace('{$f_' . $lfpermname . '}', $trklib->get_item_value($trackerId, $rid, $lf), $wikioutput);
                    }
                    if (isset($registration)) {
                        $wikioutput = str_replace('{$register_login}', $user, $wikioutput);
                        $wikioutput = str_replace('{$register_email}', $_REQUEST['email'], $wikioutput);
                    }
                    $tikilib->create_page($newpagename, 0, $wikioutput, $tikilib->now, '', $user, $tikilib->get_ip_address());
                    $cat_desc = '';
                    $cat_type = 'wiki page';
                    $cat_name = $newpagename;
                    $cat_objid = $newpagename;
                    $cat_href = "tiki-index.php?page=" . urlencode($newpagename);
                    if (count($ins_categs)) {
                        $_REQUEST['cat_categories'] = $ins_categs;
                        $_REQUEST['cat_categorize'] = 'on';
                        include_once "categorize.php";
                    }
                    if (isset($newpagefreetags) && $newpagefreetags) {
                        $_REQUEST['freetag_string'] = $newpagefreetags;
                        include_once "freetag_apply.php";
                    }
                    if ($discarditem == 'y') {
                        $trklib->remove_tracker_item($rid);
                    } elseif ($outputwikirelation == 'y') {
                        TikiLib::lib('relation')->add_relation('tiki.wiki.linkeditem', 'wiki page', $newpagename, 'trackeritem', $rid);
                        TikiLib::lib('relation')->add_relation('tiki.wiki.linkedfield', 'wiki page', $newpagename, 'trackerfield', $outputtowiki);
                    }
                    if (empty($url)) {
                        $wikilib = TikiLib::lib('wiki');
                        $url[0] = $wikilib->sefurl($newpagename);
                    }
                }
                // end wiki output
                // send emails if email param is set and tracker_always_notify or something was changed (mail_data is set in \TrackerLib::send_replace_item_notifications)
                if (!empty($email) && ($prefs['tracker_always_notify'] === 'y' || !empty($smarty->getTemplateVars('mail_data')))) {
                    // expose the pretty tracker fields to the email tpls
                    foreach ($flds['data'] as $f) {
                        $prettyout = strip_tags(wikiplugin_tracker_render_value($f, $item));
                        $smarty->assign('f_' . $f['fieldId'], $prettyout);
                        $smarty->assign('f_' . $f['permName'], $prettyout);
                    }
                    $emailOptions = preg_split("#\\|#", $email);
                    if (is_numeric($emailOptions[0])) {
                        $emailOptions[0] = $trklib->get_item_value($trackerId, $rid, $emailOptions[0]);
                    }
                    if (empty($emailOptions[0])) {
                        // from
                        $emailOptions[0] = $prefs['sender_email'];
                    }
                    if (empty($emailOptions[1])) {
                        // to
                        $emailOptions[1][0] = $prefs['sender_email'];
                    } else {
                        $emailOptions[1] = preg_split('/ *, */', $emailOptions[1]);
                        foreach ($emailOptions[1] as $key => $email) {
                            if (is_numeric($email)) {
                                $emailOptions[1][$key] = $trklib->get_item_value($trackerId, $rid, $email);
                            }
                        }
                    }
                    include_once 'lib/webmail/tikimaillib.php';
                    $mail = new TikiMail();
                    $mail->setFrom($emailOptions[0]);
                    if (!empty($emailOptions[2])) {
                        //tpl
                        $emailOptions[2] = preg_split('/ *, */', $emailOptions[2]);
                        foreach ($emailOptions[2] as $ieo => $eo) {
                            if (!preg_match('/\\.tpl$/', $eo)) {
                                $emailOptions[2][$ieo] = $eo . '.tpl';
                            }
                            $tplSubject[$ieo] = str_replace('.tpl', '_subject.tpl', $emailOptions[2][$ieo]);
                        }
                    } else {
                        $emailOptions[2] = array('tracker_changed_notification.tpl');
                    }
                    if (empty($tplSubject)) {
                        $tplSubject = array('tracker_changed_notification_subject.tpl');
                    }
                    $itpl = 0;
                    $smarty->assign('mail_date', $tikilib->now);
                    $smarty->assign('mail_itemId', $rid);
                    foreach ($emailOptions[1] as $ieo => $ueo) {
                        @($mail_data = $smarty->fetch('mail/' . $tplSubject[$itpl]));
                        if (empty($mail_data)) {
                            $mail_data = tra('Tracker was modified at ') . $_SERVER["SERVER_NAME"];
                        }
                        $mail->setSubject($mail_data);
                        $mail_data = $smarty->fetch('mail/' . $emailOptions[2][$itpl]);
                        if ($emailformat == 'html') {
                            $mail->setHtml($mail_data);
                        } else {
                            $mail->setText($mail_data);
                        }
                        try {
                            $mail->send($ueo);
                            $title = 'mail';
                        } catch (Zend_Mail_Exception $e) {
                            $title = 'mail error';
                        }
                        if ($title == 'mail error') {
                            // Log the email error at the tiki syslog
                            $logslib = TikiLib::lib('logs');
                            $logslib->add_log('mail error', 'plugin tracker email error / ' . $emailOptions[1][$ieo] . ' / item' . $rid);
                        } elseif ($title == 'mail' && $prefs['log_mail'] == 'y') {
                            // Log the email at the tiki syslog
                            $logslib = TikiLib::lib('logs');
                            $logslib->add_log('mail', 'plugin tracker email sent / ' . $emailOptions[1][$ieo] . ' / item' . $rid);
                        }
                        if (isset($tplSubject[$itpl + 1])) {
                            ++$itpl;
                        }
                    }
                }
                if (empty($url)) {
                    if (!empty($_REQUEST['ajax_add'])) {
                        // called by tracker ItemLink fields when adding new list items
                        while (ob_get_level()) {
                            ob_end_clean();
                        }
                        if ($prefs['feature_obzip'] == 'y') {
                            ob_start('ob_gzhandler');
                        } else {
                            ob_start();
                        }
                        // Need to add newly created itemId for item link selector
                        $ins_fields['itemId'] = $rid;
                        $access = TikiLib::lib('access');
                        $access->output_serialized($ins_fields);
                        ob_end_flush();
                        die;
                    } else {
                        if (!empty($page)) {
                            $url = "tiki-index.php?page=" . urlencode($page);
                            if (!empty($itemId)) {
                                $url .= "&itemId=" . $itemId;
                            }
                            $url .= "&ok=y&iTRACKER={$iTRACKER}";
                            $url .= "#wikiplugin_tracker{$iTRACKER}";
                            TikiLib::lib('access')->redirect($url);
                            exit;
                        } else {
                            return '';
                        }
                    }
                } else {
                    $key = 0;
                    foreach ($action as $key => $act) {
                        if (!empty($_REQUEST["action{$key}"])) {
                            break;
                        }
                    }
                    $itemIdPos = strpos($url[$key], 'itemId');
                    if ($itemIdPos !== false) {
                        if (strstr($url[$key], '#itemId')) {
                            $url[$key] = str_replace('#itemId', $rid, $url[$key]);
                        } else {
                            if ($itemIdPos + strlen('itemId') >= strlen($url[$key]) - 1 || substr($url[$key], $itemIdPos + strlen('itemId'), 1) == "&") {
                                // replace by the itemId if in the end (or -1: for backward compatibility so that "&itemId=" also works) or if it is followed by an '&'
                                $url[$key] = str_replace('itemId', 'itemId=' . $rid, $url[$key]);
                            }
                        }
                    }
                    TikiLib::lib('access')->redirect($url[$key]);
                    exit;
                }
            } elseif (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
                $smarty->assign('wikiplugin_tracker', $trackerId);
                //used in vote plugin
            }
        } else {
            if ((empty($itemId) || $overwrite == 'y') && !empty($values) || (!empty($_REQUEST['values']) and empty($_REQUEST['prefills']))) {
                // assign default values for each filedId specify
                if (empty($values)) {
                    // url with values[]=x&values[] witouth the list of fields
                    $values = $_REQUEST['values'];
                }
                if (!is_array($values)) {
                    $values = array($values);
                }
                if (isset($fields)) {
                    $fl = $fields;
                    for ($j = 0, $count_fl = count($fl); $j < $count_fl; $j++) {
                        for ($i = 0, $count_flds = count($flds['data']); $i < $count_flds; $i++) {
                            if ($flds['data'][$i]['fieldId'] == $fl[$j]) {
                                $flds['data'][$i]['value'] = $values[$j];
                            }
                        }
                    }
                } else {
                    // values contains all the fields value in the default order
                    $i = 0;
                    foreach ($values as $value) {
                        $flds['data'][$i++]['value'] = $value;
                    }
                }
            } elseif (!empty($itemId)) {
                if (isset($fields)) {
                    $fl = $fields;
                    $filter = '';
                    foreach ($flds['data'] as $f) {
                        if (in_array($f['fieldId'], $fl)) {
                            $filter[] = $f;
                        }
                    }
                } else {
                    $filter =& $flds['data'];
                }
                if (!empty($filter)) {
                    foreach ($filter as $f) {
                        $filter2[$f['fieldId']] = $f;
                    }
                    $flds['data'] = $trklib->get_item_fields($trackerId, $itemId, $filter2, $itemUser, true);
                }
                // todo: apply the values for fields with no values
            } else {
                if (isset($_REQUEST['values']) && isset($_REQUEST['prefills'])) {
                    //url:prefills=1:2&values[]=x&values[]=y
                    if (!is_array($_REQUEST['values'])) {
                        $_REQUEST['values'] = array($_REQUEST['values']);
                    }
                    $fl = preg_split('/:/', $_REQUEST['prefills']);
                } else {
                    unset($fl);
                }
                for ($i = 0, $count_flds2 = count($flds['data']); $i < $count_flds2; $i++) {
                    if (isset($fl) && ($j = array_search($flds['data'][$i]['fieldId'], $fl)) !== false) {
                        $flds['data'][$i]['value'] = $_REQUEST['values'][$j];
                    } else {
                        // setting default value prevent dropdown default value working
                        $options = $flds['data'][$i]['options_array'];
                        if (!in_array($flds['data'][$i]['type'], array('d', 'D', 'R', 'M')) || count($options) === count(array_unique($options))) {
                            $flds['data'][$i]['value'] = '';
                            // initialize fields with blank values
                        }
                    }
                }
            }
        }
        // Check that individual fields are in the tracker
        if (!empty($fields)) {
            $fl = $fields;
            if ($sort == 'y') {
                $flds = $trklib->sort_fields($flds, $fl);
            }
            foreach ($fl as $l) {
                $ok = false;
                foreach ($flds['data'] as $f) {
                    if ($f['fieldId'] == $l) {
                        $ok = true;
                        break;
                    }
                }
                if (!$ok) {
                    $back .= '<div class="alert alert-warning"><strong>' . tra('Incorrect fieldId:') . ' ' . $l . '</strong>.<br> ' . tra("Please ensure you are using the correct field ID and that it is properly included in the template, if any.") . '</div>';
                }
            }
        } elseif (empty($fields) && empty($wiki) && empty($tpl)) {
            // in this case outf still be blank and needs to be filled
            foreach ($flds['data'] as $f) {
                $outf[] = $f['fieldId'];
            }
        }
        // Check that multiple fill fields are in the tracker
        if (!empty($fieldsfill)) {
            foreach ($fill_fields as $l) {
                $ok = false;
                foreach ($fill_flds['data'] as $f) {
                    if ($f['fieldId'] == $l) {
                        $ok = true;
                        break;
                    }
                }
                if (!$ok) {
                    $back .= '<div class="alert alert-warning">' . tra('Incorrect fieldId:') . ' ' . $l . '</div>';
                }
            }
        }
        // Display warnings when needed
        if (count($field_errors['err_mandatory']) > 0 || count($field_errors['err_value']) > 0) {
            $back .= $smarty->fetch('tracker_error.tpl');
            $_REQUEST['error'] = 'y';
            if (count($field_errors['err_mandatory']) > 0) {
                $msg = tra('Following mandatory fields are missing');
                foreach ($field_errors['err_mandatory'] as $err) {
                    $msg .= '<br>&nbsp;&nbsp;&nbsp;&nbsp;' . $err['name'];
                }
                TikiLib::lib('errorreport')->report($msg);
            }
            if (count($field_errors['err_value']) > 0) {
                $msg = tra('Following fields are incorrect');
                foreach ($field_errors['err_value'] as $err) {
                    $msg .= '<br>&nbsp;&nbsp;&nbsp;&nbsp;' . $err['name'];
                }
                TikiLib::lib('errorreport')->report($msg);
            }
            if ($registration && !empty($userField) && isset($_REQUEST['name']) && $_REQUEST['name'] === $userField['value'] && $_REQUEST['name'] === $user) {
                // if in registration and creating a user tracker item for the new user
                // remove the user if they did not complete the tracker correctly
                $userlib->remove_user($userField['value']);
                if ($prefs['eponymousGroups'] == 'y') {
                    // eponymous group will contain only this (former) user so remove that too
                    $userlib->remove_group($userField['value']);
                }
                $user = '';
                // needed to re-include the captcha inputs
                $hidden_fieldId = array();
                // remove hidden user fields which are otherwise required
                foreach ($flds['data'] as $k => $v) {
                    // remove the login field otherwise it gets rendered in the form also required
                    if ($v['fieldId'] == $userField['fieldId']) {
                        unset($flds['data'][$k]);
                    }
                }
            }
            if (isset($field_errors['err_antibot'])) {
                $_REQUEST['error'] = 'y';
            }
            if (isset($field_errors['err_outputwiki'])) {
                $smarty->loadPlugin('smarty_function_icon');
                $icon = smarty_function_icon(['name' => 'warning'], $smarty);
                $back .= '<div class="alert alert-warning">' . $icon . ' ';
                $back .= $field_errors['err_outputwiki'];
                $back .= '</div><br />';
                $_REQUEST['error'] = 'y';
            }
            if (count($field_errors['err_mandatory']) > 0 || count($field_errors['err_value']) > 0 || isset($field_errors['err_antibot']) || isset($field_errors['err_outputwiki'])) {
                $smarty->assign('input_err', 'y');
            }
        }
        if (!empty($page)) {
            $back .= '~np~';
            $smarty->assign_by_ref('tiki_p_admin_trackers', $perms['tiki_p_admin_trackers']);
        }
        if (!empty($params['_ajax_form_ins_id'])) {
            $headerlib = TikiLib::lib('header');
            $old_js['js'] = $headerlib->js;
            // of tracker form JS into a function to initialise it when the dialog is created
            $old_js['jq_onready'] = $headerlib->jq_onready;
            $headerlib->clear_js();
            // so store existing js for later and clear
        }
        if ($prefs['feature_jquery'] == 'y' && $prefs['feature_jquery_validation'] == 'y') {
            $validatorslib = TikiLib::lib('validators');
            $customvalidation = '';
            $customvalidation_m = '';
            if ($registration == 'y') {
                // email validation
                $customvalidation .= 'email: { ';
                $customvalidation .= 'required: true, ';
                $customvalidation .= 'email: true }, ';
                $customvalidation_m .= 'email: { email: "' . tra("Invalid email") . '", required: "' . tra("This field is required") . '"}, ';
                // password validation
                $customvalidation .= 'pass: { ';
                $customvalidation .= 'required: true, ';
                $customvalidation .= 'remote: { ';
                $customvalidation .= 'url: "validate-ajax.php", ';
                $customvalidation .= 'type: "post", ';
                $customvalidation .= 'data: { ';
                $customvalidation .= 'validator: "password", ';
                $customvalidation .= 'input: function() { ';
                $customvalidation .= 'return $("#pass1").val(); ';
                $customvalidation .= '} } } ';
                $customvalidation .= '}, ';
                $customvalidation_m .= 'pass: { required: "' . tra("This field is required") . '"}, ';
                // password repeat validation
                $customvalidation .= 'passAgain: { equalTo: "#pass1" }, ';
                $customvalidation_m .= 'passAgain: { equalTo: "' . tra("Passwords do not match") . '"}, ';
                // username validation
                $customvalidation .= 'name: { ';
                $customvalidation .= 'required: true, ';
                $customvalidation .= 'remote: { ';
                $customvalidation .= 'url: "validate-ajax.php", ';
                $customvalidation .= 'type: "post", ';
                $customvalidation .= 'data: { ';
                $customvalidation .= 'validator: "username", ';
                $customvalidation .= 'input: function() { ';
                $customvalidation .= 'return $("#name").val(); ';
                $customvalidation .= '} } } ';
                $customvalidation .= '}, ';
                $customvalidation_m .= 'name: { required: "' . tra("This field is required") . '"}, ';
                if (extension_loaded('gd') && function_exists('imagepng') && function_exists('imageftbbox') && $prefs['feature_antibot'] == 'y' && empty($user) && $prefs['recaptcha_enabled'] != 'y') {
                    // antibot validation
                    $customvalidation .= '"captcha[input]": { ';
                    $customvalidation .= 'required: true, ';
                    $customvalidation .= 'remote: { ';
                    $customvalidation .= 'url: "validate-ajax.php", ';
                    $customvalidation .= 'type: "post", ';
                    $customvalidation .= 'data: { ';
                    $customvalidation .= 'validator: "captcha", ';
                    $customvalidation .= 'parameter: function() { ';
                    $customvalidation .= 'return $("#captchaId").val(); ';
                    $customvalidation .= '}, ';
                    $customvalidation .= 'input: function() { ';
                    $customvalidation .= 'return $("#antibotcode").val(); ';
                    $customvalidation .= '} } } ';
                    $customvalidation .= '}, ';
                    $customvalidation_m .= '"captcha[input]": { required: "' . tra("This field is required") . '"}, ';
                }
                if ($prefs['useRegisterPasscode'] == 'y') {
                    $customvalidation .= 'passcode: {
								required: true,
								remote: {
									url: "validate-ajax.php",
									type: "post",
									data: {
										validator: "passcode",
										input: function() {
											return $("#passcode").val();
											}
										}
									}
								}, ';
                    $customvalidation_m .= 'passcode: { required: "' . tra("This field is required") . '"}, ';
                }
            }
            $validationjs = $validatorslib->generateTrackerValidateJS($flds['data'], $fields_prefix, $customvalidation, $customvalidation_m);
            if (!empty($params['_ajax_form_ins_id']) && $params['_ajax_form_ins_id'] === 'group') {
                $headerlib->add_jq_onready("var ajaxTrackerValidation_group={validation:{" . $validationjs . '};');
                // return clean rules and messages object for ajax
            } else {
                $smarty->assign('validationjs', $validationjs);
                $back .= $smarty->fetch('tracker_validator.tpl');
            }
        }
        if ($params['formtag'] == 'y') {
            //check if tracker has custom form classes, else default to form-horizontal
            $formClasses = $tracker['useFormClasses'] == 'y' ? $tracker['formClasses'] : "form-horizontal";
            $back .= '<form class="' . $formClasses . '" name="editItemForm' . $iTRACKER . '" id="editItemForm' . $iTRACKER . '" enctype="multipart/form-data" method="post"' . (isset($target) ? ' target="' . $target . '"' : '') . ' action="' . $_SERVER['REQUEST_URI'] . '"><input type="hidden" name="trackit" value="' . $trackerId . '" />';
            $back .= '<input type="hidden" name="refresh" value="1" />';
        }
        $back .= '<input type="hidden" name="iTRACKER" value="' . $iTRACKER . '" />';
        if (isset($_REQUEST['page'])) {
            $back .= '<input type="hidden" name="page" value="' . $_REQUEST["page"] . '" />';
        }
        // for registration
        if (isset($_REQUEST['name'])) {
            $back .= '<input type="hidden" name="name" value="' . $_REQUEST["name"] . '" />';
        }
        if (isset($_REQUEST['pass'])) {
            $back .= '<input type="hidden" name="pass" value="' . $_REQUEST["pass"] . '" />';
            $back .= '<input type="hidden" name="passAgain" value="' . $_REQUEST["pass"] . '" />';
        }
        if (isset($_REQUEST['email'])) {
            $back .= '<input type="hidden" name="email" value="' . $_REQUEST["email"] . '" />';
        }
        if (isset($_REQUEST['antibotcode'])) {
            $back .= '<input type="hidden" name="antibotcode" value="' . $_REQUEST["antibotcode"] . '" />';
        }
        if (isset($_REQUEST['chosenGroup'])) {
            // for registration
            $back .= '<input type="hidden" name="chosenGroup" value="' . $_REQUEST["chosenGroup"] . '" />';
        }
        if (isset($_REQUEST['register'])) {
            $back .= '<input type="hidden" name="register" value="' . $_REQUEST["register"] . '" />';
        }
        if ($showtitle == 'y') {
            $back .= '<div class="h1">' . $tracker["name"] . '</div>';
        }
        if ($showdesc == 'y' && $tracker['description']) {
            if ($tracker['descriptionIsParsed'] == 'y') {
                $back .= '<div class="wikitext">' . $tikilib->parse_data($tracker['description']) . '</div><br />';
            } else {
                $back .= '<div class="wikitext">' . tra($tracker["description"]) . '</div><br />';
            }
        }
        if (isset($_REQUEST['tr_preview'])) {
            // use for the computed and join fields
            $assocValues = array();
            $assocNumerics = array();
            foreach ($flds['data'] as $f) {
                if (empty($f['value']) && ($f['type'] == 'u' || $f['type'] == 'g' || $f['type'] == 'I') && ($f['options_array'][0] == '1' || $f['options_array'][0] == '2')) {
                    //need to fill the selector fields for the join
                    $f['value'] = $f['type'] == 'I' ? $tikilib->get_ip_address() : ($f['type'] == 'g' ? $group : $user);
                }
                $assocValues[$f['fieldId']] = $f['value'];
                $assocNumerics[$f['fieldId']] = preg_replace('/[^0-9\\.\\+]/', '', $f['value']);
                // get rid off the $ and such unit
            }
        }
        if (!empty($itemId)) {
            $item = array('itemId' => $itemId, 'trackerId' => $trackerId);
        } else {
            $item = array('itemId' => '');
        }
        foreach ($flds['data'] as $i => $f) {
            // collect additional infos
            if (in_array($f['fieldId'], $outf)) {
                $flds['data'][$i]['ins_id'] = $f['type'] == 'e' ? 'ins_' . $f['fieldId'] : $fields_prefix . $f['fieldId'];
                if (($f['isHidden'] == 'c' || $f['isHidden'] == 'p') && !empty($itemId) && !isset($item['creator'])) {
                    $item['creator'] = $trklib->get_item_creator($trackerId, $itemId);
                }
            }
        }
        if (!empty($showstatus) && $showstatus == 'y') {
            $status_types = $trklib->status_types();
            $smarty->assign_by_ref('status_types', $status_types);
            $smarty->assign('form_status', 'status');
            $smarty->assign_by_ref('tracker', $tracker);
            if (!empty($item_info)) {
                $smarty->assign_by_ref('item', $item_info);
            }
            $status_input = $smarty->fetch('tracker_status_input.tpl');
        }
        $labelclass = 'col-md-3';
        $inputclass = 'col-md-9';
        $buttonclass = 'col-md-9 col-md-offset-3';
        if ($registration == "y") {
            $back .= '<input type="hidden" name="register" value="Register">';
            $labelclass = 'col-md-4 col-sm-3';
            $inputclass = 'col-md-4 col-sm-6';
            $buttonclass = 'col-md-8 col-md-offset-4';
        }
        // Loop on tracker fields and display form
        if (empty($tpl) && empty($wiki)) {
            $back .= '<div class="wikiplugin_tracker">';
            if (!empty($showstatus) && $showstatus == 'y') {
                $back .= '<div class="alert alert-info">' . tra('Status') . $status_input . '</div>';
                // <tr><td>'.tra('Status').'</td><td>'.$status_input.'</td></tr>
            }
            if ($registration == 'y' && $prefs["user_register_prettytracker"] != 'y') {
                $back .= $smarty->fetch('register-form.tpl');
            }
        } else {
            $back .= '<div class="wikiplugin_tracker">';
            if (!empty($showstatus) && $showstatus == 'y') {
                $smarty->assign_by_ref('f_status_input', $status_input);
            }
        }
        $backLength0 = strlen($back);
        foreach ($flds['data'] as $f) {
            if (!in_array($f['fieldId'], $auto_fieldId) && in_array($f['fieldId'], $hidden_fieldId)) {
                // Show in hidden form
                $back .= '<span style="display:none;">' . wikiplugin_tracker_render_input($f, $item, $dynamicSave) . '</span>';
            } elseif (!in_array($f['fieldId'], $auto_fieldId) && in_array($f['fieldId'], $outf)) {
                if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                    $onemandatory = true;
                }
                if ($f['type'] == 'A') {
                    $smarty->assign_by_ref('tiki_p_attach_trackers', $perms['tiki_p_attach_trackers']);
                }
                if (!empty($tpl) || !empty($wiki)) {
                    if ($prettyModifier[$f['fieldId']] == "output") {
                        //check if modifier is set to "output" ( set in getPrettyFieldIds() in trackerlib )
                        $prettyout = '<span class="outputPretty" id="track_' . $f['fieldId'] . '" name="track_' . $f['fieldId'] . '">' . wikiplugin_tracker_render_value($f, $item) . '</span>';
                        $smarty->assign('f_' . $f['fieldId'], $prettyout);
                        $smarty->assign('f_' . $f['permName'], $prettyout);
                    } else {
                        $mand = ($showmandatory == 'y' and $f['isMandatory'] == 'y') ? "&nbsp;<strong class='mandatory_star'>*</strong>&nbsp;" : '';
                        if (!empty($f['description'])) {
                            $desc = $f['descriptionIsParsed'] == 'y' ? $tikilib->parse_data($f['description']) : tra($f['description']);
                            $desc = '<div class="trackerplugindesc">' . $desc . '</div>';
                        } else {
                            $desc = '';
                        }
                        if (!empty($prettyModifier[$f['fieldId']])) {
                            // check if a template was specified in prettyModifier
                            $smarty->assign("field_name", $f['name']);
                            $smarty->assign("field_id", $f['fieldId']);
                            $smarty->assign("permname", $f['permName']);
                            $smarty->assign("mandatory_sym", $mand);
                            $smarty->assign("field_input", wikiplugin_tracker_render_input($f, $item, $dynamicSave));
                            $smarty->assign("description", $desc);
                            $smarty->assign("field_type", $f['type']);
                            $prettyout = $smarty->fetch($prettyModifier[$f['fieldId']]);
                            //fetch template identified in prettyModifier
                        } else {
                            $prettyout = wikiplugin_tracker_render_input($f, $item, $dynamicSave) . $mand . $desc;
                        }
                        $smarty->assign('f_' . $f['fieldId'], $prettyout);
                        $smarty->assign('f_' . $f['permName'], $prettyout);
                    }
                } else {
                    $back .= '<div class="form-group tracker_input_label"';
                    // <tr><td class="tracker_input_label"
                    // If type is has a samerow param and samerow is "No", show text on one line and the input field on the next
                    $isTextOnSameRow = true;
                    switch ($f['type']) {
                        case 't':
                            // Text field
                        // Text field
                        case 'n':
                            // Numeric field
                        // Numeric field
                        case 'b':
                            // Currency
                            if (empty($f['options_array']) || isset($f['options_array']['0']) && strlen($f['options_array']['0']) == 0) {
                                // Use default
                                //	Pending: Unable to locate the object to check to determine the default (in the tracker field definitions). Hardcode true. Arild
                                $isTextOnSameRow = true;
                            } else {
                                $isTextOnSameRow = intval($f['options_array']['0']) == 0 ? false : true;
                            }
                            break;
                        case 'a':
                            // Text area
                            $isTextOnSameRow = true;
                            if (isset($f['options_array']['8'])) {
                                if (empty($f['options_array']) || isset($f['options_array']['8']) && strlen($f['options_array']['8']) == 0) {
                                    // Use default
                                    //	Pending: Unable to locate the object to check to determine the default (in the tracker field definitions). Hardcode true. Arild
                                    $isTextOnSameRow = true;
                                } else {
                                    $isTextOnSameRow = intval($f['options_array']['8']) == 0 ? false : true;
                                }
                            }
                            break;
                    }
                    if (!empty($colwidth)) {
                        $back .= " width='" . $colwidth . "'";
                    }
                    $back .= '><label class="' . $labelclass . ' control-label" for="' . $f['ins_id'] . '">' . wikiplugin_tracker_name($f['fieldId'], tra($f['name']), $field_errors);
                    //
                    if ($showmandatory == 'y' and $f['isMandatory'] == 'y' && $registration != 'y') {
                        $back .= " <strong class='mandatory_star'>*</strong> ";
                    }
                    $back .= '</label>';
                    // If use different lines, add a line break.
                    // Otherwise a new column
                    if (!$isTextOnSameRow) {
                        $back .= "<br/>";
                    } else {
                        $back .= '<div class="' . $inputclass . ' tracker_input_value tracker_field' . $f['fieldId'] . '">';
                        // '</td><td class="tracker_input_value">';
                    }
                    $back .= wikiplugin_tracker_render_input($f, $item, $dynamicSave) . "</div>";
                    // chibaguy added /divs
                    if ($showmandatory == 'y' and $f['isMandatory'] == 'y' && $registration == 'y') {
                        $back .= '<div class="col-md-1 col-sm-1"><span class="text-danger tips" title=":' . tra('This field is mandatory') . '">*</span></div>';
                    }
                    if ($isTextOnSameRow) {
                        $back .= '</div>';
                    }
                }
                if ($f['type'] != 'S' && empty($tpl) && empty($wiki)) {
                    if ($showfieldsdesc == 'y') {
                        $back .= '<div class="form-group tracker-help-block"><div class="' . $labelclass . ' control-label sr-only">Label</div><div class="' . $inputclass . ' trackerplugindesc help-block">';
                        if ($f['descriptionIsParsed'] == 'y') {
                            $back .= $tikilib->parse_data($f['description']);
                        } else {
                            $back .= tra($f['description']);
                        }
                        $back .= '</div></div>';
                    }
                }
            }
        }
        if (isset($params['fieldsfill']) && !empty($params['fieldsfill']) && empty($itemId)) {
            // $back.= '<tr><td><label for="ins_fill">' . tra("Create multiple items (one per line).") . '</label>';
            $back .= '<div class="form-group"><label class="col-md-3" for="ins_fill">' . tra("Insert one item per line:") . '<br />' . '<br />' . '<br />' . '</label>';
            $back .= <<<FILL
// </td><td>
<input type="hidden" value="" name="mode_wysiwyg"/>
<input type="hidden" value="" name="mode_normal"/>
<div class="edit-zone">
<textarea id="ins_fill" class="wikiedit class="form-control" data-syntax="" data-codemirror="" onkeyup="" rows="15" name="ins_fill" >
</textarea>
</div>
<input type="hidden" value="n" name="wysiwyg"/>
<div name="ins_fill_desc" class="trackerplugindesc" >
FILL;
            $back .= sprintf(tra('Each line is a list of %d field values separated with: %s'), $fill_line_cant, htmlspecialchars($fieldsfillseparator));
            $back .= '</div><div name="ins_fill_desc2" class="trackerplugindesc" >' . htmlspecialchars(implode($fieldsfillseparator, $fieldsfillnames));
            $back .= '</div>';
            //	$back .= '</td></tr>';
        }
        if ($prefs['feature_antibot'] == 'y' && (empty($user) || !empty($user) && isset($_REQUEST['error']) && $_REQUEST['error'] == 'y')) {
            $smarty->assign('showantibot', true);
        }
        if (!empty($tpl)) {
            $smarty->security = true;
            $back .= $smarty->fetch($tpl);
        } elseif (!empty($wiki)) {
            $smarty->security = true;
            if ($tikilib->page_exists($wiki)) {
                $back .= $smarty->fetch('wiki:' . $wiki);
            } else {
                $back .= '<span class="alert-warning">' . tr('Missing wiki template page "%0"', htmlspecialchars($wiki)) . '</span>';
            }
        }
        $smarty->assign('showmandatory', $showmandatory);
        if ($prefs['feature_antibot'] == 'y' && empty($user) && (!isset($transactionStep) || $transactionStep == 0) && $params['formtag'] != 'n' && ($registration != 'y' || $prefs["user_register_prettytracker"] != 'y')) {
            // in_tracker session var checking is for tiki-register.php
            $smarty->assign('antibot_table', empty($wiki) && empty($tpl) ? 'n' : 'y');
            $captchalib = TikiLib::lib('captcha');
            $smarty->assign('captchalib', $captchalib);
            if ($registration == 'y') {
                $smarty->assign('form', 'register');
            }
            $back .= $smarty->fetch('antibot.tpl');
        }
        $back .= '</div>';
        if ($params['formtag'] == 'y') {
            if (empty($wiki) && empty($tpl)) {
                $back .= '<div class="form-group"><div class="input_submit_container btn-bar ' . $buttonclass . '">';
            } else {
                $back .= '<div class="form-group"><div class="input_submit_container btn-bar">';
            }
            if (!empty($reset)) {
                $back .= '<input class="button submit preview" type="reset" name="tr_reset" value="' . tra($reset) . '" />';
            }
            if (!empty($preview)) {
                $back .= '<input class="btn btn-default button submit preview" type="submit" name="tr_preview" value="' . tra($preview) . '" />';
            }
            foreach ($action as $key => $act) {
                $back .= '<input class="button submit ' . $action_style[$key] . '" type="submit" name="action' . $key . '" value="' . tra($act) . '" onclick="needToConfirm=false" />';
            }
            $back .= '</div></div>';
        }
        if ($showmandatory == 'y' and $onemandatory) {
            if (empty($wiki) && empty($tpl)) {
                $back .= "<div class='form-group'><div class='" . $buttonclass . "'><div class='text-center alert alert-danger'><em>" . tra("Fields marked with an * are mandatory.") . "</em></div></div></div>";
            } else {
                $back .= "<div class='form-group'><div class='text-center alert alert-danger'><em>" . tra("Fields marked with an * are mandatory.") . "</em></div></div>";
            }
        }
        if ($params['formtag'] == 'y') {
            $back .= '</form>';
        }
        if (!empty($params['_ajax_form_ins_id'])) {
            // save new js in a function for the form init fn
            $headerlib->add_js(' var ajaxTrackerFormInit_' . $params['_ajax_form_ins_id'] . ' = function() {' . $headerlib->output_js(false) . '}', 10);
            // put back the pre-existing js
            $headerlib->js = array_merge($headerlib->js, $old_js['js']);
            $headerlib->jq_onready = array_merge($headerlib->jq_onready, $old_js['jq_onready']);
        }
        if (!empty($page)) {
            $back .= '~/np~';
        }
        $smarty->assign_by_ref('tiki_p_admin_trackers', $perms['tiki_p_admin_trackers']);
        return $back;
    } else {
        if (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
            $smarty->assign('wikiplugin_tracker', $trackerId);
        }
        //used in vote plugin
        $id = ' id="wikiplugin_tracker' . $iTRACKER . '"';
        if ($showtitle == 'y') {
            $back .= '<div class="h1"' . $id . '>' . $tracker["name"] . '</div>';
            $id = '';
        }
        if ($showdesc == 'y') {
            $back .= '<div class="wikitext"' . $id . '>' . $tracker["description"] . '</div><br />';
            $id = '';
        }
        $back .= "<div{$id}>" . $data . '</div>';
        return $back;
    }
}
Example #2
0
function wikiplugin_tracker($data, $params)
{
    global $tikilib, $trklib, $userlib, $dbTiki, $notificationlib, $user, $group, $page, $tiki_p_admin, $tiki_p_create_tracker_items, $smarty;
    //var_dump($_REQUEST);
    extract($params, EXTR_SKIP);
    if (!isset($embedded)) {
        $embedded = "n";
    }
    if (!isset($showtitle)) {
        $showtitle = "n";
    }
    if (!isset($showdesc)) {
        $showdesc = "n";
    }
    if (!isset($trackerId)) {
        return "<b>missing tracker ID for plugin TRACKER</b><br />";
    }
    if (!isset($action)) {
        $action = tra("Save");
    }
    if (!isset($showmandatory)) {
        $showmandatory = 'y';
    }
    if (!isset($permMessage)) {
        $permMessage = tra("You do not have permission to insert an item");
    }
    if ($userlib->object_has_one_permission($trackerId, 'tracker')) {
        if ($tiki_p_admin != 'y') {
            $perms = $userlib->get_permissions(0, -1, 'permName_desc', '', 'trackers');
            foreach ($perms["data"] as $perm) {
                $permName = $perm["permName"];
                if ($userlib->object_has_permission($user, $trackerId, 'tracker', $permName)) {
                    ${$permName} = 'y';
                    $smarty->assign("{$permName}", 'y');
                } else {
                    ${$permName} = 'n';
                    $smarty->assign("{$permName}", 'n');
                }
            }
        }
    }
    // permission checking
    if ($tiki_p_create_tracker_items != 'y') {
        return '<b>' . $permMessage . '</b>';
    }
    $tracker = $tikilib->get_tracker($trackerId);
    if (!isset($_REQUEST["ok"]) || $_REQUEST["ok"] == "n") {
        $field_errors = array('err_mandatory' => array(), 'err_value' => array());
        if ($tracker) {
            include_once 'lib/trackers/trackerlib.php';
            global $notificationlib;
            include_once 'lib/notifications/notificationlib.php';
            $tracker = array_merge($tracker, $trklib->get_tracker_options($trackerId));
            $flds = $trklib->list_tracker_fields($trackerId, 0, -1, "position_asc", "");
            $back = '';
            $bad = array();
            $embeddedId = false;
            $onemandatory = false;
            $full_fields = array();
            $mainfield = '';
            if (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
                $cpt = 0;
                foreach ($flds['data'] as $fl) {
                    // store value to display it later if form
                    // isn't fully filled.
                    if (isset($_REQUEST['track'][$fl['fieldId']])) {
                        $flds['data'][$cpt]['value'] = $_REQUEST['track'][$fl['fieldId']];
                    } else {
                        $flds['data'][$cpt]['value'] = '';
                    }
                    $full_fields[$fl['fieldId']] = $fl;
                    if ($embedded == 'y' and $fl['name'] == 'page') {
                        $embeddedId = $fl['fieldId'];
                    }
                    if ($fl['isMain'] == 'y') {
                        $mainfield = $flds['data'][$cpt]['value'];
                    }
                    if ($fl['type'] == 'e') {
                        $ins_fields['data'][] = array_merge(array('value' => ''), $fl);
                    }
                    $cpt++;
                }
                if (isset($_REQUEST['track'])) {
                    foreach ($_REQUEST['track'] as $fld => $val) {
                        //$ins_fields["data"][] = array('fieldId' => $fld, 'value' => $val, 'type' => 1);
                        $ins_fields["data"][] = array_merge(array('value' => $val), $full_fields[$fld]);
                    }
                }
                if (isset($_FILES['track'])) {
                    // image fields
                    foreach ($_FILES['track'] as $label => $w) {
                        foreach ($w as $fld => $val) {
                            if ($label == 'tmp_name' && is_uploaded_file($val)) {
                                $fp = fopen($val, 'rb');
                                $data = '';
                                while (!feof($fp)) {
                                    $data .= fread($fp, 8192 * 16);
                                }
                                fclose($fp);
                                $files[$fld]['value'] = $data;
                            } else {
                                $files[$fld]['file_' . $label] = $val;
                            }
                        }
                    }
                    foreach ($files as $fld => $file) {
                        $ins_fields['data'][] = array_merge($file, $full_fields[$fld]);
                    }
                }
                if (isset($_REQUEST['authorfieldid']) and $_REQUEST['authorfieldid']) {
                    $ins_fields["data"][] = array('fieldId' => $_REQUEST['authorfieldid'], 'value' => $user, 'type' => 'u', 'options' => 1);
                }
                if (isset($_REQUEST['authorgroupfieldid']) and $_REQUEST['authorgroupfieldid']) {
                    $ins_fields["data"][] = array('fieldId' => $_REQUEST['authorgroupfieldid'], 'value' => $group, 'type' => 'g', 'options' => 1);
                }
                if ($embedded == 'y') {
                    $ins_fields["data"][] = array('fieldId' => $embeddedId, 'value' => $_REQUEST['page']);
                }
                $ins_categs = array();
                $categorized_fields = array();
                while (list($postVar, $postVal) = each($_REQUEST)) {
                    if (preg_match("/^ins_cat_([0-9]+)/", $postVar, $m)) {
                        foreach ($postVal as $v) {
                            $ins_categs[] = $v;
                        }
                        $categorized_fields[] = $m[1];
                    }
                }
                // Check field values for each type and presence of mandatory ones
                $field_errors = $trklib->check_field_values($ins_fields, $categorized_fields);
                // values are OK, then lets add a new item
                if (count($field_errors['err_mandatory']) == 0 && count($field_errors['err_value']) == 0) {
                    $rid = $trklib->replace_item($trackerId, 0, $ins_fields, $tracker['newItemStatus']);
                    $trklib->categorized_item($trackerId, $rid, $mainfield, $ins_categs);
                    header("Location: tiki-index.php?page=" . urlencode($page) . "&ok=y");
                    die;
                    // return "<div>$data</div>";
                }
            } else {
                for ($i = 0; $i < count($flds['data']); $i++) {
                    $flds['data'][$i]['value'] = '';
                }
            }
            $optional = array();
            if (isset($fields)) {
                $outf = array();
                $fl = split(":", $fields);
                foreach ($fl as $l) {
                    if (substr($l, 0, 1) == '-') {
                        $l = substr($l, 1);
                        $optional[] = $l;
                    }
                    $outf[] = $l;
                }
            }
            // Display warnings when needed
            if (count($field_errors['err_mandatory']) > 0) {
                $back .= '<div class="simplebox highlight">';
                $back .= tra('Following mandatory fields are missing') . '&nbsp;:<br/>';
                $coma_cpt = count($field_errors['err_mandatory']);
                foreach ($field_errors['err_mandatory'] as $f) {
                    $back .= $f['name'];
                    $back .= --$coma_cpt > 0 ? ',&nbsp;' : '';
                }
                $back .= '</div><br />';
            }
            if (count($field_errors['err_value']) > 0) {
                $back .= '<div class="simplebox highlight">';
                $back .= tra('Following fields are incorrect') . '&nbsp;:<br/>';
                $coma_cpt = count($field_errors['err_value']);
                foreach ($field_errors['err_value'] as $f) {
                    $back .= $f['name'];
                    $back .= --$coma_cpt > 0 ? ',&nbsp;' : '';
                }
                $back .= '</div><br />';
            }
            $back .= '~np~<form enctype="multipart/form-data" method="post"><input type="hidden" name="trackit" value="' . $trackerId . '" />';
            if (!empty($_REQUEST['page'])) {
                $back .= '<input type="hidden" name="page" value="' . $_REQUEST["page"] . '" />';
            }
            $back .= '<input type="hidden" name="refresh" value="1" />';
            if ($showtitle == 'y') {
                $back .= '<div class="titlebar">' . $tracker["name"] . '</div>';
            }
            if ($showdesc == 'y') {
                $back .= '<div class="wikitext">' . $tracker["description"] . '</div><br />';
            }
            // Loop on tracker fields and display form
            $back .= '<table>';
            foreach ($flds['data'] as $f) {
                if ($f['type'] == 'u' and $f['options'] == '1') {
                    $back .= '<input type="hidden" name="authorfieldid" value="' . $f['fieldId'] . '" />';
                }
                if ($f['type'] == 'g' and $f['options'] == '1') {
                    $back .= '<input type="hidden" name="authorgroupfieldid" value="' . $f['fieldId'] . '" />';
                }
                if (in_array($f['fieldId'], $outf)) {
                    if (in_array($f['fieldId'], $optional)) {
                        $f['name'] = "<i>" . $f['name'] . "</i>";
                    }
                    // numeric or text field
                    if ($f['type'] == 't' or $f['type'] == 'n' and $f["fieldId"] != $embeddedId or $f['type'] == 'm') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $back .= '<input type="text" name="track[' . $f["fieldId"] . ']" value="' . $f['value'] . '"';
                        if (isset($f['options_array'][1])) {
                            $back .= 'size="' . $f['options_array'][1] . '" maxlength="' . $f['options_array'][1] . '"';
                        } else {
                            $back .= 'size="30"';
                        }
                        $back .= '/>';
                        // item link
                    } elseif ($f['type'] == 'r') {
                        $list = $trklib->get_all_items($f['options_array'][0], $f['options_array'][1], 'o');
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $back .= '<select name="track[' . $f["fieldId"] . ']">';
                        $back .= '<option value=""></option>';
                        foreach ($list as $key => $item) {
                            $selected = $f['value'] == $item ? 'selected="selected"' : '';
                            $back .= '<option value="' . $item . '" ' . $selected . '>' . $item . '</option>';
                        }
                        $back .= "</select>";
                        // textarea
                    } elseif ($f['type'] == 'a') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        if (isset($f['options_array'][1])) {
                            $back .= '<textarea cols=' . $f['options_array'][1] . ' rows=' . $f['options_array'][2] . ' name="track[' . $f["fieldId"] . ']" wrap="soft">' . $f['value'] . '</textarea>';
                        } else {
                            $back .= '<textarea cols="29" rows="7" name="track[' . $f["fieldId"] . ']" wrap="soft">' . $f['value'] . '</textarea>';
                        }
                        // user selector
                    } elseif ($f['type'] == 'u' and $f['options'] == '1') {
                        $back .= '<tr><td>' . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors) . '</td><td>' . $user;
                        // drop down, user selector or group selector
                    } elseif ($f['type'] == 'd' or $f['type'] == 'u' or $f['type'] == 'g' or $f['type'] == 'r') {
                        if ($f['type'] == 'd') {
                            $list = split(',', $f['options']);
                        } elseif ($f['type'] == 'u') {
                            if ($f['options'] == 1 or $f['options'] == 2) {
                                $list = false;
                            } else {
                                $list = $userlib->list_all_users();
                            }
                        } elseif ($f['type'] == 'g') {
                            $list = $userlib->list_all_groups();
                        }
                        if ($list) {
                            $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                            if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                                $back .= "&nbsp;<b>*</b>&nbsp;";
                                $onemandatory = true;
                            }
                            $back .= "</td><td>";
                            $back .= '<select name="track[' . $f["fieldId"] . ']">';
                            foreach ($list as $item) {
                                $selected = $f['value'] == $item ? 'selected="selected"' : '';
                                $back .= '<option value="' . $item . '" ' . $selected . '>' . $item . '</option>';
                            }
                            $back .= "</select>";
                        } else {
                            $back .= '<input type="hidden" name="track[' . $f["fieldId"] . ']" value="' . $user . '" />';
                        }
                    } elseif ($f['type'] == 'h') {
                        $back .= "</td></tr></table><h2>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors) . "</h2><table><tr><td>";
                    } elseif ($f['type'] == 'e') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $k = $f["options_array"][0];
                        global $categlib;
                        include_once 'lib/categories/categlib.php';
                        $cats = $categlib->get_child_categories($k);
                        $i = 0;
                        foreach ($cats as $cat) {
                            $checked = $f['value'] == $cat['categId'] ? 'checked="checked"' : '';
                            $back .= '<input type="checkbox" name="ins_cat_' . $f['fieldId'] . '[]" value="' . $cat["categId"] . '" ' . $checked . '>' . $cat['name'] . '</input><br />';
                        }
                    } elseif ($f['type'] == 'c') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $checked = $f['value'] == 'y' ? 'checked="checked"' : '';
                        $back .= '</td><td><input type="checkbox" name="track[' . $f["fieldId"] . ']" value="y" ' . $checked . '/>';
                    } elseif ($f['type'] == 'i') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $back .= '<input type="file" name="track[' . $f["fieldId"] . ']" />';
                    } else {
                    }
                    $back .= "</td></tr>";
                }
            }
            $back .= "<tr><td></td><td><input type='submit' name='action' value='" . $action . "'>";
            if ($showmandatory == 'y' and $onemandatory) {
                $back .= "<br /><i>" . tra("Fields marked with a * are mandatory.") . "</i>";
            }
            $back .= "</td></tr>";
            $back .= "</table>";
            $back .= "</form>~/np~";
        } else {
            $back = "No such id in trackers.";
        }
        return $back;
    } else {
        $back = '';
        if ($showtitle == 'y') {
            $back .= '<div class="titlebar">' . $tracker["name"] . '</div>';
        }
        if ($showdesc == 'y') {
            $back .= '<div class="wikitext">' . $tracker["description"] . '</div><br />';
        }
        $back .= '<div>' . $data . '</div>';
        return $back;
    }
}
function wikiplugin_tracker($data, $params)
{
    global $tikilib, $userlib, $dbTiki, $user, $group, $page, $tiki_p_admin, $tiki_p_create_tracker_items, $smarty, $prefs, $trklib, $tiki_p_tracker_vote_ratings;
    include_once 'lib/trackers/trackerlib.php';
    //var_dump($_REQUEST);
    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);
        $usertracker = true;
    } elseif (!empty($trackerId) && !empty($_REQUEST['view_user'])) {
        $itemId = $trklib->get_user_item($trackerId, $tracker, $_REQUEST['view_user']);
    }
    if (!isset($trackerId)) {
        return $smarty->fetch("wiki-plugins/error_tracker.tpl");
    }
    if (!isset($embedded)) {
        $embedded = "n";
    }
    if (!isset($showtitle)) {
        $showtitle = "n";
    }
    if (!isset($showdesc)) {
        $showdesc = "n";
    }
    if (!isset($sort)) {
        $sort = 'n';
    }
    if (!isset($action)) {
        $action = 'Save';
    }
    if (isset($preview)) {
        if (empty($preview)) {
            $preview = 'Preview';
        }
    } else {
        unset($_REQUEST['tr_preview']);
    }
    if (!isset($showmandatory)) {
        $showmandatory = 'y';
    }
    $smarty->assign('showmandatory', $showmandatory);
    if (isset($values)) {
        if (!is_array($values)) {
            $values = explode(':', $values);
        }
    }
    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']);
        }
    }
    if (empty($_SERVER['SCRIPT_NAME']) || !strstr($_SERVER['SCRIPT_NAME'], 'tiki-register.php')) {
        if (!empty($itemId) && $tracker['writerCanModify'] == 'y' && isset($usertracker) && $usertracker) {
            // user tracker he can modify
        } else {
            $perms = $tikilib->get_perm_object($trackerId, 'tracker', $tracker, false);
            if ($perms['tiki_p_create_tracker_items'] == 'n' && empty($itemId)) {
                return '<b>' . tra("You do not have permission to insert an item") . '</b>';
            } elseif ($perms['tiki_p_modify_tracker_items'] == 'n' && !empty($itemId)) {
                return '<b>' . tra("You do not have permission to modify an item") . '</b>';
            }
        }
    }
    if (isset($_REQUEST['removeattach']) && $tracker['useAttachments'] == 'y') {
        $owner = $trklib->get_item_attachment_owner($_REQUEST['removeattach']);
        if ($tiki_p_wiki_admin_attachments == '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 = '';
    $thisIsThePlugin = isset($_REQUEST['trackit']) && $_REQUEST['trackit'] == $trackerId && (isset($_REQUEST['fields']) && isset($params['fields']) && $_REQUEST['fields'] == $params['fields'] || !isset($_REQUEST['fields']) && !isset($params['fields']));
    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;
        }
        $flds = $trklib->list_tracker_fields($trackerId, 0, -1, "position_asc", "");
        $bad = array();
        $embeddedId = false;
        $onemandatory = false;
        $full_fields = array();
        $mainfield = '';
        if ($thisIsThePlugin) {
            /* ------------------------------------- Recup all values from REQUEST -------------- */
            $cpt = 0;
            if (isset($fields)) {
                $fields_plugin = split(':', $fields);
            }
            foreach ($flds['data'] as $fl) {
                // store value to display it later if form
                // isn't fully filled.
                if (($flds['data'][$cpt]['type'] == 'u' || $flds['data'][$cpt]['type'] == 'g' || $flds['data'][$cpt]['type'] == 'I') && ($flds['data'][$cpt]['options_array'][0] == '1' || $flds['data'][$cpt]['options_array'][0] == '2') && $tiki_p_admin_trackers != 'y' && empty($_REQUEST['track'][$fl['fieldId']])) {
                    if (empty($itemId) && ($flds['data'][$cpt]['options_array'][0] == '1' || $flds['data'][$cpt]['options_array'][0] == '2')) {
                        if ($flds['data'][$cpt]['type'] == 'u') {
                            $_REQUEST['track'][$fl['fieldId']] = empty($user) ? empty($_REQUEST['name']) ? '' : $_REQUEST['name'] : $user;
                        } elseif ($flds['data'][$cpt]['type'] == 'g') {
                            $_REQUEST['track'][$fl['fieldId']] = $group;
                        } elseif ($flds['data'][$cpt]['type'] == 'I') {
                            $_REQUEST['track'][$fl['fieldId']] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
                        }
                    } elseif (!empty($itemId) && $flds['data'][$cpt]['options_array'][0] == '2') {
                        if ($flds['data'][$cpt]['type'] == 'u') {
                            $_REQUEST['track'][$fl['fieldId']] = $user;
                        } elseif ($flds['data'][$cpt]['type'] == 'g') {
                            $_REQUEST['track'][$fl['fieldId']] = $group;
                        } elseif ($flds['data'][$cpt]['type'] == 'I') {
                            $_REQUEST['track'][$fl['fieldId']] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
                        }
                    }
                } elseif ($flds['data'][$cpt]['type'] == 'f') {
                    $ins_id = 'track_' . $fl['fieldId'];
                    if (isset($_REQUEST[$ins_id . 'Day'])) {
                        if (empty($_REQUEST['$ins_id' . 'Hour'])) {
                            $_REQUEST['$ins_id' . 'Hour'] = 0;
                        }
                        if (empty($_REQUEST['$ins_id' . 'Minute'])) {
                            $_REQUEST['$ins_id' . 'Minute'] = 0;
                        }
                        $_REQUEST['track'][$fl['fieldId']] = $tikilib->make_time($_REQUEST["{$ins_id}" . "Hour"], $_REQUEST["{$ins_id}" . "Minute"], 0, $_REQUEST["{$ins_id}" . "Month"], $_REQUEST["{$ins_id}" . "Day"], $_REQUEST["{$ins_id}" . "Year"]);
                    } else {
                        $_REQUEST['track'][$fl['fieldId']] = $tikilib->now;
                    }
                }
                if (isset($_REQUEST['ins_cat_' . $fl['fieldId']])) {
                    // to remember if error
                    $_REQUEST['track'][$fl['fieldId']] = $_REQUEST['ins_cat_' . $fl['fieldId']];
                }
                if (isset($_REQUEST['track'][$fl['fieldId']])) {
                    $flds['data'][$cpt]['value'] = $_REQUEST['track'][$fl['fieldId']];
                } else {
                    $flds['data'][$cpt]['value'] = '';
                    if ($fl['type'] == 'c' && (empty($fields_plugin) || in_array($fl['fieldId'], $fields_plugin))) {
                        $_REQUEST['track'][$fl['fieldId']] = 'n';
                    } elseif ($fl['type'] == 'R' && $fl['isMandatory'] == 'y' && !isset($_REQUEST['track'][$fl['fieldId']])) {
                        // if none radio is selected, there will be no value and no error if mandatory
                        if (empty($fields_plugin) || in_array($fl['fieldId'], $fields_plugin)) {
                            $_REQUEST['track'][$fl['fieldId']] = '';
                        }
                    }
                }
                if (!empty($_REQUEST['other_track'][$fl['fieldId']])) {
                    $flds['data'][$cpt]['value'] = $_REQUEST['other_track'][$fl['fieldId']];
                }
                $full_fields[$fl['fieldId']] = $fl;
                if ($embedded == 'y' and $fl['name'] == 'page') {
                    $embeddedId = $fl['fieldId'];
                }
                if ($fl['isMain'] == 'y') {
                    $mainfield = $flds['data'][$cpt]['value'];
                }
                $cpt++;
            }
            /*foreach */
            if (isset($_REQUEST['track'])) {
                foreach ($_REQUEST['track'] as $fld => $val) {
                    //$ins_fields["data"][] = array('fieldId' => $fld, 'value' => $val, 'type' => 1);
                    if (!empty($_REQUEST['other_track'][$fld])) {
                        $val = $_REQUEST['other_track'][$fld];
                    }
                    $ins_fields["data"][] = array_merge(array('value' => $val), $full_fields[$fld]);
                }
            }
            if (isset($_FILES['track'])) {
                // image or attachment fields
                foreach ($_FILES['track'] as $label => $w) {
                    foreach ($w as $fld => $val) {
                        if ($label == 'tmp_name' && is_uploaded_file($val)) {
                            $fp = fopen($val, 'rb');
                            $data = '';
                            while (!feof($fp)) {
                                $data .= fread($fp, 8192 * 16);
                            }
                            fclose($fp);
                            $files[$fld]['old_value'] = $files[$fld]['value'];
                            $files[$fld]['value'] = $data;
                        } else {
                            $files[$fld]['file_' . $label] = $val;
                        }
                    }
                }
                foreach ($files as $fld => $file) {
                    $ins_fields['data'][] = array_merge($file, $full_fields[$fld]);
                }
            }
            if ($embedded == 'y' && isset($_REQUEST['page'])) {
                $ins_fields["data"][] = array('fieldId' => $embeddedId, 'value' => $_REQUEST['page']);
            }
            $ins_categs = array();
            $categorized_fields = array();
            while (list($postVar, $postVal) = each($_REQUEST)) {
                if (preg_match("/^ins_cat_([0-9]+)/", $postVar, $m)) {
                    foreach ($postVal as $v) {
                        $ins_categs[] = $v;
                    }
                    $categorized_fields[] = $m[1];
                }
            }
            /* ------------------------------------- End recup all values from REQUEST -------------- */
            /* ------------------------------------- Check field values for each type and presence of mandatory ones ------------------- */
            $field_errors = $trklib->check_field_values($ins_fields, $categorized_fields);
            if (empty($user) && $prefs['feature_antibot'] == 'y') {
                if (!isset($_SESSION['random_number']) || $_SESSION['random_number'] != $_REQUEST['antibotcode']) {
                    $field_errors['err_antibot'] = 'y';
                }
            }
            if (count($field_errors['err_mandatory']) == 0 && count($field_errors['err_value']) == 0 && empty($field_errors['err_antibot']) && !isset($_REQUEST['tr_preview'])) {
                /* ------------------------------------- save the item ---------------------------------- */
                if (!isset($itemId)) {
                    $itemId = $trklib->get_user_item($trackerId, $tracker);
                }
                if (isset($_REQUEST['status'])) {
                    $status = $_REQUEST['status'];
                } elseif (isset($newstatus) && ($newstatus == 'o' || $newstatus == 'c' || $newstatus == 'p')) {
                    $status = $newstatus;
                } elseif (empty($itemId) && isset($tracker['newItemStatus'])) {
                    $status = $tracker['newItemStatus'];
                } else {
                    $status = '';
                }
                $rid = $trklib->replace_item($trackerId, $itemId, $ins_fields, $status, $ins_categs);
                $trklib->categorized_item($trackerId, $rid, $mainfield, $ins_categs);
                if (!empty($email)) {
                    $emailOptions = split("\\|", $email);
                    if (is_numeric($emailOptions[0])) {
                        $emailOptions[0] = $trklib->get_item_value($trackerId, $rid, $emailOptions[0]);
                    }
                    if (empty($emailOptions[0])) {
                        // from
                        $emailOptions[0] = $prefs['sender_email'];
                    }
                    if (empty($emailOptions[1])) {
                        // to
                        $emailOptions[1][0] = $prefs['sender_email'];
                    } else {
                        $emailOptions[1] = split(',', $emailOptions[1]);
                        foreach ($emailOptions[1] as $key => $email) {
                            if (is_numeric($email)) {
                                $emailOptions[1][$key] = $trklib->get_item_value($trackerId, $rid, $email);
                            }
                        }
                    }
                    if (!empty($emailOptions[2])) {
                        //tpl
                        if (!preg_match('/\\.tpl$/', $emailOptions[2])) {
                            $emailOptions[2] .= '.tpl';
                        }
                        $tplSubject = str_replace('.tpl', '_subject.tpl', $emailOptions[2]);
                    } else {
                        $emailOptions[2] = 'tracker_changed_notification.tpl';
                    }
                    if (empty($tplSubject)) {
                        $tplSubject = 'tracker_changed_notification_subject.tpl';
                    }
                    include_once 'lib/webmail/tikimaillib.php';
                    $mail = new TikiMail();
                    @($mail_data = $smarty->fetch('mail/' . $tplSubject));
                    if (empty($mail_data)) {
                        $mail_data = tra('Tracker was modified at ') . $_SERVER["SERVER_NAME"];
                    }
                    $mail->setSubject($mail_data);
                    $mail_data = $smarty->fetch('mail/' . $emailOptions[2]);
                    $mail->setText($mail_data);
                    $mail->setHeader('From', $emailOptions[0]);
                    $mail->send($emailOptions[1]);
                }
                if (empty($url)) {
                    if (!empty($page)) {
                        $url = "tiki-index.php?page=" . urlencode($page) . "&ok=y&trackit={$trackerId}";
                        if (!empty($params['fields'])) {
                            $url .= "&fields=" . urlencode($params['fields']);
                        }
                        $url .= "#wikiplugin_tracker{$trackerId}";
                        header("Location: {$url}");
                        die;
                    } else {
                        return '';
                    }
                } else {
                    header("Location: {$url}");
                    die;
                }
                /* ------------------------------------- end save the item ---------------------------------- */
            } elseif (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
                $smarty->assign('wikiplugin_tracker', $trackerId);
                //used in vote plugin
            }
        } else {
            if (!empty($values) || (!empty($_REQUEST['values']) and empty($_REQUEST['prefills']))) {
                // assign default values for each filedId specify
                if (empty($values)) {
                    // url with values[]=x&values[] witouth the list of fields
                    $values = $_REQUEST['values'];
                }
                if (!is_array($values)) {
                    $values = array($values);
                }
                if (isset($fields)) {
                    $fl = split(':', $fields);
                    for ($j = 0; $j < count($fl); $j++) {
                        for ($i = 0; $i < count($flds['data']); $i++) {
                            if ($flds['data'][$i]['fieldId'] == $fl[$j]) {
                                $flds['data'][$i]['value'] = $values[$j];
                            }
                        }
                    }
                } else {
                    // values contains all the fields value in the default order
                    $i = 0;
                    foreach ($values as $value) {
                        $flds['data'][$i++]['value'] = $value;
                    }
                }
            } elseif (!empty($itemId)) {
                if (isset($fields)) {
                    $fl = split(':', $fields);
                    $filter = '';
                    foreach ($flds['data'] as $f) {
                        if (in_array($f['fieldId'], $fl)) {
                            $filter[] = $f;
                        }
                    }
                } else {
                    $filter =& $flds['data'];
                }
                if (!empty($filter)) {
                    $flds['data'] = $trklib->get_item_fields($trackerId, $itemId, $filter, $itemUser);
                }
            } else {
                if (isset($_REQUEST['values']) && isset($_REQUEST['prefills'])) {
                    //url:prefields=1:2&values[]=x&values[]=y
                    if (!is_array($_REQUEST['values'])) {
                        $_REQUEST['values'] = array($_REQUEST['values']);
                    }
                    $fl = split(':', $_REQUEST['prefills']);
                } else {
                    unset($fl);
                }
                for ($i = 0; $i < count($flds['data']); $i++) {
                    if (isset($fl) && ($j = array_search($flds['data'][$i]['fieldId'], $fl)) !== false) {
                        $flds['data'][$i]['value'] = $_REQUEST['values'][$j];
                    } else {
                        $flds['data'][$i]['value'] = '';
                        // initialize fields with blank values
                    }
                }
            }
        }
        $optional = array();
        $outf = array();
        if (isset($fields) && !empty($fields)) {
            $fl = split(":", $fields);
            if ($sort == 'y') {
                $flds = $trklib->sort_fields($flds, $fl);
            }
            foreach ($fl as $l) {
                if (substr($l, 0, 1) == '-') {
                    $l = substr($l, 1);
                    $optional[] = $l;
                }
                $ok = false;
                foreach ($flds['data'] as $f) {
                    if ($f['fieldId'] == $l) {
                        $ok = true;
                        break;
                    }
                }
                if (!$ok) {
                    $back .= tra('Incorrect fieldId:') . ' ' . $l;
                }
                $outf[] = $l;
            }
        } elseif (!isset($fields)) {
            foreach ($flds['data'] as $f) {
                if ($f['isMandatory'] == 'y') {
                    $optional[] = $f['fieldId'];
                }
                $outf[] = $f['fieldId'];
            }
        }
        // Display warnings when needed
        if (count($field_errors['err_mandatory']) > 0) {
            $back .= '<div class="simplebox highlight"><img src="pics/icons/exclamation.png" alt=" ' . tra('Error') . '" style="vertical-align:middle" /> ';
            $back .= tra('Following mandatory fields are missing') . '&nbsp;:<br/>';
            $coma_cpt = count($field_errors['err_mandatory']);
            foreach ($field_errors['err_mandatory'] as $f) {
                $back .= $f['name'];
                $back .= --$coma_cpt > 0 ? ',&nbsp;' : '';
            }
            $back .= '</div><br />';
            $_REQUEST['error'] = 'y';
        }
        if (count($field_errors['err_value']) > 0) {
            $back .= '<div class="simplebox highlight">';
            $b = '';
            foreach ($field_errors['err_value'] as $f) {
                if (!empty($f['errorMsg'])) {
                    $back .= tra($f['errorMsg']) . '<br>';
                } else {
                    if (!empty($b)) {
                        $b .= ' : ';
                    }
                    $b .= $f['name'];
                }
            }
            if (!empty($b)) {
                $back .= tra('Following fields are incorrect') . '&nbsp;:<br/>' . $b;
            }
            $back .= '</div><br />';
            $_REQUEST['error'] = 'y';
        }
        if (isset($field_errors['err_antibot'])) {
            $back .= '<div class="simplebox highlight"><img src="pics/icons/exclamation.png" alt=" ' . tra('Error') . '" style="vertical-align:middle" /> ';
            $back .= tra('You have mistyped the anti-bot verification code; please try again.');
            $back .= '</div><br />';
            $_REQUEST['error'] = 'y';
        }
        if (count($field_errors['err_mandatory']) > 0 || count($field_errors['err_value']) > 0 || isset($field_errors['err_antibot'])) {
            $smarty->assign('input_err', 'y');
        }
        if (!empty($page)) {
            $back .= '~np~';
        }
        $back .= '<form enctype="multipart/form-data" method="post"><input type="hidden" name="trackit" value="' . $trackerId . '" />';
        if (isset($fields)) {
            $back .= '<input type="hidden" name="fields" value="' . $params['fields'] . '" />';
        }
        //if plugin inserted twice with the same trackerId
        if (!empty($_REQUEST['page'])) {
            $back .= '<input type="hidden" name="page" value="' . $_REQUEST["page"] . '" />';
        }
        $back .= '<input type="hidden" name="refresh" value="1" />';
        if (isset($_REQUEST['page'])) {
            $back .= '<input type="hidden" name="page" value="' . $_REQUEST["page"] . '" />';
        }
        // for registration
        if (isset($_REQUEST['name'])) {
            $back .= '<input type="hidden" name="name" value="' . $_REQUEST["name"] . '" />';
        }
        if (isset($_REQUEST['pass'])) {
            $back .= '<input type="hidden" name="pass" value="' . $_REQUEST["pass"] . '" />';
            $back .= '<input type="hidden" name="passAgain" value="' . $_REQUEST["pass"] . '" />';
        }
        if (isset($_REQUEST['email'])) {
            $back .= '<input type="hidden" name="email" value="' . $_REQUEST["email"] . '" />';
        }
        if (isset($_REQUEST['regcode'])) {
            $back .= '<input type="hidden" name="regcode" value="' . $_REQUEST["regcode"] . '" />';
        }
        if (isset($_REQUEST['chosenGroup'])) {
            // for registration
            $back .= '<input type="hidden" name="chosenGroup" value="' . $_REQUEST["chosenGroup"] . '" />';
        }
        if (isset($_REQUEST['register'])) {
            $back .= '<input type="hidden" name="register" value="' . $_REQUEST["register"] . '" />';
        }
        if ($showtitle == 'y') {
            $back .= '<div class="titlebar">' . $tracker["name"] . '</div>';
        }
        if ($showdesc == 'y' && $tracker['description']) {
            if ($tracker["descriptionIsParsed"] == 'y') {
                $back .= '<div class="wikitext">' . $tikilib->parse_data($tracker["description"], 'false') . '</div><br />';
            } else {
                $back .= '<div class="wikitext">' . $tracker["description"] . '</div><br />';
            }
        }
        if (isset($_REQUEST['tr_preview'])) {
            // use for the computed and join fields
            $assocValues = array();
            $assocNumerics = array();
            foreach ($flds['data'] as $f) {
                if (empty($f['value']) && ($f['type'] == 'u' || $f['type'] == 'g' || $f['type'] == 'I') && ($f['options_array'][0] == '1' || $f['options_array'][0] == '2')) {
                    //need to fill the selector fields for the join
                    $f['value'] = $f['type'] == 'I' ? $_SERVER['REMOTE_ADDR'] : ($f['type'] == 'g' ? $group : $user);
                }
                $assocValues[$f['fieldId']] = $f['value'];
                $assocNumerics[$f['fieldId']] = preg_replace('/[^0-9\\.\\+]/', '', $f['value']);
                // get rid off the $ and such unit
            }
        }
        if (!empty($itemId)) {
            $item = array('itemId' => $itemId, 'trackerId' => $trackerId);
        }
        foreach ($flds['data'] as $i => $f) {
            // collect additional infos
            if (in_array($f['fieldId'], $outf)) {
                $flds['data'][$i]['ins_id'] = $f['type'] == 'e' ? 'ins_cat_' . $f['fieldId'] : ($f['type'] == 'f' ? 'track_' . $f['fieldId'] : 'track[' . $f['fieldId'] . ']');
                if ($f['isHidden'] == 'c' && !empty($itemId) && !isset($item['creator'])) {
                    $item['creator'] = $trklib->get_item_creator($trackerId, $itemId);
                }
                if ($f['type'] == 's' && ($f['name'] == 'Rating' || $f['name'] == tra('Rating')) && $tiki_p_tracker_vote_ratings == 'y' && isset($item)) {
                    $item['my_rate'] = $tikilib->get_user_vote("tracker{$trackerId}.{$itemId}", $user);
                }
                if ($f['type'] == 'r') {
                    $flds['data'][$i]['list'] = array_unique($trklib->get_all_items($f['options_array'][0], $f['options_array'][1], 'o'));
                    if (isset($f['options_array'][3])) {
                        $flds['data'][$i]['displayedList'] = array_unique($trklib->concat_all_items_from_fieldslist($f['options_array'][0], $f['options_array'][3]));
                    }
                } elseif ($f['type'] == 'y') {
                    $flds['data'][$i]['flags'] = $tikilib->get_flags();
                    if ($prefs['language'] != 'en') {
                        foreach ($flags as $flag) {
                            $flagsTranslated[] = $tikilib->take_away_accent(tra($flag));
                        }
                        array_multisort($flagsTranslated, $flds['data'][$i]['flags']);
                    }
                } elseif ($f['type'] == 'u') {
                    if ($tiki_p_admin == 'y' || $f['options_array'][0] != 1 && $f['options_array'][0] != 2) {
                        $flds['data'][$i]['list'] = $userlib->list_all_users();
                    }
                } elseif ($f['type'] == 'g') {
                    if ($tiki_p_admin == 'y' || $f['options_array'][0] != 1 && $f['options_array'][0] != 2) {
                        $flds['data'][$i]['list'] = $userlib->list_all_groups();
                    }
                } elseif ($f['type'] == 'e') {
                    global $categlib;
                    include_once 'lib/categories/categlib.php';
                    $flds['data'][$i]['list'] = $categlib->get_child_categories($f["options_array"][0]);
                } elseif ($f['type'] == 'A') {
                    if (!empty($f['value'])) {
                        $flds['data'][$i]['info'] = $trklib->get_item_attachment($f['value']);
                    }
                } elseif ($f['type'] == 'a') {
                    if ($f['options_array'][0] == 1 && empty($quicktags)) {
                        global $quicktagslib;
                        include_once 'lib/quicktags/quicktagslib.php';
                        $quicktags = $quicktagslib->list_quicktags(0, -1, 'taglabel_desc', '', 'trackers');
                        $smarty->assign_by_ref('quicktags', $quicktags['data']);
                    }
                }
            }
        }
        // Loop on tracker fields and display form
        if (empty($tpl) && empty($wiki)) {
            $back .= '<table class="wikiplugin_tracker">';
        } else {
            $back .= '<div class="wikiplugin_tracker">';
        }
        $backLength0 = strlen($back);
        foreach ($flds['data'] as $f) {
            if ($f['type'] == 'u' and $f['options_array'][0] == '1') {
                $back .= '<input type="hidden" name="authorfieldid" value="' . $f['fieldId'] . '" />';
            }
            if ($f['type'] == 'I' and $f['options_array'][0] == '1') {
                $back .= '<input type="hidden" name="authoripid" value="' . $f['fieldId'] . '" />';
            }
            if ($f['type'] == 'g' and $f['options_array'][0] == '1') {
                $back .= '<input type="hidden" name="authorgroupfieldid" value="' . $f['fieldId'] . '" />';
            }
            if ($f['type'] == 'q') {
                $back .= '<input type="hidden" name="track[' . $f['fieldId'] . ']" />';
            }
            if (in_array($f['fieldId'], $outf)) {
                if (!empty($tpl) || !empty($wiki)) {
                    $smarty->assign_by_ref('field_value', $f);
                    $smarty->assign('f_' . $f['fieldId'], $smarty->fetch('tracker_item_field_input.tpl'));
                } elseif (true) {
                    // comment this block in problem
                    if (in_array($f['fieldId'], $optional)) {
                        $f['name'] = "<i>" . $f['name'] . "</i>";
                    }
                    if ($f['type'] != 'h') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                    } else {
                        $back .= "<tr><td class='heading' colspan='2'>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                    }
                    $smarty->assign_by_ref('field_value', $f);
                    if (isset($item)) {
                        $smarty->assign_by_ref('item', $item);
                    }
                    $back .= $smarty->fetch('tracker_item_field_input.tpl');
                } else {
                    //old
                    // numeric or text field
                    if ($f['type'] == 't' or $f['type'] == 'n' and $f["fieldId"] != $embeddedId or $f['type'] == 'm') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        if ($f['type'] != 'h') {
                            $back .= "</td><td>";
                        }
                        $back .= '<input type="text" name="track[' . $f["fieldId"] . ']" value="' . $f['value'] . '"';
                        if (isset($f['options_array'][1])) {
                            $back .= 'size="' . $f['options_array'][1] . '" maxlength="' . $f['options_array'][1] . '"';
                        } else {
                            $back .= 'size="30"';
                        }
                        $back .= '/>';
                        // item link
                    } elseif ($f['type'] == 'r') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $back .= '<select name="track[' . $f["fieldId"] . ']">';
                        $back .= '<option value=""></option>';
                        foreach ($f['list'] as $key => $item) {
                            $selected = $f['value'] == $item ? 'selected="selected"' : '';
                            $back .= '<option value="' . $item . '" ' . $selected . '>';
                            $back .= isset($f['displayedList'][$key]) ? $f['displayedList'][$key] : $item;
                            $back .= '</option>';
                        }
                        $back .= "</select>";
                        // country
                    } elseif ($f['type'] == 'y') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $back .= '<select name="track[' . $f["fieldId"] . ']">';
                        $back .= '<option value=""></option>';
                        foreach ($f['flags'] as $flag) {
                            $selected = $f['value'] == $flag ? 'selected="selected"' : '';
                            if (!isset($f['options_array'][0]) || $f['options_array'][0] != '1') {
                                $selected .= ' style="background-image:url(\'img/flags/' . $flag . '.gif\');background-repeat:no-repeat;padding-left:25px;padding-bottom:3px;"';
                            }
                            $back .= '<option value="' . $flag . '" ' . $selected . '>' . tra($flag) . '</option>';
                        }
                        $back .= "</select>";
                        // textarea
                    } elseif ($f['type'] == 'a') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        if (isset($f['options_array'][1])) {
                            $back .= '<textarea cols="' . $f['options_array'][1] . '" rows="' . $f['options_array'][2] . '" name="track[' . $f["fieldId"] . ']" wrap="soft">' . $f['value'] . '</textarea>';
                        } else {
                            $back .= '<textarea cols="29" rows="7" name="track[' . $f["fieldId"] . ']" wrap="soft">' . $f['value'] . '</textarea>';
                        }
                        // user selector
                    } elseif (($f['type'] == 'u' or $f['type'] == 'g' or $f['type'] == 'I') and ($f['options_array'][0] == '1' or $f['options_array'][0] == '2')) {
                        $back .= '<tr><td>' . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors) . '</td><td>';
                        $back .= $f['type'] == 'I' ? $_SERVER['REMOTE_ADDR'] : ($f['type'] == 'g' ? $group : $user);
                        // drop down, user selector or group selector
                    } elseif ($f['type'] == 'd' or $f['type'] == 'D' or $f['type'] == 'u' or $f['type'] == 'g' or $f['type'] == 'r' or $f['type'] == 'R') {
                        if ($f['type'] == 'd' or $f['type'] == 'D' or $f['type'] == 'R') {
                            $list = $f['options_array'];
                        } elseif ($f['type'] == 'u') {
                            $list = $f['list'];
                        } elseif ($f['type'] == 'g') {
                            $list = $f['list'];
                        }
                        if ($list) {
                            $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                            if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                                $back .= "&nbsp;<b>*</b>&nbsp;";
                                $onemandatory = true;
                            }
                            $back .= "</td><td>";
                            if ($f['type'] == 'R') {
                                foreach ($list as $item) {
                                    $selected = $f['value'] == $item || empty($f['value']) && !empty($f['defaultvalue']) && $item == $f['defaultvalue'] ? 'checked="checked"' : '';
                                    $back .= '<div class="radio"><input type="radio" name="track[' . $f["fieldId"] . ']" value="' . $item . '" ' . $selected . ' />' . $item . '</div>';
                                }
                            } else {
                                $back .= '<select name="track[' . $f["fieldId"] . ']">';
                                $back .= '<option value=""></option>';
                                $otherValue = $f['value'];
                                foreach ($list as $item) {
                                    if ($f['value'] == $item || empty($f['value']) && !empty($f['defaultvalue']) && $item == $f['defaultvalue']) {
                                        $selected = 'selected="selected"';
                                        $otherValue = '';
                                    } else {
                                        $selected = '';
                                    }
                                    $back .= '<option value="' . $item . '" ' . $selected . '>' . tra($item) . '</option>';
                                }
                                $back .= "</select>";
                            }
                            if ($f['type'] == 'D') {
                                $back .= '<br />' . tra('Other:') . ' <input type="text" name="track_other[' . $f["fieldId"] . ']" value="' . $otherValue . '" />';
                            }
                        } else {
                            $back .= '<input type="hidden" name="track[' . $f["fieldId"] . ']" value="' . $user . '" />';
                        }
                    } elseif ($f['type'] == 'h') {
                        if (strlen($back) != $backLength0) {
                            $back .= '</td></tr>';
                        }
                        $back .= "<tr><td colspan=\"2\" class=\"trackerheader\"><h2>";
                        $n = wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        $back .= $n ? $n : ' ' . '</h2>';
                        if (!empty($f['description'])) {
                            $back .= '<i>' . $f['description'] . '</i>';
                        }
                    } elseif ($f['type'] == 'e') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $i = 0;
                        if (!empty($f['options_array'][2]) && ($f['options_array'][2] == '1' || $f['options_array'][2] == 'y')) {
                            $back .= '<script type="text/javascript"> /* <![CDATA[ */';
                            $back .= "document.write('<div class=\"categSelectAll\"><input type=\"checkbox\" onclick=\"switchCheckboxes(this.form,\\'ins_cat_{$f['fieldId']}[]\\',this.checked)\"/>";
                            $back .= tra('Select All');
                            $back .= "</div>')/* ]]> */</script>";
                        }
                        if (isset($f['options_array'][1]) && ($f['options_array'][1] == 'd' || $f['options_array'][1] == 'm')) {
                            $back .= '<select name="ins_cat_' . $f['fieldId'] . '[]"';
                            if ($f['options_array'][1] == 'm') {
                                $back .= ' multiple="multiple"';
                            }
                            $back .= '>';
                            if ($f['options_array'][1] == 'd') {
                                $back .= '<option value=""></option>"';
                            }
                            foreach ($f['list'] as $cat) {
                                $checked = $f['value'] == $cat['categId'] ? 'selected="selected"' : '';
                                $back .= '<option value="' . $cat['categId'] . '" ' . $checked . '>' . $cat['name'] . '</option>';
                            }
                            $back .= '</select>';
                        } else {
                            $t = isset($f["options_array"][1]) && $f["options_array"][1] == 'radio' ? 'radio' : 'checkbox';
                            foreach ($f['list'] as $cat) {
                                $checked = $f['value'] == $cat['categId'] ? 'checked="checked"' : '';
                                $back .= '<input type="' . $t . '" name="ins_cat_' . $f['fieldId'] . '[]" value="' . $cat["categId"] . '" ' . $checked . '>' . $cat['name'] . '</input><br />';
                            }
                        }
                    } elseif ($f['type'] == 'c') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $checked = $f['value'] == 'y' ? 'checked="checked"' : '';
                        $back .= '</td><td><input type="checkbox" name="track[' . $f["fieldId"] . ']" value="y" ' . $checked . '/>';
                    } elseif ($f['type'] == 'i') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        $back .= '<input type="file" name="track[' . $f["fieldId"] . ']" />';
                    } elseif ($f['type'] == 'f') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        include_once 'lib/smarty_tiki/function.html_select_date.php';
                        include_once 'lib/smarty_tiki/function.html_select_time.php';
                        $params['prefix'] = 'track_' . $f['fieldId'];
                        if (isset($f['options_array'][1])) {
                            $params['start_year'] = $f['options_array'][1];
                        }
                        if (isset($f['options_array'][2])) {
                            $params['end_year'] = $f['options_array'][2];
                        }
                        if (isset($f['value'])) {
                            $params['time'] = $f['value'];
                        }
                        $back .= smarty_function_html_select_date($params, $smarty);
                        if (empty($f['options_array'][0]) || $f['options_array'][0] != 'd') {
                            $params['display_seconds'] = false;
                            $back .= smarty_function_html_select_time($params, $smarty);
                        }
                    } elseif ($f['type'] == 'j') {
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<b>*</b>&nbsp;";
                            $onemandatory = true;
                        }
                        $back .= "</td><td>";
                        include_once 'lib/smarty_tiki/function.jscalendar.php';
                        $params['id'] = 'track[' . $f['fieldId'] . ']';
                        $params['fieldname'] = 'track[' . $f['fieldId'] . ']';
                        if (empty($f['options_array'][0]) || $f['options_array'][0] != 'd') {
                            $params['showtime'] = 'y';
                        } else {
                            $params['showtime'] = 'n';
                        }
                        if (isset($f['value'])) {
                            $params['date'] = $f['value'];
                        }
                        $back .= smarty_function_jscalendar_body($params, $smarty);
                    } elseif ($f['type'] == 'C' && isset($_REQUEST['tr_preview'])) {
                        // computed
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors) . "</td><td>";
                        $calc = preg_replace('/#([0-9]+)/', '$assocNumerics[\\1]', $f['options_array'][0]);
                        eval('$computed = ' . $calc . ';');
                        $back .= $computed;
                    } elseif ($f['type'] == 'l' && isset($_REQUEST['tr_preview'])) {
                        // itemlist
                        $back .= "<tr><td>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors) . "</td><td>";
                        $items = $trklib->get_items_list($f['options_array'][0], $f['options_array'][1], $assocValues[$f['options_array'][2]]);
                        $i = 0;
                        foreach ($items as $id) {
                            $value = $trklib->get_item_value($f['options_array'][0], $id, $f['options_array'][3]);
                            $assocValues[$f['fieldId']] = $value;
                            // can be used in another computed field
                            $assocNumerics[$f['fieldId']] = preg_replace('/[^0-9\\.\\+]/', '', $value);
                            if ($i++ > 0) {
                                $back .= ',';
                            }
                            $back .= $value;
                        }
                    } else {
                    }
                }
                //old
                if (!empty($f['description']) && $f['type'] != 'h' && $f['type'] != 'S') {
                    $back .= '<br /><i>' . $f['description'] . '</i>';
                }
                if (empty($tpl) && empty($wiki)) {
                    $back .= "</td></tr>";
                }
            }
        }
        if (!empty($tpl)) {
            $smarty->security = true;
            $back .= $smarty->fetch($tpl);
        } elseif (!empty($wiki)) {
            $smarty->security = true;
            $back .= $smarty->fetch('wiki:' . $wiki);
        }
        if ($prefs['feature_antibot'] == 'y' && empty($user)) {
            $back .= $smarty->fetch('antibot.tpl');
        }
        if (empty($tpl) && empty($wiki)) {
            $back .= "<tr><td></td><td>";
        }
        if (!empty($preview)) {
            $back .= "<input type='submit' name='tr_preview' value='" . tra($preview) . "' />";
        }
        $back .= "<input type='submit' name='action' value='" . tra($action) . "' />";
        if ($showmandatory == 'y' and $onemandatory) {
            $back .= "<br /><i>" . tra("Fields marked with a * are mandatory.") . "</i>";
        }
        if (empty($tpl) && empty($wiki)) {
            $back .= "</td></tr>";
            $back .= "</table>";
        } else {
            $back .= '</div>';
        }
        $back .= '</form>';
        if (!empty($page)) {
            $back .= '~/np~';
        }
        return $back;
    } else {
        if (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
            $smarty->assign('wikiplugin_tracker', $trackerId);
        }
        //used in vote plugin
        $id = ' id="wikiplugin_tracker' . $trackerId . '"';
        if ($showtitle == 'y') {
            $back .= '<div class="titlebar"' . $id . '>' . $tracker["name"] . '</div>';
            $id = '';
        }
        if ($showdesc == 'y') {
            $back .= '<div class="wikitext"' . $id . '>' . $tracker["description"] . '</div><br />';
            $id = '';
        }
        $back .= "<div{$id}>" . $data . '</div>';
        return $back;
    }
}
Example #4
0
function wikiplugin_tracker($data, $params)
{
    global $tikilib, $userlib, $dbTiki, $user, $group, $page, $tiki_p_admin_trackers, $smarty, $prefs, $trklib, $tiki_p_view;
    static $iTRACKER = 0;
    ++$iTRACKER;
    include_once 'lib/trackers/trackerlib.php';
    //var_dump($_REQUEST);
    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);
        $usertracker = true;
    } elseif (!empty($trackerId) && !empty($view) && $view == 'page' && !empty($_REQUEST['page']) && ($f = $trklib->get_field_id_from_type($trackerId, 'k', '1%'))) {
        // 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'])) {
        $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($embedded)) {
        $embedded = "n";
    }
    if (!isset($showtitle)) {
        $showtitle = "n";
    }
    if (!isset($showdesc)) {
        $showdesc = "n";
    }
    if (!isset($sort)) {
        $sort = 'n';
    }
    if (!isset($action)) {
        $action = 'Save';
    }
    if (isset($preview)) {
        if (empty($preview)) {
            $preview = 'Preview';
        }
    } else {
        unset($_REQUEST['tr_preview']);
    }
    if (!isset($showmandatory)) {
        $showmandatory = 'y';
    }
    $smarty->assign('showmandatory', $showmandatory);
    if (!empty($wiki)) {
        $wiki = trim($wiki);
    }
    if (isset($values)) {
        if (!is_array($values)) {
            $values = $tikilib->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']);
        }
    }
    if (empty($_SERVER['SCRIPT_NAME']) || !strstr($_SERVER['SCRIPT_NAME'], 'tiki-register.php')) {
        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 {
            $perms = $tikilib->get_perm_object($trackerId, 'tracker', $tracker, false);
            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 (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;
        }
        $flds = $trklib->list_tracker_fields($trackerId, 0, -1, "position_asc", "");
        if (empty($fields) && (!empty($wiki) || !empty($tpl))) {
            if (!empty($wiki)) {
                $outf = $trklib->get_pretty_fieldIds($wiki, 'wiki');
            } else {
                $outf = $trklib->get_pretty_fieldIds($tpl, 'tpl');
            }
            $ret = array();
            foreach ($flds['data'] as $field) {
                if ($field['type'] == 'q' || $field['type'] == 'k' || $field['type'] == 'u' || $field['type'] == 'g' || in_array($field['fieldId'], $outf)) {
                    $ret[] = $field;
                }
            }
            $flds['cant'] = sizeof($ret);
            $flds['data'] = $ret;
        }
        $bad = array();
        $embeddedId = false;
        $onemandatory = false;
        $full_fields = array();
        $mainfield = '';
        if ($thisIsThePlugin) {
            /* ------------------------------------- Recup all values from REQUEST -------------- */
            $cpt = 0;
            if (isset($fields)) {
                $fields_plugin = split(':', $fields);
            }
            foreach ($flds['data'] as $fl) {
                // store value to display it later if form
                // isn't fully filled.
                if ($flds['data'][$cpt]['type'] == 's' && $flds['data'][$cpt]['name'] == 'Rating') {
                    if (isset($_REQUEST['track'][$fl['fieldId']])) {
                        $newItemRate = $_REQUEST['track'][$fl['fieldId']];
                        $newItemRateField = $fl['fieldId'];
                    } else {
                        $newItemRate = NULL;
                    }
                } elseif (($flds['data'][$cpt]['type'] == 'u' || $flds['data'][$cpt]['type'] == 'g' || $flds['data'][$cpt]['type'] == 'I' || $flds['data'][$cpt]['type'] == 'k') && ($flds['data'][$cpt]['options_array'][0] == '1' || $flds['data'][$cpt]['options_array'][0] == '2') && empty($_REQUEST['track'][$fl['fieldId']])) {
                    if (empty($itemId) && ($flds['data'][$cpt]['options_array'][0] == '1' || $flds['data'][$cpt]['options_array'][0] == '2')) {
                        if ($flds['data'][$cpt]['type'] == 'u') {
                            $_REQUEST['track'][$fl['fieldId']] = empty($user) ? empty($_REQUEST['name']) ? '' : $_REQUEST['name'] : $user;
                        } elseif ($flds['data'][$cpt]['type'] == 'g') {
                            $_REQUEST['track'][$fl['fieldId']] = $group;
                        } elseif ($flds['data'][$cpt]['type'] == 'I') {
                            $_REQUEST['track'][$fl['fieldId']] = $tikilib->get_ip_address();
                        } elseif ($flds['data'][$cpt]['type'] == 'k') {
                            $_REQUEST['track'][$fl['fieldId']] = isset($_REQUEST['page']) ? $_REQUEST['page'] : '';
                        }
                    } elseif (!empty($itemId) && $flds['data'][$cpt]['options_array'][0] == '2') {
                        if ($flds['data'][$cpt]['type'] == 'u') {
                            $_REQUEST['track'][$fl['fieldId']] = $user;
                        } elseif ($flds['data'][$cpt]['type'] == 'g') {
                            $_REQUEST['track'][$fl['fieldId']] = $group;
                        } elseif ($flds['data'][$cpt]['type'] == 'I') {
                            $_REQUEST['track'][$fl['fieldId']] = $tikilib->get_ip_address();
                        }
                    }
                } elseif (($flds['data'][$cpt]['type'] == 'C' || $flds['data'][$cpt]['type'] == 'e') && empty($_REQUEST['track'][$fl['fieldId']])) {
                    $_REQUEST['track'][$fl['fieldId']] = '';
                } elseif ($flds['data'][$cpt]['type'] == 'f') {
                    $ins_id = 'track_' . $fl['fieldId'];
                    if (isset($_REQUEST[$ins_id . 'Day'])) {
                        if (empty($_REQUEST['$ins_id' . 'Hour'])) {
                            $_REQUEST['$ins_id' . 'Hour'] = 0;
                        }
                        if (empty($_REQUEST['$ins_id' . 'Minute'])) {
                            $_REQUEST['$ins_id' . 'Minute'] = 0;
                        }
                        $_REQUEST['track'][$fl['fieldId']] = $tikilib->make_time($_REQUEST["{$ins_id}" . "Hour"], $_REQUEST["{$ins_id}" . "Minute"], 0, $_REQUEST["{$ins_id}" . "Month"], $_REQUEST["{$ins_id}" . "Day"], $_REQUEST["{$ins_id}" . "Year"]);
                    } else {
                        $_REQUEST['track'][$fl['fieldId']] = $tikilib->now;
                    }
                } elseif ($f['type'] == 'N' && !empty($itemId)) {
                    if (empty($itemUser)) {
                        $itemUser = $this->get_item_creator($trackerId, $itemId);
                    }
                    $flds['data'][$i]['value'] = $trklib->in_group_value($flds['data'][$i], $itemUser);
                }
                if (isset($_REQUEST['ins_cat_' . $fl['fieldId']])) {
                    // to remember if error
                    $_REQUEST['track'][$fl['fieldId']] = $_REQUEST['ins_cat_' . $fl['fieldId']];
                }
                if (isset($_REQUEST['track'][$fl['fieldId']])) {
                    $flds['data'][$cpt]['value'] = $_REQUEST['track'][$fl['fieldId']];
                } else {
                    $flds['data'][$cpt]['value'] = '';
                    if ($fl['type'] == 'c') {
                        $_REQUEST['track'][$fl['fieldId']] = 'n';
                    } elseif ($fl['type'] == 'R' && $fl['isMandatory'] == 'y') {
                        // if none radio is selected, there will be no value and no error if mandatory
                        $_REQUEST['track'][$fl['fieldId']] = '';
                    }
                }
                if (!empty($_REQUEST['other_track'][$fl['fieldId']])) {
                    $flds['data'][$cpt]['value'] = $_REQUEST['other_track'][$fl['fieldId']];
                }
                if ($flds['data'][$cpt]['isMultilingual'] == 'y') {
                    foreach ($prefs['available_languages'] as $num => $tmplang) {
                        if (isset($_REQUEST['track'][$fl['fieldId']][$tmplang])) {
                            $fl['lingualvalue'][$num]['value'] = $_REQUEST['track'][$fl['fieldId']][$tmplang];
                            $fl['lingualvalue'][$num]['lang'] = $tmplang;
                        }
                    }
                }
                $full_fields[$fl['fieldId']] = $fl;
                if ($embedded == 'y' and $fl['name'] == 'page') {
                    $embeddedId = $fl['fieldId'];
                }
                if ($fl['isMain'] == 'y') {
                    $mainfield = $flds['data'][$cpt]['value'];
                }
                $cpt++;
            }
            /*foreach */
            if (isset($_REQUEST['track'])) {
                foreach ($_REQUEST['track'] as $fld => $val) {
                    //$ins_fields["data"][] = array('fieldId' => $fld, 'value' => $val, 'type' => 1);
                    if (!empty($_REQUEST['other_track'][$fld])) {
                        $val = $_REQUEST['other_track'][$fld];
                    }
                    $ins_fields["data"][] = array_merge(array('value' => $val), $full_fields[$fld]);
                }
            }
            if (isset($_FILES['track'])) {
                // image or attachment fields
                foreach ($_FILES['track'] as $label => $w) {
                    foreach ($w as $fld => $val) {
                        if ($label == 'tmp_name' && is_uploaded_file($val)) {
                            $fp = fopen($val, 'rb');
                            $data = '';
                            while (!feof($fp)) {
                                $data .= fread($fp, 8192 * 16);
                            }
                            fclose($fp);
                            $files[$fld]['old_value'] = $files[$fld]['value'];
                            $files[$fld]['value'] = $data;
                        } else {
                            $files[$fld]['file_' . $label] = $val;
                        }
                    }
                }
                foreach ($files as $fld => $file) {
                    $ins_fields['data'][] = array_merge($file, $full_fields[$fld]);
                }
            }
            if ($embedded == 'y' && isset($_REQUEST['page'])) {
                $ins_fields["data"][] = array('fieldId' => $embeddedId, 'value' => $_REQUEST['page']);
            }
            $ins_categs = array();
            $categorized_fields = array();
            while (list($postVar, $postVal) = each($_REQUEST)) {
                if (preg_match("/^ins_cat_([0-9]+)/", $postVar, $m)) {
                    foreach ($postVal as $v) {
                        $ins_categs[] = $v;
                    }
                    $categorized_fields[] = $m[1];
                }
            }
            /* ------------------------------------- End recup all values from REQUEST -------------- */
            /* ------------------------------------- Check field values for each type and presence of mandatory ones ------------------- */
            $field_errors = $trklib->check_field_values($ins_fields, $categorized_fields);
            if (empty($user) && $prefs['feature_antibot'] == 'y' && !$_SESSION['in_tracker']) {
                // in_tracker session var checking is for tiki-register.php
                if (!isset($_SESSION['random_number']) || $_SESSION['random_number'] != $_REQUEST['antibotcode']) {
                    $field_errors['err_antibot'] = 'y';
                }
            }
            if (count($field_errors['err_mandatory']) == 0 && count($field_errors['err_value']) == 0 && empty($field_errors['err_antibot']) && !isset($_REQUEST['tr_preview'])) {
                /* ------------------------------------- save the item ---------------------------------- */
                if (!isset($itemId) && $tracker['oneUserItem'] == 'y') {
                    $itemId = $trklib->get_user_item($trackerId, $tracker);
                }
                if (isset($_REQUEST['status'])) {
                    $status = $_REQUEST['status'];
                } elseif (isset($newstatus) && ($newstatus == 'o' || $newstatus == 'c' || $newstatus == 'p')) {
                    $status = $newstatus;
                } elseif (empty($itemId) && isset($tracker['newItemStatus'])) {
                    $status = $tracker['newItemStatus'];
                } else {
                    $status = '';
                }
                $rid = $trklib->replace_item($trackerId, $itemId, $ins_fields, $status, $ins_categs);
                $trklib->categorized_item($trackerId, $rid, $mainfield, $ins_categs);
                if (isset($newItemRate)) {
                    $trklib->replace_rating($trackerId, $rid, $newItemRateField, $user, $newItemRate);
                }
                if (!empty($email)) {
                    $emailOptions = split("\\|", $email);
                    if (is_numeric($emailOptions[0])) {
                        $emailOptions[0] = $trklib->get_item_value($trackerId, $rid, $emailOptions[0]);
                    }
                    if (empty($emailOptions[0])) {
                        // from
                        $emailOptions[0] = $prefs['sender_email'];
                    }
                    if (empty($emailOptions[1])) {
                        // to
                        $emailOptions[1][0] = $prefs['sender_email'];
                    } else {
                        $emailOptions[1] = split(',', $emailOptions[1]);
                        foreach ($emailOptions[1] as $key => $email) {
                            if (is_numeric($email)) {
                                $emailOptions[1][$key] = $trklib->get_item_value($trackerId, $rid, $email);
                            }
                        }
                    }
                    if (!empty($emailOptions[2])) {
                        //tpl
                        if (!preg_match('/\\.tpl$/', $emailOptions[2])) {
                            $emailOptions[2] .= '.tpl';
                        }
                        $tplSubject = str_replace('.tpl', '_subject.tpl', $emailOptions[2]);
                    } else {
                        $emailOptions[2] = 'tracker_changed_notification.tpl';
                    }
                    if (empty($tplSubject)) {
                        $tplSubject = 'tracker_changed_notification_subject.tpl';
                    }
                    include_once 'lib/webmail/tikimaillib.php';
                    $mail = new TikiMail();
                    @($mail_data = $smarty->fetch('mail/' . $tplSubject));
                    if (empty($mail_data)) {
                        $mail_data = tra('Tracker was modified at ') . $_SERVER["SERVER_NAME"];
                    }
                    $mail->setSubject($mail_data);
                    $mail_data = $smarty->fetch('mail/' . $emailOptions[2]);
                    $mail->setText($mail_data);
                    $mail->setHeader('From', $emailOptions[0]);
                    $mail->send($emailOptions[1]);
                }
                if (empty($url)) {
                    if (!empty($page)) {
                        $url = "tiki-index.php?page=" . urlencode($page) . "&ok=y&iTRACKER={$iTRACKER}";
                        $url .= "#wikiplugin_tracker{$iTRACKER}";
                        header("Location: {$url}");
                        die;
                    } else {
                        return '';
                    }
                } else {
                    if (strstr($url, 'itemId')) {
                        $url = str_replace('itemId', 'itemId=' . $rid, $url);
                    }
                    header("Location: {$url}");
                    die;
                }
                /* ------------------------------------- end save the item ---------------------------------- */
            } elseif (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
                $smarty->assign('wikiplugin_tracker', $trackerId);
                //used in vote plugin
            }
        } else {
            if (empty($itemId) && !empty($values) || (!empty($_REQUEST['values']) and empty($_REQUEST['prefills']))) {
                // assign default values for each filedId specify
                if (empty($values)) {
                    // url with values[]=x&values[] witouth the list of fields
                    $values = $_REQUEST['values'];
                }
                if (!is_array($values)) {
                    $values = array($values);
                }
                if (isset($fields)) {
                    $fl = split(':', $fields);
                    for ($j = 0, $count_fl = count($fl); $j < $count_fl; $j++) {
                        for ($i = 0, $count_flds = count($flds['data']); $i < $count_flds; $i++) {
                            if ($flds['data'][$i]['fieldId'] == $fl[$j]) {
                                $flds['data'][$i]['value'] = $values[$j];
                            }
                        }
                    }
                } else {
                    // values contains all the fields value in the default order
                    $i = 0;
                    foreach ($values as $value) {
                        $flds['data'][$i++]['value'] = $value;
                    }
                }
            } elseif (!empty($itemId)) {
                if (isset($fields)) {
                    $fl = split(':', $fields);
                    $filter = '';
                    foreach ($flds['data'] as $f) {
                        if (in_array($f['fieldId'], $fl)) {
                            $filter[] = $f;
                        }
                    }
                } else {
                    $filter =& $flds['data'];
                }
                if (!empty($filter)) {
                    foreach ($filter as $f) {
                        $filter2[$f['fieldId']] = $f;
                    }
                    $flds['data'] = $trklib->get_item_fields($trackerId, $itemId, $filter2, $itemUser);
                }
            } else {
                if (isset($_REQUEST['values']) && isset($_REQUEST['prefills'])) {
                    //url:prefields=1:2&values[]=x&values[]=y
                    if (!is_array($_REQUEST['values'])) {
                        $_REQUEST['values'] = array($_REQUEST['values']);
                    }
                    $fl = split(':', $_REQUEST['prefills']);
                } else {
                    unset($fl);
                }
                for ($i = 0, $count_flds2 = count($flds['data']); $i < $count_flds2; $i++) {
                    if (isset($fl) && ($j = array_search($flds['data'][$i]['fieldId'], $fl)) !== false) {
                        $flds['data'][$i]['value'] = $_REQUEST['values'][$j];
                    } else {
                        $flds['data'][$i]['value'] = '';
                        // initialize fields with blank values
                    }
                }
            }
        }
        $optional = array();
        $outf = array();
        if (isset($fields) && !empty($fields)) {
            $fl = split(":", $fields);
            if ($sort == 'y') {
                $flds = $trklib->sort_fields($flds, $fl);
            }
            foreach ($fl as $l) {
                if (substr($l, 0, 1) == '-') {
                    $l = substr($l, 1);
                    $optional[] = $l;
                }
                $ok = false;
                foreach ($flds['data'] as $f) {
                    if ($f['fieldId'] == $l) {
                        $ok = true;
                        break;
                    }
                }
                if (!$ok) {
                    $back .= tra('Incorrect fieldId:') . ' ' . $l;
                }
                $outf[] = $l;
            }
        } elseif (empty($fields) && !empty($wiki)) {
            $wiki_info = $tikilib->get_page_info($wiki);
            preg_match_all('/\\$f_([0-9]+)/', $wiki_info['data'], $matches);
            $outf = $matches[1];
        } elseif (empty($fields) && !empty($tpl)) {
            $f = $smarty->get_filename($tpl);
            if (!empty($f)) {
                $f = file_get_contents($f);
                preg_match_all('/\\$f_([0-9]+)/', $f, $matches);
                $outf = $matches[1];
            }
        } elseif (empty($fields) && empty($wiki)) {
            foreach ($flds['data'] as $f) {
                if ($f['isMandatory'] == 'y') {
                    $optional[] = $f['fieldId'];
                }
                $outf[] = $f['fieldId'];
            }
        }
        // Display warnings when needed
        if (count($field_errors['err_mandatory']) > 0) {
            $back .= '<div class="simplebox highlight"><img src="pics/icons/exclamation.png" alt=" ' . tra('Error') . '" style="vertical-align:middle" /> ';
            $back .= tra('Following mandatory fields are missing') . '&nbsp;:<br/>';
            $coma_cpt = count($field_errors['err_mandatory']);
            foreach ($field_errors['err_mandatory'] as $f) {
                $back .= $f['name'];
                $back .= --$coma_cpt > 0 ? ',&nbsp;' : '';
            }
            $back .= '</div><br />';
            $_REQUEST['error'] = 'y';
        }
        if (count($field_errors['err_value']) > 0) {
            $back .= '<div class="simplebox highlight">';
            $b = '';
            foreach ($field_errors['err_value'] as $f) {
                if (!empty($f['errorMsg'])) {
                    $back .= tra($f['errorMsg']) . '<br>';
                } else {
                    if (!empty($b)) {
                        $b .= ' : ';
                    }
                    $b .= $f['name'];
                }
            }
            if (!empty($b)) {
                $back .= tra('Following fields are incorrect') . '&nbsp;:<br/>' . $b;
            }
            $back .= '</div><br />';
            $_REQUEST['error'] = 'y';
        }
        if (isset($field_errors['err_antibot'])) {
            $back .= '<div class="simplebox highlight"><img src="pics/icons/exclamation.png" alt=" ' . tra('Error') . '" style="vertical-align:middle" /> ';
            $back .= tra('You have mistyped the anti-bot verification code; please try again.');
            $back .= '</div><br />';
            $_REQUEST['error'] = 'y';
        }
        if (count($field_errors['err_mandatory']) > 0 || count($field_errors['err_value']) > 0 || isset($field_errors['err_antibot'])) {
            $smarty->assign('input_err', 'y');
        }
        if (!empty($page)) {
            $back .= '~np~';
        }
        $smarty->assign_by_ref('tiki_p_admin_trackers', $perms['tiki_p_admin_trackers']);
        $back .= '<form enctype="multipart/form-data" method="post"' . (isset($target) ? ' target="' . $target . '"' : '') . ' action="' . $_SERVER['REQUEST_URI'] . '"><input type="hidden" name="trackit" value="' . $trackerId . '" />';
        $back .= '<input type="hidden" name="iTRACKER" value="' . $iTRACKER . '" />';
        $back .= '<input type="hidden" name="refresh" value="1" />';
        if (isset($_REQUEST['page'])) {
            $back .= '<input type="hidden" name="page" value="' . $_REQUEST["page"] . '" />';
        }
        // for registration
        if (isset($_REQUEST['name'])) {
            $back .= '<input type="hidden" name="name" value="' . $_REQUEST["name"] . '" />';
        }
        if (isset($_REQUEST['pass'])) {
            $back .= '<input type="hidden" name="pass" value="' . $_REQUEST["pass"] . '" />';
            $back .= '<input type="hidden" name="passAgain" value="' . $_REQUEST["pass"] . '" />';
        }
        if (isset($_REQUEST['email'])) {
            $back .= '<input type="hidden" name="email" value="' . $_REQUEST["email"] . '" />';
        }
        if (isset($_REQUEST['regcode'])) {
            $back .= '<input type="hidden" name="regcode" value="' . $_REQUEST["regcode"] . '" />';
        }
        if (isset($_REQUEST['chosenGroup'])) {
            // for registration
            $back .= '<input type="hidden" name="chosenGroup" value="' . $_REQUEST["chosenGroup"] . '" />';
        }
        if (isset($_REQUEST['register'])) {
            $back .= '<input type="hidden" name="register" value="' . $_REQUEST["register"] . '" />';
        }
        if ($showtitle == 'y') {
            $back .= '<div class="titlebar">' . $tracker["name"] . '</div>';
        }
        if ($showdesc == 'y' && $tracker['description']) {
            if ($tracker['descriptionIsParsed'] == 'y') {
                $back .= '<div class="wikitext">' . $tikilib->parse_data($tracker['description']) . '</div><br />';
            } else {
                $back .= '<div class="wikitext">' . $tracker["description"] . '</div><br />';
            }
        }
        if (isset($_REQUEST['tr_preview'])) {
            // use for the computed and join fields
            $assocValues = array();
            $assocNumerics = array();
            foreach ($flds['data'] as $f) {
                if (empty($f['value']) && ($f['type'] == 'u' || $f['type'] == 'g' || $f['type'] == 'I') && ($f['options_array'][0] == '1' || $f['options_array'][0] == '2')) {
                    //need to fill the selector fields for the join
                    $f['value'] = $f['type'] == 'I' ? $tikilib->get_ip_address() : ($f['type'] == 'g' ? $group : $user);
                }
                $assocValues[$f['fieldId']] = $f['value'];
                $assocNumerics[$f['fieldId']] = preg_replace('/[^0-9\\.\\+]/', '', $f['value']);
                // get rid off the $ and such unit
            }
        }
        if (!empty($itemId)) {
            $item = array('itemId' => $itemId, 'trackerId' => $trackerId);
        }
        foreach ($flds['data'] as $i => $f) {
            // collect additional infos
            if (in_array($f['fieldId'], $outf)) {
                $flds['data'][$i]['ins_id'] = $f['type'] == 'e' ? 'ins_cat_' . $f['fieldId'] : ($f['type'] == 'f' ? 'track_' . $f['fieldId'] : 'track[' . $f['fieldId'] . ']');
                if ($f['isHidden'] == 'c' && !empty($itemId) && !isset($item['creator'])) {
                    $item['creator'] = $trklib->get_item_creator($trackerId, $itemId);
                }
                if ($f['type'] == 's' && ($f['name'] == 'Rating' || $f['name'] == tra('Rating')) && $perms['tiki_p_tracker_vote_ratings'] == 'y' && isset($item)) {
                    $item['my_rate'] = $tikilib->get_user_vote("tracker{$trackerId}.{$itemId}", $user);
                }
                if ($f['isMultilingual'] == 'y') {
                    $multi_languages = $prefs['available_languages'];
                    foreach ($multi_languages as $num => $tmplang) {
                        $flds['data'][$i]['lingualvalue'][$num]['lang'] = $tmplang;
                    }
                }
                if ($f['type'] == 'r') {
                    $flds['data'][$i]['list'] = array_unique($trklib->get_all_items($f['options_array'][0], $f['options_array'][1], 'poc'));
                    if (isset($f['options_array'][3])) {
                        $flds['data'][$i]['displayedList'] = array_unique($trklib->concat_all_items_from_fieldslist($f['options_array'][0], $f['options_array'][3]));
                    }
                } elseif ($f['type'] == 'y') {
                    $flds['data'][$i]['flags'] = $tikilib->get_flags();
                    if ($prefs['language'] != 'en') {
                        foreach ($flags as $flag) {
                            $flagsTranslated[] = $tikilib->take_away_accent(tra($flag));
                        }
                        array_multisort($flagsTranslated, $flds['data'][$i]['flags']);
                    }
                } elseif ($f['type'] == 'u') {
                    if ($perms['tiki_p_admin_trackers'] == 'y' || $f['options_array'][0] != 1 && $f['options_array'][0] != 2) {
                        $flds['data'][$i]['list'] = $userlib->list_all_users();
                    } elseif ($f['options_array'][0] == 1) {
                        $flds['data'][$i]['value'] = $user;
                    }
                } elseif ($f['type'] == 'g') {
                    if ($perms['tiki_p_admin_trackers'] == 'y' || $f['options_array'][0] != 1 && $f['options_array'][0] != 2) {
                        $flds['data'][$i]['list'] = $userlib->list_all_groups();
                    } elseif ($f['options_array'][0] == 1) {
                        global $group;
                        $flds['data'][$i]['value'] = $group;
                    }
                } elseif ($f['type'] == 'k') {
                    if ($f['options_array'][0] == 1) {
                        if (isset($page)) {
                            $flds['data'][$i]['value'] = $page;
                        }
                    }
                } elseif ($f['type'] == 'e') {
                    global $categlib;
                    include_once 'lib/categories/categlib.php';
                    $flds['data'][$i]['list'] = $categlib->get_viewable_child_categories($f["options_array"][0]);
                } elseif ($f['type'] == 'A') {
                    if (!empty($f['value'])) {
                        $flds['data'][$i]['info'] = $trklib->get_item_attachment($f['value']);
                    }
                } elseif ($f['type'] == 'a') {
                    if ($f['options_array'][0] == 1 && empty($toolbars)) {
                        // all in the smarty object now
                    }
                } elseif ($f['type'] == 'l' && isset($itemId)) {
                    $opts[1] = split(':', $f['options_array'][1]);
                    $finalFields = explode('|', $f['options_array'][3]);
                    $flds['data'][$i]['value'] = $trklib->get_join_values($itemId, array_merge(array($f['options_array'][2]), array($f['options_array'][1]), array($finalFields[0])), $f['options_array'][0], $finalFields);
                } elseif ($f['type'] == 'w') {
                    $refFieldId = $f['options_array'][2];
                    foreach ($flds['data'] as $i => $ff) {
                        if ($ff['fieldId'] == $refFieldId) {
                            $refFieldId = $i;
                        }
                    }
                    if (!isset($flds['data'][$refFieldId]['http_request'])) {
                        $flds['data'][$refFieldId]['http_request'] = array('', '', '', '', '', '', '', '', '');
                    }
                    for ($i = 0; $i < 5; $i++) {
                        $flds['data'][$refFieldId]['http_request'][$i] .= ($flds['data'][$refFieldId]['http_request'][$i] ? "," : "") . isset($f['options_array'][$i]) ? $f['options_array'][$i] : '';
                    }
                    $flds['data'][$refFieldId]['http_request'][5] .= ($flds['data'][$refFieldId]['http_request'][5] ? "," : "") . $f['fieldId'];
                    $flds['data'][$refFieldId]['http_request'][6] .= ($flds['data'][$refFieldId]['http_request'][6] ? "," : "") . $f['isMandatory'];
                    $flds['data'][$refFieldId]['http_request'][7] .= $flds['data'][$refFieldId]['value'];
                    $flds['data'][$refFieldId]['http_request'][8] .= ($flds['data'][$refFieldId]['http_request'][8] ? "," : "") . $f['value'];
                }
            }
        }
        // Loop on tracker fields and display form
        if (empty($tpl) && empty($wiki)) {
            $back .= '<table class="wikiplugin_tracker">';
        } else {
            $back .= '<div class="wikiplugin_tracker">';
        }
        $backLength0 = strlen($back);
        foreach ($flds['data'] as $f) {
            if ($f['type'] == 'u' and $f['options_array'][0] == '1') {
                $back .= '<input type="hidden" name="authorfieldid" value="' . $f['fieldId'] . '" />';
            }
            if ($f['type'] == 'I' and $f['options_array'][0] == '1') {
                $back .= '<input type="hidden" name="authoripid" value="' . $f['fieldId'] . '" />';
            }
            if ($f['type'] == 'g' and $f['options_array'][0] == '1') {
                $back .= '<input type="hidden" name="authorgroupfieldid" value="' . $f['fieldId'] . '" />';
            }
            if ($f['type'] == 'q') {
                $back .= '<input type="hidden" name="track[' . $f['fieldId'] . ']" />';
            }
            if (in_array($f['fieldId'], $outf)) {
                if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                    $onemandatory = true;
                }
                if (!empty($tpl) || !empty($wiki)) {
                    $smarty->assign_by_ref('field_value', $f);
                    $smarty->assign('showmandatory', $showmandatory);
                    if (isset($item)) {
                        $smarty->assign_by_ref('item', $item);
                    }
                    $smarty->assign('f_' . $f['fieldId'], $smarty->fetch('tracker_item_field_input.tpl'));
                } else {
                    if (in_array($f['fieldId'], $optional)) {
                        $f['name'] = "<i>" . $f['name'] . "</i>";
                    }
                    if ($f['type'] != 'h') {
                        $back .= "<tr><td";
                        if (!empty($colwidth)) {
                            $back .= " width='" . $colwidth . "'";
                        }
                        $back .= ">" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                        if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
                            $back .= "&nbsp;<strong class='mandatory_star'>*</strong>&nbsp;";
                        }
                        $back .= "</td><td>";
                    } else {
                        $back .= "<tr><th colspan='2'>" . wikiplugin_tracker_name($f['fieldId'], $f['name'], $field_errors);
                    }
                    $smarty->assign_by_ref('field_value', $f);
                    if (isset($item)) {
                        $smarty->assign_by_ref('item', $item);
                    }
                    $back .= $smarty->fetch('tracker_item_field_input.tpl');
                }
                if (!empty($f['description']) && $f['type'] != 'h' && $f['type'] != 'S') {
                    $back .= '<br />';
                    if ($f['descriptionIsParsed'] == 'y') {
                        $back .= $tikilib->parse_data($f['description']);
                    } else {
                        $back .= '<i>' . $f['description'] . '</i>';
                    }
                }
                if (empty($tpl) && empty($wiki)) {
                    if ($f['type'] != 'h') {
                        $back .= "</td></tr>";
                    } else {
                        $back .= "</th></tr>";
                    }
                }
                if (!empty($f['http_request']) && !empty($itemId)) {
                    $js .= 'selectValues("trackerIdList=' . $f['http_request'][0] . '&fieldlist=' . $f['http_request'][3] . '&filterfield=' . $f['http_request'][1] . '&status=' . $f['http_request'][4] . '&mandatory=' . $f['http_request'][6] . '&filtervalue=' . $f['http_request'][7] . '&selected=' . $f['http_request'][8] . '","' . $f['http_request'][5] . '");';
                }
            }
        }
        if (!empty($tpl)) {
            $smarty->security = true;
            $back .= $smarty->fetch($tpl);
        } elseif (!empty($wiki)) {
            $smarty->security = true;
            $back .= $smarty->fetch('wiki:' . $wiki);
        }
        if ($prefs['feature_antibot'] == 'y' && empty($user) && !$_SESSION['in_tracker']) {
            // in_tracker session var checking is for tiki-register.php
            $back .= $smarty->fetch('antibot.tpl');
        }
        if (empty($tpl) && empty($wiki)) {
            $back .= "<tr><td></td><td>";
        }
        if (!empty($preview)) {
            $back .= "<input type='submit' name='tr_preview' value='" . tra($preview) . "' />";
        }
        $back .= "<input type='submit' name='action' value='" . tra($action) . "' />";
        if ($showmandatory == 'y' and $onemandatory) {
            $back .= "<em class='mandatory_note'>" . tra("Fields marked with a * are mandatory.") . "</em>";
        }
        if (empty($tpl) && empty($wiki)) {
            $back .= "</td></tr>";
            $back .= "</table>";
        } else {
            $back .= '</div>';
        }
        $back .= '</form>';
        if (!empty($js)) {
            $back .= '<script type="text/javascript">' . $js . '</script>';
        }
        if (!empty($page)) {
            $back .= '~/np~';
        }
        $smarty->assign_by_ref('tiki_p_admin_trackers', $tiki_p_admin_trackers);
        return $back;
    } else {
        if (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
            $smarty->assign('wikiplugin_tracker', $trackerId);
        }
        //used in vote plugin
        $id = ' id="wikiplugin_tracker' . $iTRACKER . '"';
        if ($showtitle == 'y') {
            $back .= '<div class="titlebar"' . $id . '>' . $tracker["name"] . '</div>';
            $id = '';
        }
        if ($showdesc == 'y') {
            $back .= '<div class="wikitext"' . $id . '>' . $tracker["description"] . '</div><br />';
            $id = '';
        }
        $back .= "<div{$id}>" . $data . '</div>';
        return $back;
    }
}
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 ($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 (empty($item_info)) {
				return '<b>'.tra("Incorrect item").'</b>';
			}
			$itemObject = Tracker_Item::fromInfo($item_info);
			if (! $itemObject->canModify()) {
				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 = '';

	$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();
			$auto_fieldId = array();
			$hidden_fieldId = 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)) {
					$auto_fieldId = array_merge($auto_fieldId, $autosavefields);
				}
				if ($user) {
					$hidden_fieldId[] = $trklib->get_field_id_from_type($trackerId, 'u', '1%');	// user owner
					$hidden_fieldId[] = $trklib->get_field_id_from_type($trackerId, 'u', '2%');	// user modifier
					$hidden_fieldId[] = $trklib->get_field_id_from_type($trackerId, 'g', '1%');	// owner group
					$hidden_fieldId[] = $trklib->get_field_id_from_type($trackerId, 'g', '2%');	// owner modifier
				}
				$hidden_fieldId[] = $trklib->get_field_id_from_type($trackerId, 'I', '1%');	// IP auto-assign
				$hidden_fieldId[] = $trklib->get_field_id_from_type($trackerId, 'k', '1%');	// page creator
				$auto_fieldId[] = $trklib->get_field_id_from_type($trackerId, 'q');	// auto-increment	
				foreach ($auto_fieldId as $k => $v) {
					if (empty($v) || in_array($v, $outf)) {
						unset($auto_fieldId[$k]);
					} else {
						$outf[] = $v;
					}
				}
				foreach ($hidden_fieldId as $k => $v) {
					if (empty($v) || in_array($v, $outf)) {
						unset($hidden_fieldId[$k]);
					} else {
						$outf[] = $v;
					}
				}
			}

			$definition = Tracker_Definition::get($trackerId);
			$item_info = isset($item_info) ? $item_info : array();
			$factory = $definition->getFieldFactory();

			if (empty($item_info)) {
				$itemObject = Tracker_Item::newItem($trackerId);
			} elseif (! isset($itemObject)) {
				$itemObject = Tracker_Item::fromInfo($item_info);
			}

			if (empty($outf)) {
				$unfiltered = array('data' => $definition->getFields());
			} else {
				$unfiltered = array('data' => array());
				foreach ($outf as $fieldId) {
					$unfiltered['data'][] = $definition->getField($fieldId);
				}
			}

			$flds = array('data' => array());
			foreach ($unfiltered['data'] as $f) {
				if ($itemObject->canModifyField($f['fieldId']) || $registration == 'y' && empty($item_info)) {
					$flds['data'][] = $f;
				}
			}

			// If we create multiple items, get field Ids, default values and separator
			if (!empty($fieldsfill)) {
				$fill_fields = preg_split('/ *: */', $fieldsfill);	// Allow for superfluous spaces and ignore them
				$fill_flds = array('data' => array());
				$fill_defaults = array();
				$fill_flds_defaults = array();	// May be different from fill_defaults if some fields are not editable
				$fieldsfillnames = array();
				if (trim($fieldsfilldefaults) != '') {
					$fill_defaults = preg_split('/ *: */', $fieldsfilldefaults);
				}
				foreach ($fill_fields as $k=>$fieldId) {
					if ($itemObject->canModifyField($fieldId)) {
						$tmp = $definition->getField($fieldId);
						$fill_flds['data'][] = $tmp;
						if (isset($fill_defaults[$k])) {
							$fill_flds_defaults[] = $fill_defaults[$k];
						} else {
							$fill_flds_defaults[] = '';
						}
						$fieldsfillnames[] = $tmp['name'];
					}
				}
				$fill_line_cant = count($fill_flds['data']);
				if ($fieldsfillseparator == '') {
					$fieldsfillseparator = '|';
				}
			}

			$bad = array();
			$embeddedId = false;
			$onemandatory = false;
			$full_fields = array();
			$mainfield = '';

			if ($thisIsThePlugin) {
				/* ------------------------------------- Recup all values from REQUEST -------------- */
				if (!empty($autosavefields)) {
					foreach ($autosavefields as $i=>$f) {
						if (!$ff = $trklib->get_field($f, $flds['data'])) {
							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_$f"] = $prefs[$matches[1]];
						} elseif ($ff['type'] == 'e') {
							$_REQUEST["ins_$f"][] = $autosavevalues[$i];
						} else {
							if (isset($params['levelupfields']) && in_array($f, $params['levelupfields'])) {
								$current_levelup_val = $trklib->get_item_value($trackerId, $itemId, $f);
								if ($autosavevalues[$i] <= $current_levelup_val) {
									continue;
								}
							}					
							$_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));
						if (isset($ins_fields['data'][$k]['value'])) {		// add ins value into field if creating or editing item
							$flds['data'][$k] = $ins_fields['data'][$k];	// to keep user input in case of errors (not only value)
						}
					}
				}
				$cpt = 0;
				if (isset($fields)) {
					$fields_plugin = preg_split('/:/', $fields);
				}
				if (!isset($itemId) && $tracker['oneUserItem'] == 'y') {
					$itemId = $trklib->get_user_item($trackerId, $tracker);
				}

				if ($embedded == 'y' && isset($_REQUEST['page'])) {
					$ins_fields["data"][] = array('fieldId' => $embeddedId, 'value' => $_REQUEST['page']);
				}

				if ($registration == 'y' && isset($params['userField'])) {
					$userField = $definition->getField($params['userField']);
					$userField['value'] = $_REQUEST['name'];
					$ins_fields['data'][] = $userField;
				}

				$ins_categs = 0; // important: non-array ins_categs means categories should remain unchanged
				$parent_categs_only = array();
				foreach ($ins_fields['data'] as $current_field) {
					if ($current_field['type'] == 'e' && isset($current_field['selected_categories'])) {
						if (!is_array($ins_categs)) {
							$ins_categs = array();
						}
						$ins_categs = array_merge($ins_categs, $current_field['selected_categories']);
						$parent_categs_only[] = $current_field['options_array'][0];
					}
				}
				$categorized_fields = $definition->getCategorizedFields();
				/* ------------------------------------- End recup all values from REQUEST -------------- */

				/* ------------------------------------- Check field values for each type and presence of mandatory ones ------------------- */
				$field_errors = $trklib->check_field_values($ins_fields, $categorized_fields, $trackerId, empty($itemId)?'':$itemId);

				if (empty($user) && $prefs['feature_antibot'] == 'y' && $registration != 'y') {
					// in_tracker session var checking is for tiki-register.php
					if (!$captchalib->validate()) {
						$field_errors['err_antibot'] = 'y';
					}
				}

				// check valid page name for wiki output if requested
				if (isset($outputtowiki) && !empty($outputwiki)) {
					$newpagename = '';
					foreach ($ins_fields["data"] as $fl) {
						if ($fl["fieldId"] == $outputtowiki) {
							$newpagename = $fl["value"];
						}
						if ($fl["type"] == 'F') {
							$newpagefreetags = $fl["value"];
						}
						$newpagefields[] = $fl["fieldId"];
					}
					if ($newpagename) {
						if ($tikilib->page_exists($newpagename)) {
							$field_errors['err_outputwiki'] = tra('The page to output the results to already exists. Try another name.');
						}
						$page_badchars_display = ":/?#[]@!$&'()*+,;=<>";
						$page_badchars = "/[:\/?#\[\]@!$&'()*+,;=<>]/";
						$matches = preg_match($page_badchars, $newpagename);
						if ($matches) {
							$field_errors['err_outputwiki'] = tr("The page to output the results to contains the following prohibited characters: %0. Try another name.", $page_badchars_display);
						} 
					} else {
						unset($outputtowiki);
					}
				}
				if ( count($field_errors['err_mandatory']) == 0  && count($field_errors['err_value']) == 0 && empty($field_errors['err_antibot']) && empty($field_errors['err_outputwiki']) && !isset($_REQUEST['tr_preview'])) {
					/* ------------------------------------- save the item ---------------------------------- */
					if (isset($_REQUEST['status'])) {
						$status = $_REQUEST['status'];
					} elseif (isset($newstatus) && ($newstatus == 'o' || $newstatus == 'c'|| $newstatus == 'p')) {
						$status = $newstatus;
					} elseif (empty($itemId) && isset($tracker['newItemStatus'])) {
						$status = $tracker['newItemStatus'];
					} else {
						$status = '';
					}

					if (!empty($fieldsfill) && !empty($_REQUEST['ins_fill']) ) {	// We create multiple items
						$fill_lines = explode("\n", $_REQUEST['ins_fill']);
						foreach ($fill_lines as $fill_line) {
							if (trim($fill_line) == '') {	// Ignore blank lines
								continue;
							}
							$fill_line_item = explode($fieldsfillseparator,$fill_line,$fill_line_cant);	// Extra fields are merged with the last field. this avoids data loss and permits a last text field with commas
							$rid = $trklib->replace_item($trackerId, $itemId, $ins_fields, $status, $ins_categs);
							for ($i=0;$i<$fill_line_cant;$i++) {
								if ($fill_line_item[$i] != '') {
									$fill_item = trim($fill_line_item[$i]);
								} else {
									$fill_item = $fill_flds_defaults[$i];
								}
								$fill_rid = $trklib->modify_field($rid, $fill_flds['data'][$i]['fieldId'], $fill_item);
							}
							if (is_array($ins_categs)) {
								if ($registration == 'y' && empty($item_info)) {
									$override_perms = true;
								} else {
									$override_perms = false;
								}
								$trklib->categorized_item($trackerId, $rid, $mainfield, $ins_categs, $parent_categs_only, $override_perms);	
							}
							if (isset($newItemRate)) {
								$trklib->replace_rating($trackerId, $rid, $newItemRateField, $user, $newItemRate);
							}
						}
					} else {
						if ($registration == 'y' && $_SERVER['REQUEST_METHOD'] != 'POST') {
							return false;
						}
						$rid = $trklib->replace_item($trackerId, $itemId, $ins_fields, $status, $ins_categs);
						if (is_array($ins_categs)) {
							if ($registration == 'y' && empty($item_info)) {
								$override_perms = true;
							} else {
								$override_perms = false;
							}
							$trklib->categorized_item($trackerId, $rid, $mainfield, $ins_categs, $parent_categs_only, $override_perms);	
						}
						if (isset($newItemRate)) {
							$trklib->replace_rating($trackerId, $rid, $newItemRateField, $user, $newItemRate);
						}
					}
					// now for wiki output if desired
					if (isset($outputtowiki) && !empty($outputwiki)) {
						// note that values will be raw - that is the limit of the capability of this feature for now
						$newpageinfo = $tikilib->get_page_info($outputwiki);
						$wikioutput = $newpageinfo["data"];
						$newpagefields = $trklib->get_pretty_fieldIds($outputwiki, 'wiki', $outputPretty);
						foreach ($newpagefields as $lf) {
							$wikioutput = str_replace('{$f_' . $lf . '}', $trklib->get_item_value($trackerId, $rid, $lf), $wikioutput);
						}
						if (isset($registration)) {
							 $wikioutput = str_replace('{$register_login}', $user, $wikioutput);
							 $wikioutput = str_replace('{$register_email}', $_REQUEST['email'], $wikioutput);
						}
						$tikilib->create_page($newpagename, 0, $wikioutput, $tikilib->now, '', $user, $tikilib->get_ip_address());
						$cat_desc = '';
						$cat_type = 'wiki page';
						$cat_name = $newpagename;
						$cat_objid = $newpagename;
						$cat_href = "tiki-index.php?page=".urlencode($newpagename);
						if (count($ins_categs)) {
							$_REQUEST['cat_categories'] = $ins_categs;
							$_REQUEST['cat_categorize'] = 'on';
							include_once("categorize.php");
						}
						if (isset($newpagefreetags) && $newpagefreetags) {
							$_REQUEST['freetag_string'] = $newpagefreetags;
							include_once("freetag_apply.php");
						}
						if ($discarditem == 'y') {
							$trklib->remove_tracker_item($rid);
						}
						if (empty($url)) {
							global $wikilib;
							$url[0] = $wikilib->sefurl($newpagename);
						}
					}
					// end wiki output
					if (!empty($email)) {
						$emailOptions = preg_split("#\|#", $email);
						if (is_numeric($emailOptions[0])) {
							$emailOptions[0] = $trklib->get_item_value($trackerId, $rid, $emailOptions[0]);
						}
						if (empty($emailOptions[0])) { // from
							$emailOptions[0] = $prefs['sender_email'];
						}
						if (empty($emailOptions[1])) { // to
							$emailOptions[1][0] = $prefs['sender_email'];
						} else {
							$emailOptions[1] = preg_split('/ *, */', $emailOptions[1]);
							foreach ($emailOptions[1] as $key=>$email) {
								if (is_numeric($email))
									$emailOptions[1][$key] = $trklib->get_item_value($trackerId, $rid, $email);
							}
						}
						include_once('lib/webmail/tikimaillib.php');
						$mail = new TikiMail();
						$mail->setHeader('From', $emailOptions[0]);
						
						if (!empty($emailOptions[2])) { //tpl
							$emailOptions[2] = preg_split('/ *, */', $emailOptions[2]);
							foreach ($emailOptions[2] as $ieo=>$eo) {
								if (!preg_match('/\.tpl$/', $eo))
									$emailOptions[2][$ieo] = $eo.'.tpl';
								$tplSubject[$ieo] = str_replace('.tpl', '_subject.tpl', $emailOptions[2][$ieo]);
							}
						} else {
							$emailOptions[2] = array('tracker_changed_notification.tpl');
						}
						if (empty($tplSubject)) {
							$tplSubject = array('tracker_changed_notification_subject.tpl');
						}
						$itpl = 0;
						$smarty->assign('mail_date', $tikilib->now);
						$smarty->assign('mail_itemId', $rid);
						foreach ($emailOptions[1] as $ieo=>$ueo) {
							@$mail_data = $smarty->fetch('mail/'.$tplSubject[$itpl]);
							if (empty($mail_data))
								$mail_data = tra('Tracker was modified at '). $_SERVER["SERVER_NAME"];
							$mail->setSubject($mail_data);
							$mail_data = $smarty->fetch('mail/'.$emailOptions[2][$itpl]);
							if ($emailformat == 'html') {
							$mail->setHtml($mail_data);
							} else {
							$mail->setText($mail_data);
							}
							$mail->buildMessage(array('text_encoding' => '8bit'));
							$mail->send($ueo);
							if (isset($tplSubject[$itpl+1]))
								++$itpl;
						}
					}
					if (empty($url)) {
						if (!empty($_REQUEST['ajax_add'])) {	// called by tracker ItemLink fields when adding new list items
							global $access;
							while ( ob_get_level() ) {
								ob_end_clean();
							}
							if ( $prefs['feature_obzip'] == 'y' ) {
								ob_start('ob_gzhandler');
							} else {
								ob_start();
							}
							// Need to add newly created itemId for item link selector
							$ins_fields['itemId'] = $rid;
							$access->output_serialized($ins_fields);
							ob_end_flush();
							die;
							
						} else if (!empty($page)) {
							$url = "tiki-index.php?page=".urlencode($page);
							if (!empty($itemId)) {
								$url .= "&itemId=".$itemId;
							}
							$url .= "&ok=y&iTRACKER=$iTRACKER";
							$url .= "#wikiplugin_tracker$iTRACKER";
							header("Location: $url");
							exit;
						} else {
							return '';
						}
					} else {
						$key = 0;
						foreach ($action as $key=>$act) {
							if (!empty($_REQUEST["action$key"])) {
								break;
							}
						}
						$itemIdPos = strpos($url[$key], 'itemId');
						if ($itemIdPos !== false) {
							if (strstr($url[$key], '#itemId')) {
								$url[$key] = str_replace('#itemId', $rid, $url[$key]);
							} else if (($itemIdPos+strlen('itemId') >= strlen($url[$key])-1) || (substr($url[$key], $itemIdPos+strlen('itemId'), 1) == "&")) {
								// replace by the itemId if in the end (or -1: for backward compatibility so that "&itemId=" also works) or if it is followed by an '&'
								$url[$key] = str_replace('itemId', 'itemId='.$rid, $url[$key]);
							}
						}
						header('Location: '.$url[$key]);
						exit;
					}
					/* ------------------------------------- end save the item ---------------------------------- */
				} elseif (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId) {
					$smarty->assign('wikiplugin_tracker', $trackerId);//used in vote plugin
				}

			} else if ((empty($itemId) || $overwrite == 'y') && !empty($values) || (!empty($_REQUEST['values']) and empty($_REQUEST['prefills']))) { // assign default values for each filedId specify
				if (empty($values)) { // url with values[]=x&values[] witouth the list of fields
					$values = $_REQUEST['values'];
				}
				if (!is_array($values)) {
					$values = array($values);
				}
				if (isset($fields)) {
					$fl = preg_split('/:/', $fields);
					for ($j = 0, $count_fl = count($fl); $j < $count_fl; $j++) {
						for ($i = 0, $count_flds = count($flds['data']); $i < $count_flds; $i++) {
							if ($flds['data'][$i]['fieldId'] == $fl[$j]) { 
								$flds['data'][$i]['value'] = $values[$j];
							}	
						}
					}
				} else { // values contains all the fields value in the default order
					$i = 0;
					foreach ($values as $value) {
						$flds['data'][$i++]['value'] = $value;
					}
				}
			
			} elseif (!empty($itemId)) {
				if (isset($fields)) {
					$fl = preg_split('/:/', $fields);
					$filter = '';
					foreach ($flds['data'] as $f) {
						if (in_array($f['fieldId'], $fl))
							$filter[] = $f;
					}
				} else {
					$filter = &$flds['data'];
				}
				if (!empty($filter)) {
					foreach ($filter as $f) {
						$filter2[$f['fieldId']] = $f;
					}
					$flds['data'] = $trklib->get_item_fields($trackerId, $itemId, $filter2, $itemUser, true);
				}
				// todo: apply the values for fields with no values
			} else {
				if (isset($_REQUEST['values']) && isset($_REQUEST['prefills'])) { //url:prefields=1:2&values[]=x&values[]=y
					if (!is_array($_REQUEST['values']))
						$_REQUEST['values'] = array($_REQUEST['values']);
					$fl = preg_split('/:/', $_REQUEST['prefills']);
				} else {
					unset($fl);
				}
				for ($i = 0, $count_flds2 = count($flds['data']); $i < $count_flds2; $i++) {
					if (isset($fl) && ($j = array_search($flds['data'][$i]['fieldId'], $fl)) !== false) {
						$flds['data'][$i]['value'] = $_REQUEST['values'][$j];
					} else {
						$flds['data'][$i]['value'] = ''; // initialize fields with blank values
					}
				}
			}

			// Check that individual fields are in the tracker
			if (!empty($fields)) {
				$fl = preg_split('/:/', $fields);
				if ($sort == 'y') {
					$flds = $trklib->sort_fields($flds, $fl);
				}		
				foreach ($fl as $l) {
					$ok = false;
					foreach ($flds['data'] as $f) {
						if ($f['fieldId'] == $l) {
							$ok = true;
							break;
						}
					}
					if (!$ok) {
						$back .= '<div class="error">' . tra('Incorrect fieldId:').' '.$l . '</div>';
					}
				}
			} elseif (empty($fields) && empty($wiki) && empty($tpl)) {
				// in this case outf still be blank and needs to be filled
				foreach ($flds['data'] as $f) {
					$outf[] = $f['fieldId'];
				}
			}

			// Check that multiple fill fields are in the tracker
			if (!empty($fieldsfill)) {
				foreach ($fill_fields as $l) {	
					$ok = false;
					foreach ($fill_flds['data'] as $f) {
						if ($f['fieldId'] == $l) {
							$ok = true;
							break;
						}
					}
					if (!$ok) {
						$back .= '<div class="error">' . tra('Incorrect fieldId:').' '.$l . '</div>';
					}
				}
			}

			// Display warnings when needed
			
			if (count($field_errors['err_mandatory']) > 0) {
				$smarty->assign_by_ref('err_mandatory', $field_errors['err_mandatory']);
			}
			if (count($field_errors['err_value']) > 0) {
				$smarty->assign_by_ref('err_value', $field_errors['err_value']);
			}
			if (count($field_errors['err_mandatory']) > 0 || count($field_errors['err_value']) > 0) {
				$back .= $smarty->fetch('tracker_error.tpl');
				$_REQUEST['error'] = 'y';
			}
			if (isset($field_errors['err_antibot'])) {
				$back.= '<div class="simplebox highlight"><img src="img/icons/exclamation.png" alt=" '.tra('Error').'" style="vertical-align:middle" /> ';
				$back .= $captchalib->getErrors();
				$back.= '</div><br />';
				$_REQUEST['error'] = 'y';
			}
			if (isset($field_errors['err_outputwiki'])) {
				$back.= '<div class="simplebox highlight"><img src="img/icons/exclamation.png" alt=" '.tra('Error').'" style="vertical-align:middle" /> ';
				$back .= $field_errors['err_outputwiki'];
				$back.= '</div><br />';
				$_REQUEST['error'] = 'y';
			}
			if (count($field_errors['err_mandatory']) > 0 || count($field_errors['err_value']) > 0 || isset($field_errors['err_antibot']) || isset($field_errors['err_outputwiki'])) {
				$smarty->assign('input_err', 'y');
			}
			if (!empty($page))
				$back .= '~np~';
			$smarty->assign_by_ref('tiki_p_admin_trackers', $perms['tiki_p_admin_trackers']);
			$smarty->assign('trackerEditFormId', $iTRACKER);

		if (!empty($params['_ajax_form_ins_id'])) {
			global $headerlib;									// when called via AJAX take a copy of the JS so far to allow collection
			$old_js['js'] = $headerlib->js;						// of tracker form JS into a function to initialise it when the dialog is created
			$old_js['jq_onready'] = $headerlib->jq_onready;
			$headerlib->clear_js();								// so store existing js for later and clear
		}

			if ($prefs['feature_jquery'] == 'y' && $prefs['feature_jquery_validation'] == 'y') {
				global $validatorslib;
				include_once('lib/validatorslib.php');
				$customvalidation = '';
				$customvalidation_m = '';
				if ($registration == 'y') {
					// email validation
					$customvalidation .= 'email: { ';
					$customvalidation .= 'required: true, ';
					$customvalidation .= 'email: true }, ';
					$customvalidation_m .= 'email: { email: "'. tra("Invalid email") 
								. '", required: "' . tra("This field is required")
								. '"}, ';
					// password validation
					$customvalidation .= 'pass: { ';
					$customvalidation .= 'required: true, ';
					$customvalidation .= 'remote: { ';
					$customvalidation .= 'url: "validate-ajax.php", ';
					$customvalidation .= 'type: "post", ';
					$customvalidation .= 'data: { ';
					$customvalidation .= 'validator: "password", ';
					$customvalidation .= 'input: function() { ';
					$customvalidation .= 'return $("#pass1").val(); ';
					$customvalidation .= '} } } ';
					$customvalidation .= '}, ';
					$customvalidation_m .= 'pass: { required: "' . tra("This field is required") . '"}, ';
					// password repeat validation
					$customvalidation .= 'passAgain: { equalTo: "#pass1" }, ';
					$customvalidation_m .= 'passAgain: { equalTo: "'. tra("Passwords do not match") .  '"}, ';
					// username validation
					$customvalidation .= 'name: { ';
					$customvalidation .= 'required: true, ';
					$customvalidation .= 'remote: { ';
					$customvalidation .= 'url: "validate-ajax.php", ';
					$customvalidation .= 'type: "post", ';
					$customvalidation .= 'data: { ';
					$customvalidation .= 'validator: "username", ';
					$customvalidation .= 'input: function() { ';
					$customvalidation .= 'return $("#name").val(); ';
					$customvalidation .= '} } } ';
					$customvalidation .= '}, ';
					$customvalidation_m .= 'name: { required: "' . tra("This field is required") . '"}, ';
					if (extension_loaded('gd') && function_exists('imagepng') && function_exists('imageftbbox') && $prefs['feature_antibot'] == 'y' && empty($user) && $prefs['recaptcha_enabled'] != 'y') {
						// antibot validation   
						$customvalidation .= '"captcha[input]": { ';
						$customvalidation .= 'required: true, ';
						$customvalidation .= 'remote: { ';
						$customvalidation .= 'url: "validate-ajax.php", ';
						$customvalidation .= 'type: "post", ';
						$customvalidation .= 'data: { ';
						$customvalidation .= 'validator: "captcha", ';
						$customvalidation .= 'parameter: function() { ';
						$customvalidation .= 'return $jq("#captchaId").val(); ';
						$customvalidation .= '}, ';
						$customvalidation .= 'input: function() { ';
						$customvalidation .= 'return $jq("#antibotcode").val(); ';
						$customvalidation .= '} } } ';
						$customvalidation .= '}, ';
						$customvalidation_m .= '"captcha[input]": { required: "' . tra("This field is required") . '"}, ';
					}
					if ($prefs['useRegisterPasscode'] == 'y') {
						$customvalidation .= 'passcode: {
									required: true,
									remote: {
										url: "validate-ajax.php", 
										type: "post",
										data: {
											validator: "passcode", 
											input: function() {
												return $("#passcode").val();
												}
											}
										}
									}, ';
						$customvalidation_m .= 'passcode: { required: "' . tra("This field is required") . '"}, ';
					} 
				}
				$validationjs = $validatorslib->generateTrackerValidateJS($flds['data'], $fields_prefix, $customvalidation, $customvalidation_m);

				$smarty->assign('validationjs', $validationjs);
				$back .= $smarty->fetch('tracker_validator.tpl');
			}
			if ($params['formtag'] == 'y') {
				$back .= '<form name="editItemForm' . $iTRACKER . '" id="editItemForm' . $iTRACKER . '" enctype="multipart/form-data" method="post"'.(isset($target)?' target="'.$target.'"':'').' action="'. $_SERVER['REQUEST_URI'] .'"><input type="hidden" name="trackit" value="'.$trackerId.'" />';
				$back .= '<input type="hidden" name="refresh" value="1" />';
			}
			$back .= '<input type="hidden" name="iTRACKER" value="'.$iTRACKER.'" />';
			if (isset($_REQUEST['page']))
				$back.= '<input type="hidden" name="page" value="'.$_REQUEST["page"].'" />';
			 // for registration
			if (isset($_REQUEST['name']))
				$back.= '<input type="hidden" name="name" value="'.$_REQUEST["name"].'" />';
			if (isset($_REQUEST['pass'])) {
				$back.= '<input type="hidden" name="pass" value="'.$_REQUEST["pass"].'" />';
				$back.= '<input type="hidden" name="passAgain" value="'.$_REQUEST["pass"].'" />';
			}
			if (isset($_REQUEST['email']))
				$back.= '<input type="hidden" name="email" value="'.$_REQUEST["email"].'" />';
			if (isset($_REQUEST['antibotcode']))
				$back.= '<input type="hidden" name="antibotcode" value="'.$_REQUEST["antibotcode"].'" />';
			if (isset($_REQUEST['chosenGroup'])) // for registration
				$back.= '<input type="hidden" name="chosenGroup" value="'.$_REQUEST["chosenGroup"].'" />';
			if (isset($_REQUEST['register']))
				$back.= '<input type="hidden" name="register" value="'.$_REQUEST["register"].'" />';
			if ($showtitle == 'y') {
				$back.= '<div class="titlebar">'.$tracker["name"].'</div>';
			}
			if ($showdesc == 'y' && $tracker['description']) {

				if ($tracker['descriptionIsParsed'] == 'y') {
					$back .= '<div class="wikitext">'.$tikilib->parse_data($tracker['description']).'</div><br />';
				} else {
					$back.= '<div class="wikitext">'.tra($tracker["description"]).'</div><br />';
				}
			}
			if (isset($_REQUEST['tr_preview'])) { // use for the computed and join fields
				$assocValues = array();
				$assocNumerics = array();
				foreach ($flds['data'] as $f) {
					if (empty($f['value']) && ($f['type'] == 'u' || $f['type'] == 'g' || $f['type'] == 'I') && ($f['options_array'][0] == '1' || $f['options_array'][0] == '2')) { //need to fill the selector fields for the join
						$f['value'] = ($f['type'] == 'I')? $tikilib->get_ip_address(): (($f['type'] == 'g')? $group: $user);
					}
					$assocValues[$f['fieldId']] = $f['value'];
					$assocNumerics[$f['fieldId']] = preg_replace('/[^0-9\.\+]/', '', $f['value']); // get rid off the $ and such unit
				}
			}

			if (!empty($itemId)) {
				$item = array('itemId'=>$itemId, 'trackerId'=>$trackerId);
			} else {
				$item = array('itemId'=>'');
			}
			foreach ($flds['data'] as $i=>$f) { // collect additional infos
				if (in_array($f['fieldId'], $outf)) {
					$flds['data'][$i]['ins_id'] = ($f['type'] == 'e')?'ins_'.$f['fieldId']: $fields_prefix.$f['fieldId'];
					if (($f['isHidden'] == 'c' || $f['isHidden'] == 'p') && !empty($itemId) && !isset($item['creator'])) {
						$item['creator'] = $trklib->get_item_creator($trackerId, $itemId);
					}
				}
			}
			if (!empty($showstatus) && $showstatus == 'y') {
				$status_types = $trklib->status_types();
				$smarty->assign_by_ref('status_types', $status_types);
				$smarty->assign('form_status', 'status');
				$smarty->assign_by_ref('tracker', $tracker);
				if (!empty($item_info)) {
					$smarty->assign_by_ref('item', $item_info);
				}
				$status_input = $smarty->fetch('tracker_status_input.tpl');
			}

			if ($registration == "y") {
				$back .= '<input type="hidden" name="register" value="Register" />';
			}
			
			// Loop on tracker fields and display form
			if (empty($tpl) && empty($wiki)) {
				$back.= '<table class="wikiplugin_tracker">';
				if (!empty($showstatus) && $showstatus == 'y') {
					$back .= '<tr><td>'.tra('Status').'</td><td>'.$status_input.'</td></tr>';
				}
				if ($registration == 'y' && $prefs["user_register_prettytracker"] != 'y') {
					$back .= $smarty->fetch('register-form.tpl');
				}
			} else {
				$back .= '<div class="wikiplugin_tracker">';
				if (!empty($showstatus) && $showstatus == 'y') {
					$smarty->assign_by_ref('f_status_input', $status_input);
				}
			}
			$backLength0 = strlen($back);

			foreach ($flds['data'] as $f) {

				if (!in_array($f['fieldId'], $auto_fieldId) && in_array($f['fieldId'], $hidden_fieldId)) {
					// Show in hidden form
					$back.= '<span style="display:none;">' . wikiplugin_tracker_render_input($f, $item)  . '</span>';
				} elseif (!in_array($f['fieldId'], $auto_fieldId) && in_array($f['fieldId'], $outf)) {
					if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
						$onemandatory = true;
					}
					if ($f['type'] == 'A') {
						$smarty->assign_by_ref('tiki_p_attach_trackers', $perms['tiki_p_attach_trackers']);
					}
					if (!empty($tpl) || !empty($wiki)) {
						if (!empty($outputPretty) && in_array($f['fieldId'], $outputPretty)) {
							$smarty->assign('f_'.$f['fieldId'], '<span class="outputPretty" id="track_'.$f['fieldId'].'" name="track_'.$f['fieldId'].'">'. wikiplugin_tracker_render_value($f, $item) . '</span>');
						} else {
							$mand =  ($showmandatory == 'y' and $f['isMandatory'] == 'y')? "&nbsp;<strong class='mandatory_star'>*</strong>&nbsp;":'';
							$smarty->assign('f_'.$f['fieldId'], wikiplugin_tracker_render_input($f, $item).$mand);
						}
					} else {
						$back.= "<tr><td";
						if (!empty($colwidth)) {
							$back .= " width='".$colwidth."'";
						}
						$back .= '><label for="' . $f['ins_id'] . '">' 
									. wikiplugin_tracker_name($f['fieldId'], tra($f['name']), $field_errors) . '</label>';
						if ($showmandatory == 'y' and $f['isMandatory'] == 'y') {
							$back.= "&nbsp;<strong class='mandatory_star'>*</strong>&nbsp;";
						}
						$back.= '</td><td>';

						$back .= wikiplugin_tracker_render_input($f, $item);
					}

					if ($f['type'] != 'S') {
						$back .= '<div class="trackerplugindesc">';
					}
					if ($f['type'] != 'S') {
						if ($f['descriptionIsParsed'] == 'y') {
							$back .= $tikilib->parse_data($f['description']);
						} else {
							$back .= tra($f['description']);
						}
					}
					if ($f['type'] != 'S') {
						$back .= '</div>';
					}
				}
			}
			if ( isset($params['fieldsfill']) && !empty($params['fieldsfill']) && empty($itemId) ) {
				// $back.= '<tr><td><label for="ins_fill">' . tra("Create multiple items (one per line).") . '</label>';
				$back.= '<tr><td><label for="ins_fill">' . tra("Insert one item per line:") 
					. '<br />'
					. '<br />'
					. '<br />'
					. '</label>';
				$back.= <<<FILL
</td><td>
<input type="hidden" value="" name="mode_wysiwyg"/>
<input type="hidden" value="" name="mode_normal"/>
<div class="edit-zone">
<textarea id="ins_fill" class="wikiedit" style="width: 99%;" data-syntax="" data-codemirror="" onkeyup="" rows="15" cols="50" name="ins_fill" >
</textarea >
</div>
<input type="hidden" value="n" name="wysiwyg"/>
<div name="ins_fill_desc" class="trackerplugindesc" >
FILL;
				$back.= sprintf(tra('Each line is a list of %d field values separated with: %s'),$fill_line_cant,htmlspecialchars($fieldsfillseparator));
				$back .= '</div><div name="ins_fill_desc2" class="trackerplugindesc" >' . htmlspecialchars(implode($fieldsfillseparator,$fieldsfillnames)) ;
				$back .= '</div></td></tr>';
			}
			if (!empty($tpl)) {
				$smarty->security = true;
				$back .= $smarty->fetch($tpl);
			} elseif (!empty($wiki)) {
				$smarty->security = true;
				if ($tikilib->page_exists($wiki)) {
					$back .= $smarty->fetch('wiki:'.$wiki);
				} else {
					$back .= '<span class="error">' . tr('Missing wiki template page "%0"', htmlspecialchars($wiki)) . '</span>';
				}
			}
			include_once('lib/smarty_tiki/function.trackerheader.php');
			$back .= smarty_function_trackerheader(array('level'=>-1, 'title'=>'', 'inTable' =>(empty($tpl) && empty($wiki))?'wikiplugin_tracker':'' ), $smarty);

			if ($prefs['feature_antibot'] == 'y' && empty($user) && $formtag != 'n'
				&& ($registration != 'y' || $prefs["user_register_prettytracker"] != 'y') ) {
				// in_tracker session var checking is for tiki-register.php
				$smarty->assign('showmandatory', $showmandatory);
				$smarty->assign('antibot_table', empty($wiki) && empty($tpl)?'n': 'y');
				$back .= $smarty->fetch('antibot.tpl');
			}
			if (empty($tpl) && empty($wiki)) {
				$back.= "</table>";
			} else {
				$back .= '</div>';
			}

			if ($params['formtag'] == 'y') {
				$back .= '<div class="input_submit_container">';

				if (!empty($reset)) {
					$back .= '<input class="button submit preview" type="reset" name="tr_reset" value="'.tra($reset).'" />';
				}
				if (!empty($preview)) {
					$back .= '<input class="button submit preview" type="submit" name="tr_preview" value="'.tra($preview).'" />';
				}
				foreach ($action as $key=>$act) {
					$back .= '<input class="button submit" type="submit" name="action'.$key.'" value="'.tra($act).'" onclick="needToConfirm=false" />';
				}
				$back .= '</div>';
			}
			if ($showmandatory == 'y' and $onemandatory) {
				$back.= "<em class='mandatory_note'>".tra("Fields marked with a * are mandatory.")."</em>";
			}
			if ($params['formtag'] == 'y') {
				$back.= '</form>';
			}

			if (!empty($params['_ajax_form_ins_id'])) {	// save new js in a function for the form init fn

				$headerlib->add_js(' var ajaxTrackerFormInit_' . $params['_ajax_form_ins_id'] . ' = function() {' . $headerlib->output_js(false) . '}', 10);

				// put back the pre-existing js
				$headerlib->js = array_merge( $headerlib->js, $old_js['js']);
				$headerlib->jq_onready = array_merge( $headerlib->jq_onready, $old_js['jq_onready']);
			}

			if (!empty($page))
				$back .= '~/np~';
			$smarty->assign_by_ref('tiki_p_admin_trackers', $perms['tiki_p_admin_trackers']);
		return $back;
	} else {
		if (isset($_REQUEST['trackit']) and $_REQUEST['trackit'] == $trackerId)
			$smarty->assign('wikiplugin_tracker', $trackerId);//used in vote plugin
		$id = ' id="wikiplugin_tracker'.$iTRACKER.'"';
		if ($showtitle == 'y') {
			$back.= '<div class="titlebar"'.$id.'>'.$tracker["name"].'</div>';
			$id = '';
		}
		if ($showdesc == 'y') {
			$back.= '<div class="wikitext"'.$id.'>'.$tracker["description"].'</div><br />';
			$id = '';
		}
		$back.= "<div$id>".$data.'</div>';
		return $back;
	}
}