Esempio n. 1
0
function smarty_block_trackeritemcheck($params, $content, $smarty, $repeat)
{
    if ($repeat) {
        return;
    }
    if (empty($params['itemId'])) {
        return tra('itemId required');
    }
    if (empty($params['mode'])) {
        $params['mode'] = '';
        // default is to view
    }
    $item = Tracker_Item::fromId($params['itemId']);
    $allowed = false;
    switch ($params['mode']) {
        case 'edit':
            $allowed = $item->canModify();
            break;
        case 'delete':
            $allowed = $item->canRemove();
            break;
        case 'view':
            $allowed = $item->canView();
        default:
            break;
    }
    if ($allowed) {
        return $content;
    } else {
        return '';
    }
}
Esempio n. 2
0
 function action_list($input)
 {
     global $prefs;
     $unifiedsearchlib = TikiLib::lib('unifiedsearch');
     $index = $unifiedsearchlib->getIndex();
     $dataSource = $unifiedsearchlib->getDataSource();
     $start = 'tracker_field_' . $input->beginField->word();
     $end = 'tracker_field_' . $input->endField->word();
     if ($resource = $input->resourceField->word()) {
         $resource = 'tracker_field_' . $resource;
     }
     if ($coloring = $input->coloringField->word()) {
         $coloring = 'tracker_field_' . $coloring;
     }
     $query = $unifiedsearchlib->buildQuery(array());
     $query->filterRange($input->start->int(), $input->end->int(), array($start, $end));
     $query->setRange(0, $prefs['unified_lucene_max_result']);
     if ($body = $input->filters->none()) {
         $builder = new Search_Query_WikiBuilder($query);
         $builder->apply(WikiParser_PluginMatcher::match($body));
     }
     $result = $query->search($index);
     $result = $dataSource->getInformation($result, array('title', $start, $end));
     $response = array();
     $smarty = TikiLib::lib('smarty');
     $smarty->loadPlugin('smarty_modifier_sefurl');
     foreach ($result as $row) {
         $item = Tracker_Item::fromId($row['object_id']);
         $response[] = array('id' => $row['object_id'], 'trackerId' => isset($row['tracker_id']) ? $row['tracker_id'] : null, 'title' => $row['title'], 'description' => '', 'url' => smarty_modifier_sefurl($row['object_id'], $row['object_type']), 'allDay' => false, 'start' => (int) $row[$start], 'end' => (int) $row[$end], 'editable' => $item->canModify(), 'color' => $this->getColor(isset($row[$coloring]) ? $row[$coloring] : ''), 'textColor' => '#000', 'resource' => $resource && isset($row[$resource]) ? $row[$resource] : '');
     }
     return $response;
 }
Esempio n. 3
0
 function action_list($input)
 {
     global $prefs;
     $unifiedsearchlib = TikiLib::lib('unifiedsearch');
     $index = $unifiedsearchlib->getIndex();
     $dataSource = $unifiedsearchlib->getDataSource();
     $start = 'tracker_field_' . $input->beginField->word();
     $end = 'tracker_field_' . $input->endField->word();
     if ($resource = $input->resourceField->word()) {
         $resource = 'tracker_field_' . $resource;
     }
     if ($coloring = $input->coloringField->word()) {
         $coloring = 'tracker_field_' . $coloring;
     }
     $query = $unifiedsearchlib->buildQuery(array());
     $query->filterRange($input->start->int(), $input->end->int(), array($start, $end));
     $query->setRange(0, $prefs['unified_lucene_max_result']);
     if ($body = $input->filters->none()) {
         $builder = new Search_Query_WikiBuilder($query);
         $builder->apply(WikiParser_PluginMatcher::match($body));
     }
     $result = $query->search($index);
     $result = $dataSource->getInformation($result, array('title', $start, $end));
     $response = array();
     $fields = array();
     if ($definition = Tracker_Definition::get($input->trackerId->int())) {
         foreach ($definition->getPopupFields() as $fieldId) {
             if ($field = $definition->getField($fieldId)) {
                 $fields[] = $field;
             }
         }
     }
     $smarty = TikiLib::lib('smarty');
     $smarty->loadPlugin('smarty_modifier_sefurl');
     $trklib = TikiLib::lib('trk');
     foreach ($result as $row) {
         $item = Tracker_Item::fromId($row['object_id']);
         $description = '';
         foreach ($fields as $field) {
             if ($item->canViewField($field['fieldId'])) {
                 $val = trim($trklib->field_render_value(array('field' => $field, 'item' => $item->getData(), 'process' => 'y')));
                 if ($val) {
                     if (count($fields) > 1) {
                         $description .= "<h5>{$field['name']}</h5>";
                     }
                     $description .= $val;
                 }
             }
         }
         $response[] = array('id' => $row['object_id'], 'trackerId' => isset($row['tracker_id']) ? $row['tracker_id'] : null, 'title' => $row['title'], 'description' => $description, 'url' => smarty_modifier_sefurl($row['object_id'], $row['object_type']), 'allDay' => false, 'start' => $this->getTimestamp($row[$start]), 'end' => $this->getTimestamp($row[$end]), 'editable' => $item->canModify(), 'color' => $this->getColor(isset($row[$coloring]) ? $row[$coloring] : ''), 'textColor' => '#000', 'resource' => $resource && isset($row[$resource]) ? strtolower($row[$resource]) : '');
     }
     return $response;
 }
Esempio n. 4
0
function smarty_function_object_link_trackeritem($smarty, $object, $title = null, $type = 'wiki page', $url = null)
{
    global $prefs;
    $pre = null;
    $item = Tracker_Item::fromId($object);
    //Set show status to 'y' by default
    if (!empty($prefs['tracker_status_in_objectlink'])) {
        $show_status = $prefs['tracker_status_in_objectlink'];
    } else {
        $show_status = 'y';
    }
    if ($show_status == 'y' && $item && ($status = $item->getDisplayedStatus())) {
        $alt = tr($status);
        $pre = "<img src=\"img/icons/status_{$status}.gif\" alt=\"{$status}\"/>&nbsp;";
    }
    return $pre . smarty_function_object_link_default($smarty, $object, $title, $type, $url);
}
Esempio n. 5
0
function wikiplugin_invite($data, $params)
{
    global $prefs, $user, $tiki_p_invite_to_my_groups;
    $userlib = TikiLib::lib('user');
    $tikilib = TikiLib::lib('tiki');
    $smarty = TikiLib::lib('smarty');
    if ($tiki_p_invite_to_my_groups != 'y') {
        return;
    }
    $userGroups = $userlib->get_user_groups_inclusion($user);
    if (!empty($params['including'])) {
        $groups = $userlib->get_including_groups($params['including']);
        foreach ($userGroups as $gr => $inc) {
            if (!in_array($gr, $groups)) {
                unset($userGroups[$gr]);
            }
        }
    }
    $errors = array();
    $feedbacks = array();
    if (isset($_REQUEST['invite'])) {
        if (empty($_REQUEST['email'])) {
            $errors[] = tra('The following mandatory fields are missing') . ' ' . tra('Email address');
        }
        if (!validate_email($_REQUEST['email'])) {
            $errors[] = tra('Invalid Email') . ' ' . $_REQUEST['email'];
        }
        if (!empty($_REQUEST['groups'])) {
            foreach ($_REQUEST['groups'] as $group) {
                if (empty($userGroups[$group])) {
                    $errors[] = tra('Incorrect param') . ' ' . $group;
                }
            }
        }
        if (empty($errors)) {
            $email = $_REQUEST['email'];
            if (!($invite = $userlib->get_user_by_email($email))) {
                $new_user = true;
                $password = '******';
                //$tikilib->genPass();
                $codedPassword = md5($password);
                if ($prefs['login_autogenerate'] == 'y') {
                    $uname = '';
                } else {
                    $uname = $email;
                }
                $uname = $userlib->add_user($uname, $password, $email, $password, true, NULL);
                $smarty->assign('codedPassword', $codedPassword);
                $invite = $email;
            } else {
                $new_user = false;
            }
            $smarty->assign_by_ref('new_user', $new_user);
            $smarty->assign_by_ref('invite', $invite);
            if (!empty($_REQUEST['groups'])) {
                foreach ($_REQUEST['groups'] as $group) {
                    $userlib->assign_user_to_group($uname, $group);
                    $invitedGroups[] = $userlib->get_group_info($group);
                }
            }
            include_once 'lib/webmail/tikimaillib.php';
            $mail = new TikiMail();
            $machine = parse_url($_SERVER['REQUEST_URI']);
            $machine = $tikilib->httpPrefix(true) . dirname($machine['path']);
            $smarty->assign_by_ref('machine', $machine);
            $subject = sprintf($smarty->fetch('mail/mail_invite_subject.tpl'), $_SERVER['SERVER_NAME']);
            $mail->setSubject($subject);
            if (!empty($_REQUEST['message'])) {
                $smarty->assign('message', $_REQUEST['message']);
            }
            $smarty->assign_by_ref('groups', $invitedGroups);
            $txt = $smarty->fetch('mail/mail_invite.tpl');
            $mail->setText($txt);
            $mail->send(array($email));
            return $data;
        } else {
            $smarty->assign_by_ref('errors', $errors);
            $smarty->assign_by_ref('email', $_REQUEST['email']);
            if (!empty($_REQUEST['groups'])) {
                $smarty->assign_by_ref('groups', $_REQUEST['groups']);
            }
            if (!empty($_REQUEST['message'])) {
                $smarty->assign_by_ref('message', $_REQUEST['message']);
            }
        }
    }
    if (!empty($_REQUEST['itemId'])) {
        $params['itemId'] = $_REQUEST['itemId'];
    }
    if (!empty($params['itemId'])) {
        $item = Tracker_Item::fromId($params['itemId']);
        $params['defaultgroup'] = $item->getOwnerGroup();
    }
    $smarty->assign_by_ref('params', $params);
    $smarty->assign_by_ref('userGroups', $userGroups);
    return '~np~' . $smarty->fetch('wiki-plugins/wikiplugin_invite.tpl') . '~/np~';
}
function smarty_function_object_link_trackeritem($smarty, $object, $title = null, $type = 'wiki page', $url = null)
{
    $pre = null;
    $item = Tracker_Item::fromId($object);
    if ($item && ($status = $item->getDisplayedStatus())) {
        $alt = tr($status);
        $pre = "<img src=\"img/icons/status_{$status}.gif\" alt=\"{$status}\"/>&nbsp;";
    }
    return $pre . smarty_function_object_link_default($smarty, $object, $title, $type, $url);
}
Esempio n. 7
0
function wikiplugin_vimeo($data, $params)
{
    global $prefs;
    static $instance = 0;
    $instance++;
    if (isset($params['url'])) {
        $params['vimeo'] = $params['url'];
        unset($params['url']);
        return wikiplugin_flash($data, $params);
    } elseif (isset($params['fileId'])) {
        $fileIds = preg_split('/\\D+/', $params['fileId'], -1, PREG_SPLIT_NO_EMPTY);
        unset($params['fileId']);
        $out = '';
        foreach ($fileIds as $fileId) {
            $attributelib = TikiLib::lib('attribute');
            $attributes = $attributelib->get_attributes('file', $fileId);
            if (!empty($attributes['tiki.content.url'])) {
                $params['vimeo'] = $attributes['tiki.content.url'];
                $out .= wikiplugin_flash($data, $params);
            } else {
                TikiLib::lib('errorreport')->report(tr('Vimeo video not found for file #%0', $fileId));
            }
        }
        return $out;
    } else {
        global $page;
        $smarty = TikiLib::lib('smarty');
        if ($prefs['vimeo_upload'] !== 'y') {
            $smarty->loadPlugin('smarty_block_remarksbox');
            $repeat = false;
            return smarty_block_remarksbox(array('type' => 'error', 'title' => tra('Feature required')), tra('Feature "vimeo_upload" is required to be able to add videos here.'), $smarty, $repeat);
        }
        // old perms access to get "special" gallery perms to handle user gals etc
        $perms = TikiLib::lib('tiki')->get_perm_object(!empty($params['galleryId']) ? $params['galleryId'] : $prefs['vimeo_default_gallery'], 'file gallery', TikiLib::lib('filegal')->get_file_gallery_info($prefs['vimeo_default_gallery']), false);
        if ($perms['tiki_p_upload_files'] !== 'y') {
            return '';
            //$permMessage = tra('You do not have permsission to add files here.');
        } else {
            if (!empty($params['fromFieldId'])) {
                $fieldInfo = TikiLib::lib('trk')->get_tracker_field($params['fromFieldId']);
                if (empty($params['fromItemId'])) {
                    $item = Tracker_Item::newItem($fieldInfo['trackerId']);
                } else {
                    $item = Tracker_Item::fromId($params['fromItemId']);
                }
                if (!$item->canModify()) {
                    return '';
                    //$permMessage = tra('You do not have permsission modify this tracker item.');
                }
            } else {
                if ($page) {
                    $pagePerms = Perms::get(array('type' => 'wiki page', 'object' => $page))->edit;
                    if (!$pagePerms) {
                        return '';
                        //$permMessage = tra('You do not have permsission modify this page.');
                    }
                }
            }
        }
        // set up for an upload
        $smarty->loadPlugin('smarty_function_button');
        $smarty->loadPlugin('smarty_function_service');
        $html = smarty_function_button(array('_keepall' => 'y', '_class' => 'vimeo dialog', 'href' => smarty_function_service(array('controller' => 'vimeo', 'action' => 'upload'), $smarty), '_text' => tra('Upload Video')), $smarty);
        $js = '
$(".vimeo.dialog").click(function () {
	var link = this;
	$(this).serviceDialog({
		title: tr("Upload Video"),
		data: {
			controller: "vimeo",
			action: "upload"' . (!empty($params['galleryId']) ? ',galleryId:' . $params['galleryId'] : '') . (!empty($params['fromFieldId']) ? ',fieldId:' . $params['fromFieldId'] : '') . (!empty($params['fromItemId']) ? ',itemId:' . $params['fromItemId'] : '') . '
		},
		load: function(data) {
			var $dialog = $(".vimeo_upload").parents(".ui-dialog-content");		// odd its the content, not the outer div
			$(".vimeo_upload").on("vimeo_uploaded", function(event, data) {';
        if (!empty($page) && empty($params['fromFieldId'])) {
            $js .= '
				var params = {
					page: ' . json_encode($page) . ',
					content: "",
					index: ' . $instance . ',
					type: "vimeo",
					params: {
						url: data.url
					}
				};
				$.post("tiki-wikiplugin_edit.php", params, function() {
					$("input[type=file]", $dialog).val("");		// webkit reloads the dialog as it destroys it for some reason
					$dialog.dialog("destroy").remove();
					$.get($.service("wiki", "get_page", {page:' . json_encode($page) . '}), function (data) {
						if (data) {
							$("#page-data").html(data);
						}
					});
				});';
        } else {
            $js .= '
				$dialog.dialog("destroy").remove();
				handleVimeoFile(link, data);
';
        }
        $js .= '	});
		}
	});
	return false;
});';
        TikiLib::lib('header')->add_jq_onready($js);
        return $html;
    }
}
Esempio n. 8
0
 function action_process($input)
 {
     $id = $input->id->int();
     $userid = $input->userid->int();
     $username = $input->username->text();
     $fieldId = $input->fieldId->int();
     $command = $input->command->word();
     $svntag = $input->svntag->text();
     $item = Tracker_Item::fromId($id);
     if (!$item->canViewField($fieldId)) {
         throw new Services_Exception_Denied();
     }
     $field = TikiLib::lib('trk')->get_tracker_field($fieldId);
     $options = json_decode($field['options']);
     if (!is_object($options) && is_array($field['options_array'])) {
         // Support Tiki 11
         $options = new stdClass();
         $options->domain = $field['options_array'][0];
         $options->remoteShellUser = $field['options_array'][1];
         $options->publicKey = $field['options_array'][2];
         $options->privateKey = $field['options_array'][3];
     }
     $domain = $options->domain;
     $conn = ssh2_connect($domain, 22);
     $conntry = ssh2_auth_pubkey_file($conn, $options->remoteShellUser, $options->publicKey, $options->privateKey);
     if (!$conntry) {
         $ret['status'] = 'DISCO';
         return $ret;
     }
     $infostring = "info -i {$id} -U {$userid}";
     $infostream = ssh2_exec($conn, $infostring);
     stream_set_blocking($infostream, TRUE);
     $infooutput = stream_get_contents($infostream);
     $ret['debugoutput'] = $infooutput;
     if (strpos($infooutput, 'MAINTENANCE: ') !== false) {
         $maintpos = strpos($infooutput, 'MAINTENANCE: ');
         $maintreason = substr($infooutput, $maintpos + 13);
         $maintreason = substr($maintreason, 0, strpos($maintreason, '"'));
         $ret['maintreason'] = $maintreason;
         $ret['status'] = 'MAINT';
         return $ret;
     }
     $versionpos = strpos($infooutput, 'VERSION: ');
     $version = substr($infooutput, $versionpos + 9);
     $version = substr($version, 0, strpos($version, PHP_EOL));
     $version = trim($version);
     $ret['version'] = $version;
     $statuspos = strpos($infooutput, 'STATUS: ');
     $status = substr($infooutput, $statuspos + 8, 5);
     $status = trim($status);
     if (!$status || $status == 'FAIL') {
         $ret['status'] = 'FAIL';
     } else {
         $ret['status'] = $status;
         $sitepos = strpos($infooutput, 'SITE: ');
         $site = substr($infooutput, $sitepos + 6);
         $site = substr($site, 0, strpos($site, ' '));
         $ret['showurl'] = $site;
         $ret['showlogurl'] = $site . '/info.txt';
         $ret['snapshoturl'] = $site . '/snapshots/';
         if ($site && $ret['status'] == 'ACTIV') {
             $value = 'active ' . substr($site, 0, strpos($site, '.'));
             // the 'active' is useful for filtering on
             TikiLib::lib('trk')->modify_field($id, $fieldId, $value);
             require_once 'lib/search/refresh-functions.php';
             refresh_index('trackeritem', $id);
         } elseif ($ret['status'] == 'NONE') {
             $value = 'none';
             TikiLib::lib('trk')->modify_field($id, $fieldId, $value);
             require_once 'lib/search/refresh-functions.php';
             refresh_index('trackeritem', $id);
         }
     }
     if (!empty($command)) {
         if (($command == 'update' || $command == 'reset' || $command == 'destroy') && !TikiLib::lib('user')->user_has_permission($user, 'tiki_p_admin') && $user != $creator) {
             throw new Services_Exception_Denied();
         }
         if (empty($svntag)) {
             $fullstring = "{$command} -u {$creator} -i {$id} -U {$userid}";
         } else {
             $fullstring = "{$command} -t {$svntag} -u {$username} -i {$id} -U {$userid}";
         }
         $stream = ssh2_exec($conn, $fullstring);
         stream_set_blocking($stream, TRUE);
         $output = stream_get_contents($stream);
         fclose($stream);
         $ret['debugoutput'] = $fullstring . "\n" . $output;
         if ($command == 'snapshot') {
             $ret['status'] = 'SNAPS';
         } else {
             if ($command == 'destroy') {
                 $ret['status'] = 'DESTR';
             } else {
                 if ($command == 'create' || $command == 'update') {
                     $ret['status'] = 'BUILD';
                 } else {
                     if ($command == 'reset') {
                         if (strpos('ERROR', $fullstring) !== false) {
                             $ret['status'] = 'RENOK';
                         } else {
                             $ret['status'] = 'RESOK';
                         }
                     }
                 }
             }
         }
     }
     $ret['debugoutput'] = '-' . $status . '- ' . $ret['debugoutput'];
     $cachelib = TikiLib::lib('cache');
     $cacheKey = 'STO-' . $options->domain . '-' . $fieldId . "-" . $id;
     $cachelib->invalidate($cacheKey);
     return $ret;
 }
Esempio n. 9
0
 function action_clone_item($input)
 {
     global $prefs;
     Services_Exception_Disabled::check('tracker_clone_item');
     $trackerId = $input->trackerId->int();
     $definition = Tracker_Definition::get($trackerId);
     if (!$definition) {
         throw new Services_Exception_NotFound();
     }
     $itemId = $input->itemId->int();
     if (!$itemId) {
         throw new Services_Exception_Denied(tr('No item to clone'));
     }
     $itemObject = Tracker_Item::fromId($itemId);
     if (!$itemObject->canView()) {
         throw new Services_Exception_Denied(tr('Item to clone not visible'));
     }
     $newItem = Tracker_Item::newItem($trackerId);
     if (!$newItem->canModify()) {
         throw new Services_Exception_Denied(tr('Not allowed to create new items'));
     }
     global $prefs;
     if ($prefs['feature_jquery_validation'] === 'y') {
         $_REQUEST['itemId'] = 0;
         // let the validation code know this will be a new item
         $validationjs = TikiLib::lib('validators')->generateTrackerValidateJS($definition->getFields());
         TikiLib::lib('header')->add_jq_onready('$("#cloneItemForm' . $trackerId . '").validate({' . $validationjs . $this->get_validation_options());
     }
     $itemObject->asNew();
     $itemData = $itemObject->getData($input);
     $id = 0;
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $transaction = TikiLib::lib('tiki')->begin();
         $id = $this->utilities->insertItem($definition, $itemData);
         foreach ($definition->getFields() as $field) {
             $handler = $definition->getFieldFactory()->getHandler($field, $itemData);
             if (method_exists($handler, 'handleClone')) {
                 $handler->handleClone();
             }
         }
         $itemObject = Tracker_Item::fromId($id);
         foreach (TikiLib::lib('trk')->get_child_items($itemId) as $info) {
             $childItem = Tracker_Item::fromId($info['itemId']);
             if ($childItem->canView()) {
                 $childItem->asNew();
                 $data = $childItem->getData();
                 $data['fields'][$info['field']] = $id;
                 $childDefinition = $childItem->getDefinition();
                 // handle specific cloning actions
                 foreach ($childDefinition->getFields() as $field) {
                     $handler = $childDefinition->getFieldFactory()->getHandler($field, $data);
                     if (method_exists($handler, 'handleClone')) {
                         $newData = $handler->handleClone();
                         $data['fields'][$field['permName']] = $newData['value'];
                     }
                 }
                 $new = $this->utilities->insertItem($childDefinition, $data);
             }
         }
         $transaction->commit();
     }
     return array('title' => tr('Duplicate Item'), 'trackerId' => $trackerId, 'itemId' => $itemId, 'created' => $id, 'data' => $itemData['fields'], 'fields' => $itemObject->prepareInput(new JitFilter(array())));
 }
Esempio n. 10
0
        }
    } else {
        //new file
        if ($isConversion) {
            $_REQUEST['name'] = preg_replace('/\\.(:?jpg|gif|png|tif[f]?)$/', '', $_REQUEST['name']) . tra(' drawing');
            // strip extension
        }
        $galleryId = $_REQUEST["galleryId"];
        if ($prefs['feature_draw_in_userfiles'] === 'y') {
            $galleryId = TikiLib::lib('filegal')->get_user_file_gallery();
        }
        $fileId = $filegallib->insert_file($galleryId, $_REQUEST['name'], $_REQUEST['description'], $_REQUEST['name'] . ".svg", $_REQUEST['data'], strlen($_REQUEST['data']), $type, $user, null);
    }
    if (!empty($_REQUEST['fromItemId'])) {
        // a tracker item, so update the item field
        $item = Tracker_Item::fromId($_REQUEST['fromItemId']);
        if ($item->canModifyField($_REQUEST['fromFieldId'])) {
            $definition = $item->getDefinition();
            $field = $definition->getField($_REQUEST['fromFieldId']);
            $trackerInput = $item->prepareFieldInput($field, array($_REQUEST['fromFieldId']->{$fileId}));
            $trackerInput['value'] = $fileId;
            TikiLib::lib('trk')->replace_item($field['trackerId'], $_REQUEST['fromItemId'], array('data' => array($trackerInput)));
        }
    }
    echo $fileId;
    die;
}
if ($fileInfo['filetype'] == $mimetypes["svg"]) {
    $data = $fileInfo["data"];
} else {
    //we already confirmed that this is an image, here we make it compatible with svg
Esempio n. 11
0
 protected function getItem($id)
 {
     global $prefs;
     $tracker = Tracker_Definition::get($prefs['mustread_tracker']);
     $item = Tracker_Item::fromId($id);
     if (!$item || $tracker !== $item->getDefinition()) {
         throw new Services_Exception_NotFound(tr('Must Read Item not found'));
     }
     if (!$item->canView()) {
         throw new Services_Exception_Denied(tr('Permission denied'));
     }
     return $item;
 }
Esempio n. 12
0
 function __construct($itemId)
 {
     $this->item = \Tracker_Item::fromId($itemId);
     $this->data = $this->item->getData();
     $this->extra = ['itemId' => $this->data['itemId'], 'status' => $this->data['status']];
 }
Esempio n. 13
0
 function action_remove_item($input)
 {
     $trackerId = $input->trackerId->int();
     $definition = Tracker_Definition::get($trackerId);
     if (!$definition) {
         throw new Services_Exception_NotFound();
     }
     if (!($itemId = $input->itemId->int())) {
         throw new Services_Exception_MissingValue('itemId');
     }
     $itemInfo = TikiLib::lib('trk')->get_tracker_item($itemId);
     if (!$itemInfo || $itemInfo['trackerId'] != $trackerId) {
         throw new Services_Exception_NotFound();
     }
     $itemObject = Tracker_Item::fromInfo($itemInfo);
     if (!$itemObject->canRemove()) {
         throw new Services_Exception_Denied();
     }
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $trklib = TikiLib::lib('trk');
         foreach ($trklib->get_child_items($itemId) as $info) {
             $childItem = Tracker_Item::fromId($info['itemId']);
             if ($childItem->canRemove()) {
                 $data = $childItem->getData();
                 $childDefinition = $childItem->getDefinition();
                 // handle specific deleting actions
                 foreach ($childDefinition->getFields() as $field) {
                     $handler = $childDefinition->getFieldFactory()->getHandler($field, $data);
                     if (method_exists($handler, 'handleDelete')) {
                         $handler->handleDelete();
                     }
                 }
                 $this->utilities->removeItem($info['itemId']);
             }
         }
         foreach ($definition->getFields() as $field) {
             $itemData = $itemObject->getData();
             $handler = $definition->getFieldFactory()->getHandler($field, $itemData);
             if (method_exists($handler, 'handleDelete')) {
                 $handler->handleDelete();
             }
         }
         $this->utilities->removeItem($itemId);
         TikiLib::lib('unifiedsearch')->processUpdateQueue();
     }
     return array('trackerId' => $trackerId, 'itemId' => $itemId);
 }
Esempio n. 14
0
 private function getSystemSchema($name)
 {
     switch ($name) {
         case 'actions':
             $trackerId = $this->definition->getConfiguration('trackerId');
             $schema = new self($this->definition);
             $schema->addNew($name, 'all')->setLabel(tr('Actions'))->addQuerySource('itemId', 'object_id')->setReadOnly(true)->setPlainReplacement(false)->setRenderTransform(function ($value, $extra) use($trackerId) {
                 $smarty = \TikiLib::lib('smarty');
                 $item = \Tracker_Item::fromId($extra['itemId']);
                 $smarty->assign('tabular_actions', ['trackerId' => $trackerId, 'itemId' => $extra['itemId'], 'canModify' => $item->canModify(), 'canRemove' => $item->canRemove()]);
                 return $smarty->fetch('tabular/item_actions.tpl');
             });
             return $schema;
         case 'itemId':
             $schema = new self($this->definition);
             $schema->addNew($name, 'id')->setLabel(tr('Item ID'))->addQuerySource('itemId', 'object_id')->setRenderTransform(function ($value, $extra) {
                 return $extra['itemId'];
             })->setParseIntoTransform(function (&$info, $value) {
                 $info['itemId'] = (int) $value;
             });
             return $schema;
         case 'status':
             $types = \TikiLib::lib('trk')->status_types();
             $invert = array_flip(array_map(function ($s) {
                 return $s['name'];
             }, $types));
             $schema = new self($this->definition);
             $schema->addNew($name, 'system')->setLabel(tr('Status'))->addQuerySource('status', 'tracker_status')->setRenderTransform(function ($value, $extra) {
                 return $extra['status'];
             })->setParseIntoTransform(function (&$info, $value) {
                 $info['status'] = $value;
             });
             $schema->addNew($name, 'name')->setLabel(tr('Status'))->addQuerySource('status', 'tracker_status')->setRenderTransform(function ($value, $extra) use($types) {
                 return $types[$extra['status']]['name'];
             })->setParseIntoTransform(function (&$info, $value) use($invert) {
                 $info['status'] = $invert[$value];
             });
             return $schema;
     }
 }
Esempio n. 15
0
function wikiplugin_trackerlist($data, $params)
{
    global $tiki_p_admin_trackers, $prefs, $tiki_p_view_trackers, $user, $page, $tiki_p_tracker_vote_ratings, $tiki_p_tracker_view_ratings, $tiki_p_export_tracker, $tiki_p_watch_trackers, $tiki_p_edit;
    $userlib = TikiLib::lib('user');
    $tikilib = TikiLib::lib('tiki');
    $trklib = TikiLib::lib('trk');
    $smarty = TikiLib::lib('smarty');
    $notificationlib = TikiLib::lib('notification');
    static $iTRACKERLIST = 0;
    ++$iTRACKERLIST;
    $smarty->assign('iTRACKERLIST', $iTRACKERLIST);
    $default = array('calendarfielddate' => '', 'wiki' => '', 'calendarviewmode' => 'month', 'calendarstickypopup' => 'n', 'calendarbeginmonth' => 'y', 'calendarviewnavbar' => 'y', 'calendartitle' => '', 'calendardelta' => '', 'force_compile' => 'n', 'editable' => array(), 'editableall' => 'n');
    $params = array_merge($default, $params);
    extract($params, EXTR_SKIP);
    $skip_status_perm_check = false;
    if (isset($force_separate_compile) && $force_separate_compile == 'y') {
        $smarty->assign('force_separate_compile', 'y');
    }
    if ($prefs['feature_trackers'] != 'y' || !isset($trackerId) || !($tracker_info = $trklib->get_tracker($trackerId))) {
        return $smarty->fetch("wiki-plugins/error_tracker.tpl");
    } else {
        global $auto_query_args;
        $auto_query_args_local = array('trackerId', 'tr_initial', "tr_sort_mode{$iTRACKERLIST}", 'tr_user', 'filterfield', 'filtervalue', 'exactvalue', 'itemId', "tr_offset{$iTRACKERLIST}");
        $auto_query_args = empty($auto_query_args) ? $auto_query_args_local : array_merge($auto_query_args, $auto_query_args_local);
        $smarty->assign('listTrackerId', $trackerId);
        $definition = Tracker_Definition::get($trackerId);
        $tracker_info = $definition->getInformation();
        if (!isset($sort)) {
            $sort = 'n';
        }
        $perms = $tikilib->get_perm_object($trackerId, 'tracker', $tracker_info, false);
        if ($perms['tiki_p_view_trackers'] != 'y' && !$user) {
            return;
        }
        $userCreatorFieldId = $definition->getAuthorField();
        $groupCreatorFieldId = $definition->getWriterGroupField();
        if ($perms['tiki_p_view_trackers'] != 'y' && !$definition->isEnabled('writerCanModify') && !$definition->isEnabled('userCanSeeOwn') && empty($userCreatorFieldId) && empty($groupCreatorFieldId)) {
            return;
        }
        $smarty->assign_by_ref('perms', $perms);
        if (!empty($fields)) {
            $limit = $fields;
        } else {
            $limit = '';
        }
        // Make sure limit is an array
        if (!is_array($limit) && !empty($limit)) {
            $limit = explode(':', $limit);
        }
        if (!empty($filterfield) && !empty($limit)) {
            $limit = array_unique(array_merge($limit, $filterfield));
        }
        // for some reason if param popup is set but empty, the array contains 2 empty elements. We filter them out.
        if (isset($popup)) {
            $popup = array_filter($popup);
            if (!empty($popup)) {
                $limit = array_unique(array_merge($limit, $popup));
            }
        }
        if (!empty($calendarfielddate)) {
            $limit = array_unique(array_merge($limit, $calendarfielddate));
        }
        if (!empty($limit) && $trklib->test_field_type($limit, array('C'))) {
            $limit = array();
        }
        $allfields = $trklib->list_tracker_fields($trackerId, 0, -1, 'position_asc', '', true, '', $trklib->flaten($limit));
        if (!empty($fields)) {
            $listfields = $fields;
            //We must include the $calendarfielddate, even if they are not in the listfields
            if (!empty($calendarfielddate)) {
                foreach ($calendarfielddate as $f) {
                    if (!in_array($f, $listfields)) {
                        $listfields[] = $f;
                    }
                }
            }
            if ($sort == 'y') {
                $allfields = $trklib->sort_fields($allfields, $listfields);
            }
        } elseif (!empty($wiki) || !empty($tpl) || !empty($tplwiki)) {
            if (!empty($wiki)) {
                $listfields = $trklib->get_pretty_fieldIds($wiki, 'wiki', $prettyModifier, $trackerId);
            } elseif (!empty($tplwiki)) {
                $listfields = $trklib->get_pretty_fieldIds($tplwiki, 'wiki', $prettyModifier, $trackerId);
            } else {
                $listfields = $trklib->get_pretty_fieldIds($tpl, 'tpl', $prettyModifier, $trackerId);
            }
        } else {
            $listfields = '';
        }
        if (!empty($compute) && !empty($listfields)) {
            if (preg_match_all('/[0-9.]+/', $compute, $matches)) {
                foreach ($matches[0] as $f) {
                    if (!in_array($f, $listfields)) {
                        $listfields[] = $f;
                    }
                }
            }
        }
        /*** tablesorter ***/
        //note whether ajax is needed
        $tsServer = isset($params['server']) && $params['server'] === 'y' ? true : false;
        $tsOn = isset($sortable) && $sortable !== 'n' && Table_Check::isEnabled($tsServer);
        $smarty->assign('tsOn', $tsOn);
        //note whether this is the initial tablesorter ajax call or a subsequent ajax call
        $tsAjax = Table_Check::isAjaxCall();
        $smarty->assign('tsAjax', $tsAjax);
        if ($tsAjax) {
            // if status is enabled, need to adjust field index by -1 - need to check both - tracker config and plugin config
            $adjustCol = isset($showstatus) && $showstatus == 'y' && $definition->isEnabled('showStatus') ? -1 : 0;
            //convert tablesorter filter syntax to tiki syntax
            if (!empty($_REQUEST['filter'])) {
                $i = 0;
                $tsfiltersArray = explode('|', $tsfilters);
                foreach ($_REQUEST['filter'] as $col => $ajaxfilter) {
                    $fieldtype = $allfields['data'][$col + $adjustCol]['type'];
                    $id = $allfields['data'][$col + $adjustCol]['fieldId'];
                    //handle status filter
                    if ($adjustCol === -1 && $col === 0 && in_array($ajaxfilter, ['o', 'p', 'c'])) {
                        $status = $ajaxfilter;
                        /*
                         * handle date filter - these are always one filter, in the form of:
                         * from: >=1427389832000; to: <=1427389832000; both from and to: 1427389832000 - 1427880000000
                         * which is unix timestamp in milliseconds
                         */
                    } elseif (strpos($tsfiltersArray[$col], 'type:date') !== false && in_array($fieldtype, ['f', 'j'])) {
                        $datefilter = explode(' - ', $ajaxfilter);
                        $filterfield[$i] = $id;
                        //a range (from and to filters) will have 2 items in the array
                        if (count($datefilter) == 2) {
                            $filterfield[$i + 1] = $id;
                            //use substr to leave off milliseconds since date is stored in seconds in the database
                            $exactvalue[$i] = 'greaterequal(@' . substr($datefilter[0], 0, 10) . ')';
                            $exactvalue[$i + 1] = 'lessequal(@' . substr($datefilter[1], 0, 10) . ')';
                        } else {
                            //use substr to leave off milliseconds since date is stored in seconds in the database
                            $stamp = '(@' . substr($datefilter[0], 2, 10) . ')';
                            $symbol = substr($datefilter[0], 0, 2);
                            if ($symbol === '<=') {
                                $compare = 'lessequal';
                            } elseif ($symbol === '>=') {
                                $compare = 'greaterequal';
                            }
                            $exactvalue[$i] = $compare . $stamp;
                        }
                    } else {
                        $filterfield[$i] = $id;
                        //convert category filters entered as text
                        if ($fieldtype === 'e' && !is_numeric($ajaxfilter)) {
                            $categlib = TikiLib::lib('categ');
                            $ajaxfilter = $categlib->get_category_id($ajaxfilter);
                        }
                        $filtervalue[$i] = $ajaxfilter;
                    }
                    $i++;
                }
            }
            //convert tablesorter sort syntax to tiki syntax
            if (!empty($_REQUEST['sort'])) {
                foreach ($_REQUEST['sort'] as $sortcol => $ajaxsort) {
                    if ($ajaxsort == '0') {
                        $dir = '_asc';
                    } elseif ($ajaxsort == '1') {
                        $dir = '_desc';
                    }
                    //avoid setting sort_mode based on status field - will return error. Handle later once records are retrieved
                    if ($adjustCol !== -1 || $sortcol !== 0) {
                        $sort_mode = 'f_' . $allfields['data'][$sortcol + $adjustCol]['fieldId'] . $dir;
                    }
                }
            }
            //set max records
            if (isset($_REQUEST['numrows'])) {
                $max = $_REQUEST['numrows'];
            }
        }
        /*** end first tablesorter section ***/
        if (!empty($filterfield)) {
            if (is_array($filterfield)) {
                foreach ($filterfield as $ff) {
                    unset($filterfieldok);
                    if (is_array($ff)) {
                        // already checked in trackerfilter
                        $filterfieldok = true;
                        break;
                    } else {
                        foreach ($allfields['data'] as $f) {
                            if ($f['fieldId'] == $ff) {
                                $filterfieldok = true;
                                break;
                            }
                        }
                    }
                    if (!isset($filterfieldok)) {
                        break;
                    }
                }
            } else {
                foreach ($allfields['data'] as $f) {
                    if ($f['fieldId'] == $filterfield) {
                        $filterfieldok = true;
                        break;
                    }
                }
            }
            if (!isset($filterfieldok)) {
                return tra('incorrect filterfield');
            }
        }
        $filter = array();
        if (isset($periodQuantity)) {
            switch ($periodUnit) {
                case 'hour':
                    $periodUnit = 3600;
                    break;
                case 'day':
                    $periodUnit = 86400;
                    break;
                case 'week':
                    $periodUnit = 604800;
                    break;
                case 'month':
                    $periodUnit = 2628000;
                    break;
                default:
                    break;
            }
            if (!isset($periodType)) {
                $periodType = 'c';
            }
            if (is_int($periodUnit) && $periodType == 'm') {
                $filter['lastModifAfter'] = $tikilib->now - $periodQuantity * $periodUnit;
                $filter['lastModifBefore'] = $tikilib->now;
            } elseif (is_int($periodUnit)) {
                # case for periodType beig c or anything else (therefore, set as case for default)
                $filter['createdAfter'] = $tikilib->now - $periodQuantity * $periodUnit;
                $filter['createdBefore'] = $tikilib->now;
            }
        }
        if (isset($_REQUEST['reloff']) && empty($_REQUEST['itemId']) && !empty($_REQUEST['trackerId'])) {
            //coming from a pagination
            $items = $trklib->list_items($_REQUEST['trackerId'], $_REQUEST['reloff'], 1, '', '', isset($_REQUEST['filterfield']) ? preg_split('/\\s*:\\s*/', $_REQUEST['filterfield']) : '', isset($_REQUEST['filtervalue']) ? preg_split('/\\s*:\\s*/', $_REQUEST['filtervalue']) : '', isset($_REQUEST['status']) ? preg_split('/\\s*:\\s*/', $_REQUEST['status']) : '', isset($_REQUEST['initial']) ? $_REQUEST['initial'] : '', isset($_REQUEST['exactvalue']) ? preg_split('/\\s*:\\s*/', $_REQUEST['exactvalue']) : '', $filter);
            if (isset($items['data'][0]['itemId'])) {
                $_REQUEST['cant'] = $items['cant'];
                $_REQUEST['itemId'] = $items['data'][0]['itemId'];
            }
        }
        if (!empty($_REQUEST['itemId']) && $tiki_p_tracker_vote_ratings == 'y' && $user) {
            $hasVoted = false;
            foreach ($allfields['data'] as $f) {
                if ($f['type'] == 's' && $definition->isEnabled('useRatings') && ($f['name'] == 'Rating' || ($f['name'] = tra('Rating')))) {
                    $i = $f['fieldId'];
                    if (isset($_REQUEST["ins_{$i}"]) && ($_REQUEST["ins_{$i}"] == 'NULL' || in_array($_REQUEST["ins_{$i}"], explode(',', $tracker_info['ratingOptions'])))) {
                        $trklib->replace_rating($trackerId, $_REQUEST['itemId'], $i, $user, $_REQUEST["ins_{$i}"]);
                        $hasVoted = true;
                    }
                } elseif ($f['type'] == '*' || $f['type'] == 'STARS') {
                    $i = $f['fieldId'];
                    if (isset($_REQUEST["ins_{$i}"])) {
                        $trklib->replace_star($_REQUEST["ins_{$i}"], $trackerId, $_REQUEST['itemId'], $f, $user);
                        $hasVoted = true;
                    }
                }
            }
            if ($hasVoted) {
                // Must strip NULL for remove my vote case
                $url = preg_replace('/[(\\?)|&]vote=y/', '$1', preg_replace('/[(\\?)|&]ins_[0-9]+=-?[0-9|N|U|L]*/', '$1', $_SERVER['REQUEST_URI']));
                // reduce duplicate itemIds in query string
                $occurences = preg_match_all('/[(\\?)|&]itemId=[0-9]+/', $url, $matches);
                if ($params['list_mode'] == 'y' && $occurences > 0) {
                    $url = preg_replace('/[(\\?)|&]itemId=[0-9]+/', '$1', $url, $occurences);
                } elseif ($occurences > 1) {
                    $url = preg_replace('/&itemId=[0-9]+/', '', $url, $occurences - 1);
                }
                header("Location: {$url}");
                die;
            }
        }
        if (!empty($showwatch) && $showwatch == 'y' && $prefs['feature_user_watches'] == 'y' && $tiki_p_watch_trackers == 'y' && !empty($user)) {
            if (isset($_REQUEST['watch']) && isset($_REQUEST['trackerId']) && $_REQUEST['trackerId'] == $trackerId) {
                if ($_REQUEST['watch'] == 'add') {
                    $tikilib->add_user_watch($user, 'tracker_modified', $trackerId, 'tracker', $tracker_info['name'], "tiki-view_tracker.php?trackerId=" . $trackerId);
                } elseif ($_REQUEST['watch'] == 'stop') {
                    $tikilib->remove_user_watch($user, 'tracker_modified', $trackerId, 'tracker');
                }
            }
            if ($tikilib->user_watches($user, 'tracker_modified', $trackerId, 'tracker')) {
                $smarty->assign('user_watching_tracker', 'y');
            } else {
                $smarty->assign('user_watching_tracker', 'n');
            }
        } else {
            $smarty->clear_assign('user_watching_tracker');
        }
        if (empty($showrss) || $showrss == 'n') {
            $smarty->assign('showrss', 'n');
        } else {
            $smarty->assign('showrss', 'y');
        }
        if (empty($listfields)) {
            foreach ($allfields['data'] as $f) {
                $listfields[] = $f['fieldId'];
            }
        }
        if (!empty($popup)) {
            $popupfields = $popup;
        } else {
            $popupfields = array();
        }
        $smarty->assign_by_ref('tracker_info', $tracker_info);
        //$query_array = array();
        //$quarray = array();
        //TikiLib::parse_str($_SERVER['QUERY_STRING'],$query_array);
        if (isset($stickypopup) && $stickypopup == 'y') {
            $stickypopup = true;
        } else {
            $stickypopup = false;
        }
        $smarty->assign_by_ref('stickypopup', $stickypopup);
        if (!isset($showtitle)) {
            $showtitle = 'n';
        }
        $smarty->assign_by_ref('showtitle', $showtitle);
        if (!isset($showlinks)) {
            $showlinks = 'n';
        }
        $smarty->assign_by_ref('showlinks', $showlinks);
        if (!isset($showdesc)) {
            $showdesc = 'n';
        }
        $smarty->assign_by_ref('showdesc', $showdesc);
        if (!isset($showinitials)) {
            $showinitials = 'n';
        }
        $smarty->assign_by_ref('showinitials', $showinitials);
        if (!isset($shownbitems)) {
            $shownbitems = 'n';
        }
        $smarty->assign_by_ref('shownbitems', $shownbitems);
        if (!isset($showstatus)) {
            $showstatus = 'n';
        }
        $smarty->assign_by_ref('showstatus', $showstatus);
        if (!isset($showfieldname)) {
            $showfieldname = 'y';
        }
        $smarty->assign_by_ref('showfieldname', $showfieldname);
        if (!isset($showitemrank)) {
            $showitemrank = 'n';
        }
        $smarty->assign_by_ref('showitemrank', $showitemrank);
        if (!isset($showdelete)) {
            $showdelete = 'n';
        }
        $smarty->assign_by_ref('showdelete', $showdelete);
        if (!isset($showpenditem)) {
            $showpenditem = 'n';
        }
        $smarty->assign_by_ref('showpenditem', $showpenditem);
        if (!isset($showcloseitem)) {
            $showcloseitem = 'n';
        }
        $smarty->assign_by_ref('showcloseitem', $showcloseitem);
        if (!isset($showopenitem)) {
            $showopenitem = 'n';
        }
        $smarty->assign_by_ref('showopenitem', $showopenitem);
        if (!isset($showpagination)) {
            $showpagination = 'y';
        }
        $smarty->assign_by_ref('showpagination', $showpagination);
        if (!isset($sortchoice)) {
            $sortchoice = '';
        } else {
            foreach ($sortchoice as $i => $sc) {
                $sc = explode('|', $sc);
                $sortchoice[$i] = array('value' => $sc[0], 'label' => empty($sc[1]) ? $sc[0] : $sc[1]);
            }
        }
        $smarty->assign_by_ref('sortchoice', $sortchoice);
        if (!isset($status)) {
            $status = 'o';
        }
        $tr_status = $status;
        $smarty->assign_by_ref('tr_status', $tr_status);
        if (!isset($list_mode)) {
            $list_mode = 'y';
        }
        $smarty->assign_by_ref('list_mode', $list_mode);
        if (!isset($showcreated)) {
            $showcreated = $tracker_info['showCreated'];
        }
        $smarty->assign_by_ref('showcreated', $showcreated);
        if (!isset($showlastmodif)) {
            $showlastmodif = $tracker_info['showLastModif'];
        }
        $smarty->assign_by_ref('showlastmodif', $showlastmodif);
        if (!isset($showlastmodifby)) {
            $showlastmodifby = $tracker_info['showLastModifBy'];
        }
        $smarty->assign_by_ref('showlastmodifby', $showlastmodifby);
        if (!isset($more)) {
            $more = 'n';
        }
        $smarty->assign_by_ref('more', $more);
        if (!isset($moreurl)) {
            $moreurl = 'tiki-view_tracker.php';
        }
        $smarty->assign_by_ref('moreurl', $moreurl);
        if (!isset($url)) {
            $url = '';
        }
        $smarty->assign_by_ref('url', $url);
        if (!isset($export)) {
            $export = 'n';
        }
        $smarty->assign_by_ref('export', $export);
        if (!empty($ldelim)) {
            $smarty->left_delimiter = $ldelim;
        }
        if (!empty($rdelim)) {
            $smarty->right_delimiter = $rdelim;
        }
        if (isset($checkbox)) {
            $check = array('ix' => -1, 'type' => 'checkbox');
            $cb = explode('/', $checkbox);
            if (isset($cb[0])) {
                $check['fieldId'] = $cb[0];
            }
            if (isset($cb[1])) {
                $check['name'] = $cb[1];
            }
            if (isset($cb[2])) {
                $check['title'] = $cb[2];
            }
            if (isset($cb[3])) {
                $check['submit'] = $cb[3];
            }
            if (isset($cb[4])) {
                $check['action'] = $cb[4];
            }
            if (isset($cb[5])) {
                $check['tpl'] = $cb[5];
            }
            if (isset($cb[6]) && $cb[6] == 'radio') {
                $check['radio'] = 'y';
                $check['type'] = 'radio';
            }
            if (isset($cb[6]) && $cb[6] == 'dropdown') {
                $check['dropdown'] = 'y';
            }
            // is this actually used?
            $smarty->assign_by_ref('checkbox', $check);
        }
        if (isset($_REQUEST["tr_sort_mode{$iTRACKERLIST}"])) {
            $sort_mode = $_REQUEST["tr_sort_mode{$iTRACKERLIST}"];
        } elseif (!isset($sort_mode)) {
            if (!empty($tracker_info['defaultOrderKey'])) {
                if ($tracker_info['defaultOrderKey'] == -1) {
                    $sort_mode = 'lastModif';
                } elseif ($tracker_info['defaultOrderKey'] == -2) {
                    $sort_mode = 'created';
                } elseif ($tracker_info['defaultOrderKey'] == -3) {
                    $sort_mode = 'itemId';
                } else {
                    $sort_mode = 'f_' . $tracker_info['defaultOrderKey'];
                }
                if (isset($tracker_info['defaultOrderDir'])) {
                    $sort_mode .= "_" . $tracker_info['defaultOrderDir'];
                } else {
                    $sort_mode .= "_asc";
                }
            } else {
                $sort_mode = '';
            }
        } elseif ($sort_mode != 'created_asc' && $sort_mode != 'lastModif_asc' && $sort_mode != 'created_desc' && $sort_mode != 'lastModif_desc' && !preg_match('/f_[0-9]+_(asc|desc)/', $sort_mode)) {
            return tra('Incorrect param') . ' sort_mode';
        }
        $tr_sort_mode = $sort_mode;
        $smarty->assign_by_ref('tr_sort_mode', $tr_sort_mode);
        if (!isset($max)) {
            $max = $prefs['maxRecords'];
        }
        if (isset($_REQUEST["tr_offset{$iTRACKERLIST}"]) && (!isset($forceoffset) || $forceoffset == 'n')) {
            $tr_offset = $_REQUEST["tr_offset{$iTRACKERLIST}"];
        } else {
            if (isset($offset) && $offset >= 0) {
                $tr_offset = $offset;
            } else {
                $tr_offset = 0;
            }
        }
        $smarty->assign_by_ref("tr_offset{$iTRACKERLIST}", $tr_offset);
        $tr_initial = '';
        if ($showinitials == 'y') {
            if (isset($_REQUEST['tr_initial'])) {
                //$query_array['tr_initial'] = $_REQUEST['tr_initial'];
                $tr_initial = $_REQUEST['tr_initial'];
            }
            $smarty->assign('initials', explode(' ', 'a b c d e f g h i j k l m n o p q r s t u v w x y z'));
        }
        $smarty->assign_by_ref('tr_initial', $tr_initial);
        if (isset($view) && $view == 'user' || isset($view_user) || isset($_REQUEST['tr_user'])) {
            if ($f = $definition->getAuthorField()) {
                $filterfield[] = $f;
                $filtervalue[] = '';
                if (!isset($_REQUEST['tr_user'])) {
                    $exactvalue[] = isset($view) ? empty($user) ? 'Anonymous' : $user : $view_user;
                } else {
                    $exactvalue[] = $_REQUEST['tr_user'];
                    $smarty->assign_by_ref('tr_user', $exactvalue);
                }
                if ($definition->isEnabled('writerCanModify') or $definition->isEnabled('userCanSeeOwn')) {
                    $skip_status_perm_check = true;
                }
            }
        }
        if (isset($view) && $view == 'page' && isset($_REQUEST['page'])) {
            if ($f = $trklib->get_page_field($trackerId)) {
                $filterfield[] = $f['fieldId'];
                $filtervalue[] = '';
                $exactvalue[] = $_REQUEST['page'];
            }
        }
        if (isset($view) && $view == 'ip') {
            if ($f = $definition->getAuthorIpField()) {
                $filterfield[] = $f;
                $filtervalue[] = '';
                $ip = $tikilib->get_ip_address();
                $exactvalue[] = $ip;
            }
        }
        if (!isset($filtervalue)) {
            $filtervalue = '';
        } else {
            foreach ($filtervalue as $i => $f) {
                if ($f == '#user') {
                    $filtervalue[$i] = $user;
                } else {
                    if ($f == '#default_group') {
                        $filtervalue[$i] = $_SESSION['u_info']['group'];
                    }
                }
            }
        }
        if (!isset($exactvalue)) {
            $exactvalue = '';
        } else {
            foreach ($exactvalue as $i => $f) {
                if ($f == '#user') {
                    $exactvalue[$i] = $user;
                }
            }
        }
        if (!empty($_REQUEST['itemId']) && (empty($ignoreRequestItemId) || $ignoreRequestItemId != 'y')) {
            $itemId = $_REQUEST['itemId'];
        }
        if (isset($itemId)) {
            if (is_string($itemId) && strstr($itemId, ':')) {
                // JB Tiki7: This doesn't quite make sense as itemId is an array
                $itemId = explode(':', $itemId);
                //			 Probably just some redundant code TOKIL
            }
            $filter['tti.`itemId`'] = $itemId;
        }
        $newItemRateField = false;
        $status_types = $trklib->status_types();
        $smarty->assign('status_types', $status_types);
        if (!isset($filterfield)) {
            $filterfield = '';
        } else {
            if (!empty($filterfield)) {
                if (!empty($filtervalue)) {
                    $fvs = $filtervalue;
                    unset($filtervalue);
                    for ($i = 0, $count_ff = count($filterfield); $i < $count_ff; ++$i) {
                        $filtervalue[] = isset($fvs[$i]) ? $fvs[$i] : '';
                    }
                }
                if (!empty($exactvalue)) {
                    $evs = $exactvalue;
                    unset($exactvalue);
                    for ($i = 0, $count_ff2 = count($filterfield); $i < $count_ff2; ++$i) {
                        if (isset($evs[$i])) {
                            if (is_array($evs[$i])) {
                                // already processed
                                $exactvalue[] = $evs[$i];
                            } elseif (preg_match('/(not)?categories\\(([0-9]+)\\)/', $evs[$i], $matches)) {
                                $categlib = TikiLib::lib('categ');
                                if (ctype_digit($matches[2]) && $matches[2] > 0) {
                                    $cfilter = array('identifier' => $matches[2], 'type' => 'descendants');
                                } else {
                                    $cfilter = NULL;
                                }
                                $categs = $categlib->getCategories($cfilter, true, false);
                                $l = array($matches[2]);
                                foreach ($categs as $cat) {
                                    $l[] = $cat['categId'];
                                }
                                if (empty($matches[1])) {
                                    $exactvalue[] = $l;
                                } else {
                                    $exactvalue[] = array('not' => $l);
                                }
                            } elseif (preg_match('/(not)?preference\\((.*)\\)/', $evs[$i], $matches)) {
                                if (empty($matches[1])) {
                                    $exactvalue[] = $prefs[$matches[2]];
                                } else {
                                    $exactvalue[] = array('not' => $prefs[$matches[2]]);
                                }
                            } elseif (preg_match('/(not)?field\\(([0-9]+)(,([0-9]+|user)(,([0-9]+))?)?\\)/', $evs[$i], $matches)) {
                                // syntax field(fieldId, user, trackerId) or field(fieldId)(need the REQUEST['itemId'] or field(fieldId, itemId) or field(fieldId, user)
                                if (empty($matches[4]) && !empty($_REQUEST['itemId'])) {
                                    // user the itemId of the url
                                    $matches[4] = $_REQUEST['itemId'];
                                }
                                if (!empty($matches[4]) && $matches[4] == 'user') {
                                    if (!empty($matches[6])) {
                                        // pick the user item of this tracker
                                        $t_i = $trklib->get_tracker($matches[6]);
                                        $matches[4] = $trklib->get_user_item($matches[6], $t_i, $user);
                                    } elseif ($prefs['userTracker'] == 'y') {
                                        //pick the generic user tracker
                                        $utid = $userlib->get_tracker_usergroup($user);
                                        $matches[4] = $trklib->get_item_id($utid['usersTrackerId'], $utid['usersFieldId'], $user);
                                    }
                                }
                                if (!empty($matches[4])) {
                                    $l = $trklib->get_item_value(0, $matches[4], $matches[2]);
                                    $field = $trklib->get_tracker_field($matches[2]);
                                    if ($field['type'] == 'r') {
                                        $refItemId = $l;
                                        $l = $trklib->get_item_value($field['options_array'][0], $refItemId, $field['options_array'][3]);
                                    }
                                }
                                if (empty($matches[1])) {
                                    $exactvalue[] = $l;
                                } else {
                                    $exactvalue[] = array('not' => $l);
                                }
                            } elseif (preg_match('/(less|greater|lessequal|greaterequal)\\((.+)\\)/', $evs[$i], $matches)) {
                                $conv = array('less' => '<', 'greater' => '>', 'lessequal' => '<=', 'greaterequal' => '>=');
                                $field = $trklib->get_tracker_field($filterfield[$i]);
                                if ($field['type'] == 'f' || $field['type'] == 'j') {
                                    if ($matches[2] == 'now') {
                                        $matches[2] = $tikilib->now;
                                    } elseif (($r = strtotime($matches[2])) !== false) {
                                        $matches[2] = $r;
                                    }
                                }
                                $exactvalue[] = array($conv[$matches[1]] => $matches[2]);
                            } elseif (preg_match('/not\\((.+)\\)/', $evs[$i], $matches)) {
                                $exactvalue[] = array('not' => $matches[1]);
                            } else {
                                $exactvalue[] = $evs[$i];
                            }
                        } else {
                            $exactvalue[] = '';
                        }
                    }
                }
            }
        }
        if ($tiki_p_admin_trackers != 'y' && $perms['tiki_p_view_trackers'] != 'y' && ($definition->isEnabled('writerCanModify') or $definition->isEnabled('userCanSeeOwn')) && $user && $userCreatorFieldId) {
            //patch this should be in list_items
            if ($filterfield != $userCreatorFieldId || is_array($filterfield) && !in_array(${$userCreatorFieldId}, $filterfield)) {
                if (is_array($filterfield)) {
                    $filterfield[] = $userCreatorFieldId;
                } elseif (empty($filterfield)) {
                    $filterfield = $userCreatorFieldId;
                } else {
                    $filterfield = array($filterfield, $fieldId);
                }
                if (is_array($exactvalue)) {
                    $exactvalue[] = $user;
                } elseif (empty($exactvalue)) {
                    $exactvalue = $user;
                } else {
                    $exactvalue = array($exactvalue, $user);
                }
            }
        }
        if ($tiki_p_admin_trackers != 'y' && $perms['tiki_p_view_trackers'] != 'y' && $user && $groupCreatorFieldId) {
            if ($filterfield != $groupCreatorFieldId || is_array($filterfield) && !in_array($groupCreatorFieldId, $filterfield)) {
                $groups = $userlib->get_user_groups($user);
                if (is_array($filterfield)) {
                    $filterfield[] = $groupCreatorFieldId;
                } elseif (empty($filterfield)) {
                    $filterfield = $groupCreatorFieldId;
                } else {
                    $filterfield = array($filterfield, $fieldId);
                }
                if (is_array($exactvalue)) {
                    $exactvalue[] = array_merge($exactvalue, $groups);
                } elseif (empty($exactvalue)) {
                    $exactvalue = $groups;
                } else {
                    $exactvalue = array_merge(array($exactvalue), $groups);
                }
                global $group;
                // awful trick - but the filter garantee that the group is ok
                $smarty->assign_by_ref('ours', $group);
                $perms = array_merge($perms, $trklib->get_special_group_tracker_perm($tracker_info));
            }
        }
        for ($i = 0, $count_allf = count($allfields['data']); $i < $count_allf; $i++) {
            if ($allfields['data'][$i]['type'] == 'C') {
                $infoComputed = $trklib->get_computed_info($allfields['data'][$i]['options_array'][0], $trackerId, $allfields['data']);
                if (!empty($infoComputed)) {
                    $allfields['data'][$i] = array_merge($infoComputed, $allfields['data'][$i]);
                }
            } elseif ($allfields["data"][$i]['type'] == 'w') {
                /* keep track of dynamic list items referring to user selectors */
                $refFieldId = $allfields["data"][$i]['options_array'][3];
                $refField = $trklib->get_tracker_field($refFieldId);
                if ($refField['type'] == 'u') {
                    $allfields["data"][$i]['type'] = $refField['type'];
                }
            }
            // If listfields is a colon separated string, convert it to an array
            if (!is_array($listfields)) {
                $listfields = explode(':', $listfields);
            }
            if ((in_array($allfields["data"][$i]['fieldId'], $listfields) or in_array($allfields["data"][$i]['fieldId'], $popupfields)) and $allfields["data"][$i]['isPublic'] == 'y') {
                $passfields["{$allfields["data"][$i]['fieldId']}"] = $allfields["data"][$i];
            }
            if (isset($check['fieldId']) && $allfields["data"][$i]['fieldId'] == $check['fieldId']) {
                $passfields["{$allfields["data"][$i]['fieldId']}"] = $allfields["data"][$i];
                if (!in_array($allfields["data"][$i]['fieldId'], $listfields)) {
                    $allfields["data"][$i]['isPublic'] == 'n';
                }
                //don't show it
                $check['ix'] = count($passfields) - 1;
            }
            if ($allfields["data"][$i]['name'] == 'page' && empty($filterfield) && empty($displayList) && !empty($view) && $view == 'page') {
                $filterfield = $allfields["data"][$i]['fieldId'];
                $filtervalue = $_REQUEST['page'];
            }
            if ($definition->isEnabled('useRatings') and $allfields["data"][$i]['type'] == 's' and $allfields["data"][$i]['name'] == 'Rating') {
                $newItemRateField = $allfields["data"][$i]['fieldId'];
            }
        }
        $nonPublicFieldsWarning = '';
        if ($tiki_p_edit === 'y') {
            foreach ($allfields['data'] as $field) {
                if ($field['isPublic'] !== 'y' && in_array($field['fieldId'], array_merge($listfields, $popupfields))) {
                    $nonPublicFieldsWarning = tra('You have attempted to view data of a tracker field which is not public. You need to ask the admin to change the setting to public for this field.');
                }
            }
        }
        if ($editableall == 'y') {
            $editable = $listfields;
        }
        $smarty->assign('nonPublicFieldsWarning', $nonPublicFieldsWarning);
        $smarty->assign_by_ref('filterfield', $filterfield);
        $smarty->assign_by_ref('filtervalue', $filtervalue);
        $smarty->assign_by_ref('fields', $passfields);
        $smarty->assign_by_ref('exactvalue', $exactvalue);
        $smarty->assign_by_ref('listfields', $listfields);
        $smarty->assign_by_ref('popupfields', $popupfields);
        $smarty->assign('editableFields', $editable);
        if (!empty($filterfield)) {
            $urlquery['filterfield'] = is_array($filtervalue) ? implode(':', $filterfield) : $filterfield;
            if (!is_array($filtervalue)) {
                $filtervalue = array($filtervalue);
            }
            $urlquery['filtervalue'] = is_array($filtervalue) ? implode(':', $filtervalue) : $filtervalue;
            $urlquery['exactvalue'] = is_array($exactvalue) ? implode(':', $exactvalue) : $exactvalue;
            $urlquery['trackerId'] = $trackerId;
            $smarty->assign('urlquery', $urlquery);
        } else {
            $smarty->assign('urlquery', '');
        }
        if (!empty($export) && $export != 'n' && $perms['tiki_p_export_tracker'] == 'y') {
            $smarty->loadPlugin('smarty_function_service');
            $exportParams = array('controller' => 'tracker', 'action' => 'export', 'trackerId' => $trackerId);
            if (!empty($fields)) {
                $exportParams['displayedFields'] = is_array($fields) ? implode(':', $fields) : $fields;
            }
            if (is_array($filterfield)) {
                foreach ($filterfield as $i => $fieldId) {
                    $exportParams["f_{$fieldId}"] = empty($filtervalue[$i]) ? $exactvalue[$i] : $filtervalue[$i];
                }
            } elseif (!empty($filterfield)) {
                $exportParams["f_{$filterfield}"] = empty($filtervalue) ? $exactvalue : $filtervalue;
            }
            $exportUrl = smarty_function_service($exportParams, $smarty);
            $smarty->assign('exportUrl', $exportUrl);
        }
        if (!empty($_REQUEST['delete'])) {
            $itemToDelete = Tracker_Item::fromId($_REQUEST['delete']);
            if ($itemToDelete->canRemove()) {
                $trklib->remove_tracker_item($_REQUEST['delete']);
            }
            if (!empty($urlafterdelete)) {
                header("Location: {$urlafterdelete}");
                exit;
            }
        }
        if (!empty($_REQUEST['closeitem'])) {
            $itemToModify = Tracker_Item::fromId($_REQUEST['closeitem']);
            if ($itemToModify->canModify()) {
                $trklib->change_status(array(array('itemId' => $_REQUEST['closeitem'])), 'c');
            }
        }
        if (!empty($_REQUEST['penditem'])) {
            $itemToModify = Tracker_Item::fromId($_REQUEST['penditem']);
            if ($itemToModify->canModify()) {
                $trklib->change_status(array(array('itemId' => $_REQUEST['penditem'])), 'p');
            }
        }
        if (!empty($_REQUEST['openitem'])) {
            $itemToModify = Tracker_Item::fromId($_REQUEST['openitem']);
            if ($itemToModify->canModify()) {
                $trklib->change_status(array(array('itemId' => $_REQUEST['openitem'])), 'o');
            }
        }
        if (!empty($calendarfielddate)) {
            $calendarlib = TikiLib::lib('calendar');
            $focusDate = empty($_REQUEST['todate']) ? $tikilib->now : $_REQUEST['todate'];
            $focus = $calendarlib->infoDate($focusDate);
            if (!empty($calendardelta)) {
                if ($calendardelta[0] == '-') {
                    $focus = $calendarlib->focusPrevious($focus, str_replace('-', '', $calendardelta));
                } else {
                    $focus = $calendarlib->focusNext($focus, str_replace('+', '', $calendardelta));
                }
            }
            $calendarlib->focusStartEnd($focus, $calendarviewmode, $calendarbeginmonth, $startPeriod, $startNextPeriod);
            $cell = $calendarlib->getTableViewCells($startPeriod, $startNextPeriod, $calendarviewmode, $calendarlib->firstDayofWeek($user));
            if (is_array($filterfield) == false) {
                $filterfield = array($filterfield);
            }
            if (is_array(${$filtervalue}) == false) {
                $filtervalue = array($filtervalue);
            }
            $filterfield[] = $calendarfielddate[0];
            $filtervalue[] = '';
            $exactvalue[] = array('>=' => $startPeriod['date']);
            $filterfield[] = empty($calendarfielddate[1]) ? $calendarfielddate[0] : $calendarfielddate[1];
            $filtervalue[] = '';
            $exactvalue[] = array('<' => $startNextPeriod['date']);
        }
        if (count($passfields)) {
            // Optimization: Group category fields using AND logic indicated by sub-array
            $catfilters = array();
            $catfiltervalue = array();
            $catfilternotvalue = array();
            if (!empty($filterfield)) {
                foreach ($filterfield as $k => $ff) {
                    $filterfieldinfo = $trklib->get_tracker_field($ff);
                    if ($filterfieldinfo['type'] == 'e') {
                        $catfilters[] = $k;
                        if (!empty($filtervalue[$k]) && empty($exactvalue[$k])) {
                            // Some people use filtervalue instead of exactvalue for category filters
                            $exactvalue[$k] = $filtervalue[$k];
                            for ($i = 0; $i < $k; $i++) {
                                if (!isset($exactvalue[$i])) {
                                    $exactvalue[$i] = '';
                                }
                            }
                        }
                        if (array_key_exists('not', array($exactvalue[$k]))) {
                            $catfilternotfield[0] = $ff;
                            $catfilternotvalue[] = array($exactvalue[$k]);
                        } else {
                            $catfilterfield[0] = $ff;
                            $catfiltervalue[] = array($exactvalue[$k]);
                        }
                    }
                }
            }
            if ($catfilters) {
                foreach ($catfilters as $cf) {
                    unset($filterfield[$cf]);
                    unset($exactvalue[$cf]);
                }
                if ($catfiltervalue) {
                    // array_merge is used because it reindexes
                    $filterfield = array_merge($filterfield, $catfilterfield);
                    $exactvalue = array_merge($exactvalue, array($catfiltervalue));
                }
                if ($catfilternotvalue) {
                    $filterfield = array_merge($filterfield, $catfilternotfield);
                    $exactvalue[] = array('not' => $catfilternotvalue);
                }
            }
            // End Optimization
            //fetch tracker items
            $items = $trklib->list_items($trackerId, $tr_offset, $max, $tr_sort_mode, $passfields, !empty($calendarfielddate) ? null : $filterfield, $filtervalue, $tr_status, $tr_initial, $exactvalue, $filter, $allfields, $skip_status_perm_check);
            /*** tablesorter ***/
            if ($tsOn && !$tsAjax) {
                // when using serverside filtering check wether a dropdown is in use
                // and we must take params from tracker definition because no explicit options have been defined
                if ($tsServer) {
                    //format from plugin: type:text|type:dropdown;option:1=Open;option:2=Closed|type:text|type:nofilter|type:nofilter|type:nofilter
                    if (!empty($tsfilters) && strpos($tsfilters, 'dropdown') !== false) {
                        $tsfiltersArray = explode('|', $tsfilters);
                        $adjustCol = isset($showstatus) && $showstatus == 'y' && $definition->isEnabled('showStatus') ? -1 : 0;
                        foreach ($tsfiltersArray as $col => &$tsfilterField) {
                            // only consider dropdown definitions without explicit option
                            if (strpos($tsfilterField, 'dropdown') !== false && strpos($tsfilterField, 'option') === false) {
                                //content from options (json object): {"options":["1=Open"," 2=Closed]} - note there can be whitespaces - it should not but there can be - yet another fix required
                                if ($allfields['data'][$col + $adjustCol]['type'] == 'd') {
                                    $options = $allfields['data'][$col + $adjustCol]['options'];
                                    $options = json_decode($options);
                                    $options = $options->options;
                                    // construct the new dropdown filterfield entry from the trackerfield definition
                                    $newTsfilterField = 'type:dropdown';
                                    foreach ($options as $option) {
                                        $newTsfilterField .= ";option:" . trim($option);
                                    }
                                    // update field - note that we used a ref
                                    $tsfilterField = $newTsfilterField;
                                }
                            }
                        }
                        // update tsfilters
                        $tsfilters = implode('|', $tsfiltersArray);
                    }
                }
                $ts_id = 'wptrackerlist' . $trackerId . '-' . $iTRACKERLIST;
                $ts = new Table_Plugin();
                $ts->setSettings($ts_id, isset($server) ? $server : null, $sortable, isset($sortList) ? $sortList : null, isset($tsortcolumns) ? $tsortcolumns : null, isset($tsfilters) ? $tsfilters : null, isset($tsfilteroptions) ? $tsfilteroptions : null, isset($tspaginate) ? $tspaginate : null, isset($tscolselect) ? $tscolselect : null, $GLOBALS['requestUri'], $items['cant'], isset($tstotals) ? $tstotals : null, isset($tstotalformat) ? $tstotalformat : null, isset($tstotaloptions) ? $tstotaloptions : null);
                //loads the jquery tablesorter code
                if (is_array($ts->settings)) {
                    $ts->settings['ajax']['offset'] = 'tr_offset' . $iTRACKERLIST;
                    Table_Factory::build('PluginWithAjax', $ts->settings);
                }
            }
            //determine whether totals will be added to bottom of table
            if (isset($ts->settings)) {
                Table_Totals::setTotals($ts->settings);
            }
            //handle certain tablesorter sorts
            if (isset($sortcol) && $items['cant'] > 1) {
                $fieldtype = $items['data'][0]['field_values'][$sortcol + $adjustCol]['type'];
                //convert categoryId sort to category name sort when tablesorter server side sorting is used
                if ($fieldtype === 'e') {
                    foreach ($items['data'] as $key => $record) {
                        $catfield = $record['field_values'][$sortcol + $adjustCol];
                        $sortarray[$key] = $catfield['list'][$catfield['value']]['name'];
                    }
                    //sort status
                } elseif ($adjustCol === -1 && $sortcol === 0) {
                    $sortarray = array_column($items['data'], 'status');
                }
                array_multisort($sortarray, $dir == '_desc' ? SORT_DESC : SORT_ASC, $items['data']);
            }
            /*** end second tablesorter section ***/
            if (isset($silent) && $silent == 'y' && empty($items['cant'])) {
                return;
            }
            if (isset($items['cant']) && $items['cant'] == 1 && isset($goIfOne) && ($goIfOne == 'y' || $goIfOne == 1)) {
                header('Location: tiki-view_tracker_item.php?itemId=' . $items['data'][0]['itemId'] . '&amp;trackerId=' . $items['data'][0]['trackerId']);
                die;
            }
            if ($newItemRateField && !empty($items['data'])) {
                foreach ($items['data'] as $f => $v) {
                    $items['data'][$f]['my_rate'] = $tikilib->get_user_vote("tracker." . $trackerId . '.' . $items['data'][$f]['itemId'], $user);
                }
            }
            if (!empty($items['data']) && ($definition->isEnabled('useComments') && $definition->isEnabled('showComments') || $definition->isEnabled('showLastComment'))) {
                foreach ($items['data'] as $itkey => $oneitem) {
                    if ($definition->isEnabled('showComments')) {
                        $items['data'][$itkey]['comments'] = $trklib->get_item_nb_comments($items['data'][$itkey]['itemId']);
                    }
                    if ($definition->isEnabled('showLastComment')) {
                        $l = $trklib->list_last_comments($items['data'][$itkey]['trackerId'], $items['data'][$itkey]['itemId'], 0, 1);
                        $items['data'][$itkey]['lastComment'] = !empty($l['cant']) ? $l['data'][0] : '';
                    }
                }
            }
            if (!empty($items['data']) && ($definition->isEnabled('useAttachments') && $definition->isEnabled('showAttachments'))) {
                foreach ($items["data"] as $itkey => $oneitem) {
                    $res = $trklib->get_item_nb_attachments($items["data"][$itkey]['itemId']);
                    $items["data"][$itkey]['attachments'] = $res['attachments'];
                }
            }
            if (!empty($compute) && !empty($items['data'])) {
                $fs = preg_split('/ *: */', $compute);
                foreach ($fs as $fieldId) {
                    if (strstr($fieldId, "/")) {
                        list($fieldId, $oper) = preg_split('/ *\\/ */', $fieldId);
                        $oper = strtolower($oper);
                        if ($oper == 'average') {
                            $oper = 'avg';
                        } elseif ($oper != 'sum' && $oper != 'avg') {
                            $oper = 'sum';
                        }
                    } else {
                        $oper = 'sum';
                    }
                    foreach ($items['data'] as $i => $item) {
                        foreach ($item['field_values'] as $field) {
                            if ($field['fieldId'] == $fieldId) {
                                if (preg_match('/^ *$/', $field['value']) || !is_numeric($field['value'])) {
                                    $amount[$i] = '0';
                                } else {
                                    $amount[$i] = $field['value'];
                                }
                                break;
                            }
                        }
                    }
                    $value = array_sum($amount);
                    if ($oper == 'avg') {
                        $value = round($value / count($amount));
                    }
                    $computedFields[$fieldId][] = array_merge(array('computedtype' => 'n', 'operator' => $oper, 'value' => $value), $passfields[$fieldId]);
                }
                $smarty->assign_by_ref('computedFields', $computedFields);
            } else {
                $smarty->assign('computedFields', '');
            }
            if (!empty($calendarfielddate)) {
                foreach ($items['data'] as $i => $item) {
                    if (!empty($wiki)) {
                        $smarty->assign('fields', $item['field_values']);
                        $smarty->assign('item', $item);
                        $smarty->assign('wiki', "wiki:{$wiki}");
                        $smarty->assign('showpopup', 'n');
                        $items['data'][$i]['over'] = $smarty->fetch('tracker_pretty_item.tpl');
                    }
                    if (!empty($tplwiki)) {
                        $smarty->assign('fields', $item['field_values']);
                        $smarty->assign('item', $item);
                        $smarty->assign('wiki', "tplwiki:{$tplwiki}");
                        $smarty->assign('showpopup', 'n');
                        $items['data'][$i]['over'] = $smarty->fetch('tracker_pretty_item.tpl');
                    }
                    if (empty($items['data'][$i]['over'])) {
                        $items['data'][$i]['over'] = $trklib->get_isMain_value($trackerId, $item['itemId']);
                    }
                    $items['data'][$i]['visible'] = 'y';
                }
                $trklib->fillTableViewCell($items['data'], $calendarfielddate, $cell);
                $smarty->assign('cell', $cell);
                $smarty->assign('show_calendar_module', 'y');
                $calendarlib->getDayNames($calendarlib->firstDayofWeek($user), $daysnames, $daysnames_abr);
                $smarty->assign('daysnames_abr', $daysnames_abr);
                $smarty->assign('focusmonth', TikiLib::date_format("%m", $focusDate));
                $smarty->assign('module_params', array('viewmode' => 'n', 'showaction' => 'n', 'notitle' => empty($calendartitle) ? 'y' : 'n', 'title' => $calendartitle, 'viewnavbar' => $calendarviewnavbar, 'decorations' => empty($calendartitle) ? 'n' : 'y'));
                $smarty->assign('tpl_module_title', tra($calendartitle));
                $smarty->assign('now', $tikilib->now);
                $smarty->assign('calendarViewMode', $calendarviewmode);
                $smarty->assign('viewmodelink', $calendarviewmode);
                $smarty->assign('viewmode', $calendarviewmode);
                $focus_prev = $calendarlib->focusPrevious($focus, $calendarviewmode);
                $smarty->assign('focus_prev', $focus_prev['date']);
                $focus_next = $calendarlib->focusNext($focus, $calendarviewmode);
                $smarty->assign('focus_next', $focus_next['date']);
                $smarty->assign('daystart', $startPeriod['date']);
                $dayend = $calendarlib->infoDate($startNextPeriod['date'] - 1);
                $smarty->assign('dayend', $dayend['date']);
                $smarty->assign('today', TikiLib::make_time(0, 0, 0, TikiLib::date_format('%m'), TikiLib::date_format('%d'), TikiLib::date_format('%Y')));
                $smarty->assign('sticky_popup', $calendarstickypopup);
                $smarty->assign('calendar_popup', $calendarpopup);
                $smarty->assign('showpopup', 'n');
                $headerlib = TikiLib::lib('header');
                $headerlib->add_cssfile('themes/base_files/feature_css/calendar.css', 20);
                return $smarty->fetch('modules/mod-calendar_new.tpl');
            }
            if (!empty($wiki)) {
                $tpl = "wiki:{$wiki}";
            } elseif (!empty($tplwiki)) {
                $tpl = "tplwiki:{$tplwiki}";
            } elseif (empty($tpl)) {
                $tpl = '';
            }
            if (!empty($tpl)) {
                $smarty->security = true;
            }
            $smarty->assign('tpl', $tpl);
            if (!empty($itemId) && $showpagination == 'y' && !empty($_REQUEST['cant'])) {
                $smarty->assign('max', 1);
                $smarty->assign('count_item', $_REQUEST['cant']);
                $smarty->assign('offset_arg', 'reloff');
                $smarty->assign("tr_offset{$iTRACKERLIST}", $_REQUEST['reloff']);
            } else {
                $smarty->assign_by_ref('max', $max);
                $smarty->assign_by_ref('item_count', $items['cant']);
                $smarty->assign_by_ref('count_item', $items['cant']);
                $smarty->assign('offset_arg', "tr_offset{$iTRACKERLIST}");
            }
            $smarty->assign_by_ref('items', $items["data"]);
            $smarty->assign('daformat', $tikilib->get_long_date_format() . " " . tra("at") . " %H:%M");
            if (!empty($params['showmap']) && $params['showmap'] == 'y') {
                $smarty->assign('trackerlistmapview', true);
                $smarty->assign('trackerlistmapname', "trackerlistmap_{$iTRACKERLIST}");
            } else {
                $smarty->assign('trackerlistmapview', false);
            }
            if (isset($items['data'])) {
                foreach ($items['data'] as $score_item) {
                    $item_info = $trklib->get_tracker_item($score_item['itemId']);
                    $currentItemId = $score_item['itemId'];
                    TikiLib::events()->trigger('tiki.trackeritem.view', array('type' => 'trackeritem', 'object' => $currentItemId, 'owner' => $item_info['createdBy'], 'user' => $GLOBALS['user']));
                }
            }
            $tracker = $trklib->get_tracker($trackerId, 0, -1);
            /*foreach ($query_array as $k=>$v) {
            			if (!is_array($v)) { //only to avoid an error: eliminate the params that are not simple (ex: if you have in the same page a tracker list plugin and a tracker plugin, filling the tracker plugin interfers with the tracker list. In any case this is buggy if two tracker list plugins in the same page and if one needs the query value....
            				$quarray[] = urlencode($k) ."=". urlencode($v);
            			}
            		}
            		if (is_array($quarray)) {
            			$query_string = implode("&amp;",$quarray);
            		} else {
            			$quering_string = '';
            		}
            		$smarty->assign('query_string', $query_string);
            		*/
            if (!$tracker) {
                $smarty->assign('msg', tra("Error in tracker ID"));
                return $smarty->fetch("error_raw.tpl");
            } else {
                $save_fc = null;
                if (!empty($wiki) && $params['force_compile'] === 'y') {
                    // some pretty trackers need to compile fresh for each item
                    $save_fc = $smarty->force_compile;
                    $smarty->force_compile = true;
                }
                //this options preloads the javascript for displaying sheets
                if (!empty($displaysheet) && $displaysheet == 'y') {
                    $headerlib = TikiLib::lib("header");
                    $sheetlib = TikiLib::lib("sheet");
                    $sheetlib->setup_jquery_sheet();
                    $headerlib->add_jq_onready('$("div.trackercontainer").sheet($.extend($.sheet.tikiOptions,{
							editable:false,
							buildSheet: true,
							minSize: {rows: 0, cols: 0}
						}));');
                    $smarty->assign('displaysheet', 'true');
                }
                //this method sets up the sheet just like it would for jquery.sheet, but assumes that the javascript will be handled elsewere
                if (!empty($tableassheet) && $tableassheet == 'y') {
                    $smarty->assign('tableassheet', 'true');
                }
                $smarty->assign('context', $params);
                try {
                    $str = $smarty->fetch('wiki-plugins/wikiplugin_trackerlist.tpl');
                } catch (SmartyException $e) {
                    $str = $e->getMessage();
                }
                if ($save_fc !== null) {
                    $smarty->force_compile = $save_fc;
                    // presumably will be false but put it back anyway
                }
                return $str;
            }
        } else {
            $smarty->assign('msg', tra("No field indicated"));
            return $smarty->fetch("error_raw.tpl");
        }
    }
    return $back;
}
/**
 * @param $mod_reference
 * @param null $params
 * @return bool
 */
function module_since_last_visit_new($mod_reference, $params = null)
{
    global $user;
    $smarty = TikiLib::lib('smarty');
    include_once 'tiki-sefurl.php';
    if (!$user) {
        return false;
    }
    if (!isset($params['use_jquery_ui']) || $params['use_jquery_ui'] != 'y') {
        $smarty->assign('use_jquery_ui', 'n');
    } else {
        $smarty->assign('use_jquery_ui', 'y');
    }
    if (!isset($params['date_as_link']) || $params['date_as_link'] != 'n') {
        $smarty->assign('date_as_link', 'y');
    } else {
        $smarty->assign('date_as_link', 'n');
    }
    if (!isset($params['fold_sections']) || $params['fold_sections'] != 'y') {
        $smarty->assign('default_folding', 'block');
        $smarty->assign('opposite_folding', 'none');
    } else {
        $smarty->assign('default_folding', 'none');
        $smarty->assign('opposite_folding', 'block');
    }
    if (empty($params['commentlength'])) {
        $params['commentlength'] = 40;
    }
    $resultCount = $mod_reference['rows'];
    global $prefs;
    $userlib = TikiLib::lib('user');
    $tikilib = TikiLib::lib('tiki');
    $smarty->loadPlugin('smarty_modifier_username');
    $ret = array();
    if ($params == null) {
        $params = array();
    }
    if ((empty($params['calendar_focus']) || $params['calendar_focus'] != 'ignore') && strpos($_SERVER['SCRIPT_NAME'], 'tiki-calendar.php') !== false && !empty($_REQUEST['todate'])) {
        $last = $_REQUEST['todate'];
        $_SESSION['slvn_last_login'] = $last;
        $smarty->assign('tpl_module_title', tra('Changes since'));
    } else {
        if (isset($_SESSION['slvn_last_login'])) {
            $last = $_SESSION['slvn_last_login'];
            $smarty->assign('tpl_module_title', tra('Changes since'));
        } else {
            $last = $tikilib->getOne('select `lastLogin` from `users_users` where `login`=?', array($user));
            $smarty->assign('tpl_module_title', tra('Since your last visit...'));
            if (!$last || !empty($params['daysAtLeast'])) {
                $now = TikiLib::lib('tiki')->now;
                if (!$last) {
                    $last = $now;
                }
                if (!empty($params['daysAtLeast']) && $now - $last < $params['daysAtLeast'] * 60 * 60 * 24) {
                    $last = $now - $params['daysAtLeast'] * 60 * 60 * 24;
                    $smarty->assign('tpl_module_title', tr('In the last %0 days...', $params['daysAtLeast']));
                }
            }
        }
    }
    $ret['lastLogin'] = $last;
    $ret['items']['comments']['label'] = tra('new comments');
    $ret['items']['comments']['cname'] = 'slvn_comments_menu';
    //TODO: should be a function on commentslib.php or use one of the existent functions
    $query = 'select `object`,`objectType`,`title`,`commentDate`,`userName`,`threadId`, `parentId`, `approved`, `archived`, `data`' . " from `tiki_comments` where `commentDate`>? and `objectType` != 'forum' order by `commentDate` desc";
    $result = $tikilib->query($query, array((int) $last), $resultCount);
    $count = 0;
    while ($res = $result->fetchRow()) {
        $ret['items']['comments']['list'][$count]['href'] = TikiLib::lib('comments')->getHref($res['objectType'], $res['object'], $res['threadId']);
        switch ($res['objectType']) {
            case 'article':
                $perm = 'tiki_p_read_article';
                $ret['items']['comments']['list'][$count]['href'] = filter_out_sefurl($ret['items']['comments']['list'][$count]['href'], 'article', $res['title']);
                break;
            case 'post':
                $perm = 'tiki_p_read_blog';
                $ret['items']['comments']['list'][$count]['href'] = filter_out_sefurl($ret['items']['comments']['list'][$count]['href'], 'blogpost', $res['title']);
                break;
            case 'blog':
                $perm = 'tiki_p_read_blog';
                $ret['items']['comments']['list'][$count]['href'] = filter_out_sefurl($ret['items']['comments']['list'][$count]['href'], 'blog', $res['title']);
                break;
            case 'faq':
                $perm = 'tiki_p_view_faqs';
                break;
            case 'file gallery':
                $perm = 'tiki_p_view_file_gallery';
                break;
            case 'image gallery':
                $perm = 'tiki_p_view_image_gallery';
                break;
            case 'poll':
                // no perm check for viewing polls, only a perm for taking them
                break;
            case 'wiki page':
                $perm = 'tiki_p_view';
                break;
            default:
                // note trackeritme needs more complex perms checking due to status and ownership
                $perm = 'tiki_p_read_comments';
                break;
        }
        if ($res['approved'] == 'n' || $res['archived'] == 'y') {
            $visible = $userlib->user_has_perm_on_object($user, $res['object'], $res['objectType'], 'tiki_p_admin_comments');
        } else {
            if ($res['objectType'] === 'trackeritem') {
                $item = Tracker_Item::fromId($res['object']);
                $visible = $item->canView();
            } else {
                $visible = !isset($perm) || $userlib->user_has_perm_on_object($user, $res['object'], $res['objectType'], $perm);
            }
        }
        if ($visible) {
            $ret['items']['comments']['list'][$count]['title'] = $tikilib->get_short_datetime($res['commentDate']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['userName']);
            $ret['items']['comments']['list'][$count]['label'] = TikiLib::lib('comments')->process_comment_title($res, $params['commentlength']);
            if ($res['archived'] == 'y') {
                $ret['items']['comments']['list'][$count]['label'] .= tra(' (archived)');
            }
            $count++;
        }
    }
    $ret['items']['comments']['count'] = $count;
    /////////////////////////////////////////////////////////////////////////
    // FORUMS
    if ($prefs['feature_forums'] == 'y') {
        $ret['items']['posts']['label'] = tra('new posts');
        $ret['items']['posts']['cname'] = 'slvn_posts_menu';
        $query = 'select `posts`.`object`,`posts`.`objectType`,`posts`.`title`,`posts`.`commentDate`,' . ' `posts`.`userName`,`posts`.`threadId`, `posts`.`parentId`,`topics`.`title` `topic_title`' . ' from `tiki_comments` `posts`' . ' left join `tiki_comments` `topics` ON `posts`.`parentId` = `topics`.`threadId`' . " where `posts`.`commentDate`>? and `posts`.`objectType` = 'forum'" . ' order by `posts`.`commentDate` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['object'], $res['objectType'], 'tiki_p_forum_read')) {
                $ret['items']['posts']['list'][$count]['href'] = 'tiki-view_forum_thread.php?forumId=' . $res['object'] . '&comments_parentId=';
                if ($res['parentId']) {
                    $ret['items']['posts']['list'][$count]['href'] .= $res['parentId'] . '#threadId' . $res['threadId'];
                } else {
                    $ret['items']['posts']['list'][$count]['href'] .= $res['threadId'];
                }
                $ret['items']['posts']['list'][$count]['title'] = $tikilib->get_short_datetime($res['commentDate']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['userName']);
                if ($res['parentId'] == 0 || $prefs['forum_reply_notitle'] != 'y') {
                    $ret['items']['posts']['list'][$count]['label'] = $res['title'];
                } else {
                    $ret['items']['posts']['list'][$count]['label'] = $res['topic_title'];
                }
                ++$count;
            }
        }
        $ret['items']['posts']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // WIKI PAGES
    if ($prefs['feature_wiki'] == 'y') {
        $ret['items']['pages']['label'] = tra('wiki pages changed');
        $ret['items']['pages']['cname'] = 'slvn_pages_menu';
        $query = 'select `pageName`, `user`, `lastModif` from `tiki_pages` where `lastModif`>? order by `lastModif` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['pageName'], 'wiki page', 'tiki_p_view')) {
                $ret['items']['pages']['list'][$count]['href'] = filter_out_sefurl('tiki-index.php?page=' . urlencode($res['pageName']));
                $ret['items']['pages']['list'][$count]['title'] = $tikilib->get_short_datetime($res['lastModif']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['pages']['list'][$count]['label'] = $res['pageName'];
                $count++;
            }
        }
        $ret['items']['pages']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // ARTICLES
    if ($prefs['feature_articles'] == 'y') {
        $ret['items']['articles']['label'] = tra('new articles');
        $ret['items']['articles']['cname'] = 'slvn_articles_menu';
        if ($userlib->user_has_permission($user, 'tiki_p_edit_article')) {
            $query = 'select `articleId`,`title`,`publishDate`,`authorName` from `tiki_articles` where `created`>? and `expireDate`>? order by `articleId` desc';
            $bindvars = array((int) $last, time());
        } else {
            $query = 'select `articleId`,`title`,`publishDate`,`authorName` from `tiki_articles` where `publishDate`>? and `publishDate`<=? and `expireDate`>? order by `articleId` desc';
            $bindvars = array((int) $last, time(), time());
        }
        $result = $tikilib->query($query, $bindvars, $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['articleId'], 'article', 'tiki_p_read_article')) {
                $ret['items']['articles']['list'][$count]['href'] = filter_out_sefurl('tiki-read_article.php?articleId=' . $res['articleId'], 'article', $res['title']);
                $ret['items']['articles']['list'][$count]['title'] = $tikilib->get_short_datetime($res['publishDate']) . ' ' . tra('by') . ' ' . $res['authorName'];
                $ret['items']['articles']['list'][$count]['label'] = $res['title'];
                $count++;
            }
        }
        $ret['items']['articles']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // FAQs
    if ($prefs['feature_faqs'] == 'y') {
        $ret['items']['faqs']['label'] = tra('new FAQs');
        $ret['items']['faqs']['cname'] = 'slvn_faqs_menu';
        $query = 'select `faqId`, `title`, `created` from `tiki_faqs` where `created`>? order by `created` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['faqId'], 'faq', 'tiki_p_view_faq')) {
                $ret['items']['faqs']['list'][$count]['href'] = 'tiki-view_faq.php?faqId=' . $res['faqId'];
                $ret['items']['faqs']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']);
                $ret['items']['faqs']['list'][$count]['label'] = $res['title'];
                $count++;
            }
        }
        $ret['items']['faqs']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // BLOGS
    if ($prefs['feature_blogs'] == 'y') {
        $ret['items']['blogs']['label'] = tra('new blogs');
        $ret['items']['blogs']['cname'] = 'slvn_blogs_menu';
        $query = "select `blogId`, `title`, `user`, `created` from `tiki_blogs` where `created`>? order by `created` desc";
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['blogId'], 'blog', 'tiki_p_read_blog')) {
                $ret['items']['blogs']['list'][$count]['href'] = filter_out_sefurl('tiki-view_blog.php?blogId=' . $res['blogId'], 'blog', $res['title']);
                $ret['items']['blogs']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['blogs']['list'][$count]['label'] = $res['title'];
                $count++;
            }
        }
        $ret['items']['blogs']['count'] = $count;
        $ret['items']['blogPosts']['label'] = tra('new blog posts');
        $ret['items']['blogPosts']['cname'] = 'slvn_blogPosts_menu';
        $query = 'select `postId`, `blogId`, `title`, `user`, `created` from `tiki_blog_posts` where `created`>? order by `created` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['blogId'], 'blog', 'tiki_p_read_blog')) {
                $ret['items']['blogPosts']['list'][$count]['href'] = filter_out_sefurl('tiki-view_blog_post.php?postId=' . $res['postId'], 'blogpost', $res['title']);
                $ret['items']['blogPosts']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['blogPosts']['list'][$count]['label'] = $res['title'];
                $count++;
            }
        }
        $ret['items']['blogPosts']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // IMAGE GALLERIES
    if ($prefs['feature_galleries'] == 'y') {
        // image galleries
        $ret['items']['imageGalleries']['label'] = tra('new image galleries');
        $ret['items']['imageGalleries']['cname'] = 'slvn_imageGalleries_menu';
        $query = "select `galleryId`,`name`,`created`,`user` from `tiki_galleries` where `created`>? order by `created` desc";
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['galleryId'], 'image gallery', 'tiki_p_view_image_gallery')) {
                $ret['items']['imageGalleries']['list'][$count]['href'] = 'tiki-browse_gallery.php?galleryId=' . $res['galleryId'];
                $ret['items']['imageGalleries']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['imageGalleries']['list'][$count]['label'] = $res['name'];
                $count++;
            }
        }
        $ret['items']['imageGalleries']['count'] = $count;
        // images
        $ret['items']['images']['label'] = tra('new images');
        $ret['items']['images']['cname'] = 'slvn_images_menu';
        $query = 'select `imageId`,`galleryId`,`name`,`created`,`user` from `tiki_images` where `created`>? order by `created` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['galleryId'], 'image gallery', 'tiki_p_view_image_gallery')) {
                $ret['items']['images']['list'][$count]['href'] = 'tiki-browse_image.php?galleryId=' . $res['galleryId'] . '&imageId=' . $res['imageId'];
                $ret['items']['images']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['images']['list'][$count]['label'] = $res['name'];
                $count++;
            }
        }
        $ret['items']['images']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // FILE GALLERIES
    if ($prefs['feature_file_galleries'] == 'y') {
        // file galleries
        $ret['items']['fileGalleries']['label'] = tra('new file galleries');
        $ret['items']['fileGalleries']['cname'] = 'slvn_fileGalleries_menu';
        $query = 'select `galleryId`,`name`,`created`,`user` from `tiki_file_galleries` where `created`>? order by `created` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['galleryId'], 'file gallery', 'tiki_p_view_file_gallery')) {
                $ret['items']['fileGalleries']['list'][$count]['href'] = filter_out_sefurl('tiki-list_file_gallery.php?galleryId=' . $res['galleryId'], 'file gallery');
                $ret['items']['fileGalleries']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['fileGalleries']['list'][$count]['label'] = $res['name'];
                $count++;
            }
        }
        $ret['items']['fileGalleries']['count'] = $count;
        // files
        $ret['items']['files']['label'] = tra('new files');
        //get_strings tra('new files');
        $ret['items']['files']['cname'] = 'slvn_files_menu';
        $query = 'select `fileId`, `galleryId`,`name`,`filename`,`created`,`user` from `tiki_files` where `created`>? order by `created` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['galleryId'], 'file gallery', 'tiki_p_view_file_gallery')) {
                $ret['items']['files']['list'][$count]['href'] = filter_out_sefurl('tiki-list_file_gallery.php?galleryId=' . $res['galleryId'] . '&fileId=' . $res['fileId'] . '&view=page', 'file gallery');
                $ret['items']['files']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['files']['list'][$count]['label'] = $res['name'] . ' (' . $res['filename'] . ')';
                $count++;
            }
        }
        $ret['items']['files']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // POLLS
    if ($prefs['feature_polls'] == 'y') {
        $ret['items']['polls']['label'] = tra('new polls');
        $ret['items']['polls']['cname'] = 'slvn_polls_menu';
        $query = 'select `pollId`, `title`, `publishDate` from `tiki_polls` where `publishDate`>? order by `publishDate` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            $ret['items']['polls']['list'][$count]['href'] = 'tiki-poll_results.php?pollId=' . $res['pollId'];
            $ret['items']['polls']['list'][$count]['title'] = $tikilib->get_short_datetime($res['publishDate']);
            $ret['items']['polls']['list'][$count]['label'] = $res['title'];
            $count++;
        }
        $ret['items']['polls']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // NEW USERS
    if (!isset($params['showuser']) || $params['showuser'] != 'n') {
        $ret['items']['users']['label'] = tra('new users');
        $ret['items']['users']['cname'] = 'slvn_users_menu';
        $query = 'select `login`, `registrationDate` from `users_users` where `registrationDate`>? and `provpass`=?';
        $result = $tikilib->query($query, array((int) $last, ''), $resultCount);
        $count = 0;
        $slvn_tmp_href = $userlib->user_has_permission($user, 'tiki_p_admin') ? 'tiki-assignuser.php?assign_user='******'tiki-user_information.php?view_user='******'items']['users']['list'][$count]['href'] = $slvn_tmp_href . rawurlencode($res['login']);
            $ret['items']['users']['list'][$count]['title'] = $tikilib->get_short_datetime($res['registrationDate']);
            $ret['items']['users']['list'][$count]['label'] = smarty_modifier_username($res['login']);
            $count++;
        }
        $ret['items']['users']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // TRACKER ITEMS
    // This breaks out tracker updates into sub-sections, by tracker, separating new items and updated items.
    // NEW TRACKER ITEMS
    if ($prefs['feature_trackers'] == 'y' && (!isset($params['showtracker']) || $params['showtracker'] != 'n')) {
        $ret['items']['trackers']['label'] = tra('new tracker items');
        $ret['items']['trackers']['cname'] = 'slvn_trackers_menu';
        $query = 'select `itemId`, `trackerId`, `created`, `lastModif`  from `tiki_tracker_items` where `created`>? order by `created` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        $counta = array();
        $tracker_name = array();
        $cachelib = TikiLib::lib('cache');
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['trackerId'], 'tracker', 'tiki_p_view_trackers')) {
                // Initialize tracker counter if needed.
                if (!isset($counta[$res['trackerId']])) {
                    $counta[$res['trackerId']] = 0;
                }
                // Pull Tracker Name
                if ($res['trackerId'] > 0 && !isset($tracker_name[$res['trackerId']])) {
                    $query = "select `name` from `tiki_trackers` where `trackerId` = ?";
                    $tracker_name[$res['trackerId']] = $tikilib->getOne($query, $res['trackerId']);
                }
                $ret['items']['trackers']['tid'][$res['trackerId']]['label'] = tra('in') . ' ' . tra($tracker_name[$res['trackerId']]);
                $ret['items']['trackers']['tid'][$res['trackerId']]['cname'] = 'slvn_tracker' . $res['trackerId'] . '_menu';
                $ret['items']['trackers']['tid'][$res['trackerId']]['list'][$counta[$res['trackerId']]]['href'] = filter_out_sefurl('tiki-view_tracker_item.php?itemId=' . $res['itemId'], 'trackeritem');
                $ret['items']['trackers']['tid'][$res['trackerId']]['list'][$counta[$res['trackerId']]]['title'] = $tikilib->get_short_datetime($res['created']);
                // routine to verify field in tracker that's used as label
                $cacheKey = 'trackerItemLabel' . $res['itemId'];
                if (!($label = $cachelib->getCached($cacheKey))) {
                    $query = 'select `fieldId` from `tiki_tracker_fields` where `isMain` = ? and `trackerId` = ? order by `position`';
                    $fieldId = $tikilib->getOne($query, array('y', $res['trackerId']));
                    $query = 'select `value` from `tiki_tracker_item_fields` where `fieldId` = ? and `itemId` = ?';
                    $label = $tikilib->getOne($query, array($fieldId, $res['itemId']));
                    $cachelib->cacheItem($cacheKey, $label);
                }
                // If the label is empty (b:0;), then use the item ID
                if ($label == 'b:0;' || $label == '') {
                    $label = 'Trk i' . $res['trackerId'] . ' - ID: ' . $res['itemId'];
                }
                $ret['items']['trackers']['tid'][$res['trackerId']]['list'][$counta[$res['trackerId']]]['label'] = $label;
                $counta[$res['trackerId']]++;
                $ret['items']['trackers']['tid'][$res['trackerId']]['count'] = $counta[$res['trackerId']];
                $count++;
            }
        }
        $ret['items']['trackers']['count'] = $count;
        /////////////////////////////////////////////////////////////////////////
        // UPDATED TRACKER ITEMS - ignore updates on same day as creation
        $ret['items']['utrackers']['label'] = tra('updated tracker items');
        $ret['items']['utrackers']['cname'] = 'slvn_utrackers_menu';
        $query = 'select `itemId`, `trackerId`, `created`, `lastModif`' . ' from `tiki_tracker_items` where `lastModif`>? and `lastModif`!=`created`' . ' order by `lastModif` desc';
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        $countb = array();
        $cachelib = TikiLib::lib('cache');
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['trackerId'], 'tracker', 'tiki_p_view_trackers')) {
                // Initialize tracker counter if needed.
                if (!isset($countb[$res['trackerId']])) {
                    $countb[$res['trackerId']] = 0;
                }
                // Pull Tracker Name
                if (!isset($tracker_name[$res['trackerId']])) {
                    $query = 'select `name` from `tiki_trackers` where `trackerId` = ?';
                    $tracker_name[$res['trackerId']] = $tikilib->getOne($query, $res['trackerId']);
                }
                $ret['items']['utrackers']['tid'][$res['trackerId']]['label'] = tra('in') . ' ' . tra($tracker_name[$res['trackerId']]);
                $ret['items']['utrackers']['tid'][$res['trackerId']]['cname'] = 'slvn_utracker' . $res['trackerId'] . '_menu';
                $ret['items']['utrackers']['tid'][$res['trackerId']]['list'][$countb[$res['trackerId']]]['href'] = filter_out_sefurl('tiki-view_tracker_item.php?itemId=' . $res['itemId'], 'trackeritem');
                $ret['items']['utrackers']['tid'][$res['trackerId']]['list'][$countb[$res['trackerId']]]['title'] = $tikilib->get_short_datetime($res['lastModif']);
                // routine to verify field in tracker that's used as label
                $cacheKey = 'trackerItemLabel' . $res['itemId'];
                if (!($label = $cachelib->getCached($cacheKey))) {
                    $query = 'select `fieldId` from `tiki_tracker_fields` where `isMain` = ? and `trackerId` = ? order by `position`';
                    $fieldId = $tikilib->getOne($query, array('y', $res['trackerId']));
                    $query = 'select `value` from `tiki_tracker_item_fields` where `fieldId` = ? and `itemId` = ?';
                    $label = $tikilib->getOne($query, array($fieldId, $res['itemId']));
                    $cachelib->cacheItem($cacheKey, $label);
                }
                // If the label is empty (b:0;), then use the item ID
                if ($label == 'b:0;' || $label == '') {
                    $label = 'Trk i' . $res['trackerId'] . ' - ID: ' . $res['itemId'];
                }
                $ret['items']['utrackers']['tid'][$res['trackerId']]['list'][$countb[$res['trackerId']]]['label'] = $label;
                $countb[$res['trackerId']]++;
                $ret['items']['utrackers']['tid'][$res['trackerId']]['count'] = $countb[$res['trackerId']];
                $count++;
            }
        }
        $ret['items']['utrackers']['count'] = $count;
    }
    /////////////////////////////////////////////////////////////////////////
    // CALENDARS & THEIR EVENTS
    if ($prefs['feature_calendar'] == 'y') {
        $ret['items']['calendar']['label'] = tra('new calendars');
        $ret['items']['calendar']['cname'] = 'slvn_calendar_menu';
        $query = "select `calendarId`, `name`, `user`, `created` from `tiki_calendars` where `created`>? order by `created` desc";
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['calendarId'], 'calendar', 'tiki_p_view_calendar')) {
                $ret['items']['calendar']['list'][$count]['href'] = filter_out_sefurl('tiki-calendar.php?calIds[]=' . $res['calendarId'], 'calendar', $res['name']);
                $ret['items']['calendar']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']);
                $ret['items']['calendar']['list'][$count]['label'] = $res['name'];
                $count++;
            }
        }
        $ret['items']['calendar']['count'] = $count;
        $ret['items']['events']['label'] = tra('new events');
        $ret['items']['events']['cname'] = 'slvn_events_menu';
        $query = "select `calitemId`, `calendarId`, `name`, `user`, `created`, `start` from `tiki_calendar_items` where `created`>? order by `created` desc";
        $result = $tikilib->query($query, array((int) $last), $resultCount);
        $count = 0;
        while ($res = $result->fetchRow()) {
            if ($userlib->user_has_perm_on_object($user, $res['calendarId'], 'calendar', 'tiki_p_view_events')) {
                $ret['items']['events']['list'][$count]['href'] = filter_out_sefurl('tiki-calendar_edit_item.php?viewcalitemId=' . $res['calitemId'], 'event', $res['name']);
                $ret['items']['events']['list'][$count]['title'] = $tikilib->get_short_datetime($res['created']) . ' ' . tra('by') . ' ' . smarty_modifier_username($res['user']) . ', ' . tra('starting on') . ' ' . $tikilib->get_short_datetime($res['start']);
                $ret['items']['events']['list'][$count]['label'] = $res['name'];
                $count++;
            }
        }
        $ret['items']['events']['count'] = $count;
    }
    //////////////////////////////////////////////////////////////////////////
    // SUMMARY
    //get the total of items
    $ret['cant'] = 0;
    $ret['nonempty'] = 0;
    foreach ($ret['items'] as $item) {
        $ret['cant'] += $item['count'];
        if ($item['count'] > 0) {
            $ret['nonempty']++;
        }
    }
    if ($ret['nonempty'] > 0) {
        $ret['li_width'] = min(22, (int) 90 / $ret['nonempty']);
    } else {
        $ret['li_width'] = 90;
    }
    $smarty->assign('slvn_info', $ret);
}
Esempio n. 17
0
 private function getApplicablePermissions($type, $objectId)
 {
     switch ($type) {
         case 'trackeritem':
             $item = Tracker_Item::fromId($objectId);
             return $item->getPerms();
         default:
             return Perms::get($type, $objectId);
     }
 }
function wikiplugin_trackerlist($data, $params)
{
    global $smarty, $tikilib, $dbTiki, $userlib, $tiki_p_admin_trackers, $prefs, $_REQUEST, $tiki_p_view_trackers, $user, $page, $tiki_p_tracker_vote_ratings, $tiki_p_tracker_view_ratings, $trklib, $tiki_p_export_tracker, $tiki_p_watch_trackers, $tiki_p_edit;
    require_once "lib/trackers/trackerlib.php";
    global $notificationlib;
    include_once 'lib/notifications/notificationlib.php';
    //needed if plugin tracker after plugin trackerlist
    static $iTRACKERLIST = 0;
    ++$iTRACKERLIST;
    $smarty->assign('iTRACKERLIST', $iTRACKERLIST);
    $default = array('calendarfielddate' => '', 'wiki' => '', 'calendarviewmode' => 'month', 'calendarstickypopup' => 'n', 'calendarbeginmonth' => 'y', 'calendarviewnavbar' => 'y', 'calendartitle' => '', 'calendardelta' => '', 'force_compile' => 'n', 'editable' => array(), 'editableall' => 'n');
    $params = array_merge($default, $params);
    extract($params, EXTR_SKIP);
    $skip_status_perm_check = false;
    if ($prefs['feature_trackers'] != 'y' || !isset($trackerId) || !($tracker_info = $trklib->get_tracker($trackerId))) {
        return $smarty->fetch("wiki-plugins/error_tracker.tpl");
    } else {
        global $auto_query_args;
        $auto_query_args_local = array('trackerId', 'tr_initial', "tr_sort_mode{$iTRACKERLIST}", 'tr_user', 'filterfield', 'filtervalue', 'exactvalue', 'itemId');
        $auto_query_args = empty($auto_query_args) ? $auto_query_args_local : array_merge($auto_query_args, $auto_query_args_local);
        $smarty->assign('listTrackerId', $trackerId);
        $tracker_info = $trklib->get_tracker($trackerId);
        if ($t = $trklib->get_tracker_options($trackerId)) {
            $tracker_info = array_merge($tracker_info, $t);
        }
        if (!isset($sort)) {
            $sort = 'n';
        }
        $perms = $tikilib->get_perm_object($trackerId, 'tracker', $tracker_info, false);
        if ($perms['tiki_p_view_trackers'] != 'y' && !$user) {
            return;
        }
        $userCreatorFieldId = $trklib->get_field_id_from_type($trackerId, 'u', '1%');
        $groupCreatorFieldId = $trklib->get_field_id_from_type($trackerId, 'g', '1%');
        if ($perms['tiki_p_view_trackers'] != 'y' && $tracker_info['writerCanModify'] != 'y' && empty($userCreatorFieldId) && empty($groupCreatorFieldId)) {
            return;
        }
        $smarty->assign_by_ref('perms', $perms);
        global $trklib;
        require_once "lib/trackers/trackerlib.php";
        if (!empty($fields)) {
            $limit = $fields;
        } else {
            $limit = '';
        }
        if ($editableall == 'y') {
            $editable = $fields;
        }
        if (!empty($filterfield) && !empty($limit)) {
            $limit = array_unique(array_merge($limit, $filterfield));
        }
        if (!empty($popup)) {
            $limit = array_unique(array_merge($limit, $popup));
        }
        if (!empty($calendarfielddate)) {
            $limit = array_unique(array_merge($limit, $calendarfielddate));
        }
        if (!empty($limit) && $trklib->test_field_type($limit, array('C'))) {
            $limit = '';
        }
        $allfields = $trklib->list_tracker_fields($trackerId, 0, -1, 'position_asc', '', true, '', $trklib->flaten($limit));
        if (!empty($fields)) {
            $listfields = $fields;
            //We must include the $calendarfielddate, even if they are not in the listfields
            if (!empty($calendarfielddate)) {
                foreach ($calendarfielddate as $f) {
                    if (!in_array($f, $listfields)) {
                        $listfields[] = $f;
                    }
                }
            }
            if ($sort == 'y') {
                $allfields = $trklib->sort_fields($allfields, $listfields);
            }
        } elseif (!empty($wiki) || !empty($tpl) || !empty($tplwiki)) {
            if (!empty($wiki)) {
                $listfields = $trklib->get_pretty_fieldIds($wiki, 'wiki', $outputPretty);
            } elseif (!empty($tplwiki)) {
                $listfields = $trklib->get_pretty_fieldIds($tplwiki, 'wiki', $outputPretty);
            } else {
                $listfields = $trklib->get_pretty_fieldIds($tpl, 'tpl', $outputPretty);
            }
        } else {
            $listfields = '';
        }
        if (!empty($compute) && !empty($listfields)) {
            if (preg_match_all('/[0-9.]+/', $compute, $matches)) {
                foreach ($matches[0] as $f) {
                    if (!in_array($f, $listfields)) {
                        $listfields[] = $f;
                    }
                }
            }
        }
        if (!empty($filterfield)) {
            if (is_array($filterfield)) {
                foreach ($filterfield as $ff) {
                    unset($filterfieldok);
                    if (is_array($ff)) {
                        // already checked in trackerfilter
                        $filterfieldok = true;
                        break;
                    } else {
                        foreach ($allfields['data'] as $f) {
                            if ($f['fieldId'] == $ff) {
                                $filterfieldok = true;
                                break;
                            }
                        }
                    }
                    if (!isset($filterfieldok)) {
                        break;
                    }
                }
            } else {
                foreach ($allfields['data'] as $f) {
                    if ($f['fieldId'] == $filterfield) {
                        $filterfieldok = true;
                        break;
                    }
                }
            }
            if (!isset($filterfieldok)) {
                return tra('incorrect filterfield');
            }
        }
        $filter = array();
        if (isset($periodQuantity)) {
            switch ($periodUnit) {
                case 'hour':
                    $periodUnit = 3600;
                    break;
                case 'day':
                    $periodUnit = 86400;
                    break;
                case 'week':
                    $periodUnit = 604800;
                    break;
                case 'month':
                    $periodUnit = 2628000;
                    break;
                default:
                    break;
            }
            if (!isset($periodType)) {
                $periodType = 'c';
            }
            if (is_int($periodUnit) && $periodType == 'm') {
                $filter['lastModifAfter'] = $tikilib->now - $periodQuantity * $periodUnit;
                $filter['lastModifBefore'] = $tikilib->now;
            } elseif (is_int($periodUnit)) {
                # case for periodType beig c or anything else (therefore, set as case for default)
                $filter['createdAfter'] = $tikilib->now - $periodQuantity * $periodUnit;
                $filter['createdBefore'] = $tikilib->now;
            }
        }
        if (isset($_REQUEST['reloff']) && empty($_REQUEST['itemId']) && !empty($_REQUEST['trackerId'])) {
            //coming from a pagination
            $items = $trklib->list_items($_REQUEST['trackerId'], $_REQUEST['reloff'], 1, '', '', isset($_REQUEST['filterfield']) ? preg_split('/\\s*:\\s*/', $_REQUEST['filterfield']) : '', isset($_REQUEST['filtervalue']) ? preg_split('/\\s*:\\s*/', $_REQUEST['filtervalue']) : '', isset($_REQUEST['status']) ? preg_split('/\\s*:\\s*/', $_REQUEST['status']) : '', isset($_REQUEST['initial']) ? $_REQUEST['initial'] : '', isset($_REQUEST['exactvalue']) ? preg_split('/\\s*:\\s*/', $_REQUEST['exactvalue']) : '', $filter);
            if (isset($items['data'][0]['itemId'])) {
                $_REQUEST['cant'] = $items['cant'];
                $_REQUEST['itemId'] = $items['data'][0]['itemId'];
            }
        }
        if (!empty($_REQUEST['itemId']) && $tiki_p_tracker_vote_ratings == 'y' && $user) {
            $hasVoted = false;
            foreach ($allfields['data'] as $f) {
                if ($f['type'] == 's' && isset($tracker_info['useRatings']) and $tracker_info['useRatings'] == 'y' && ($f['name'] == 'Rating' || ($f['name'] = tra('Rating')))) {
                    $i = $f['fieldId'];
                    if (isset($_REQUEST["ins_{$i}"]) && ($_REQUEST["ins_{$i}"] == 'NULL' || in_array($_REQUEST["ins_{$i}"], explode(',', $tracker_info['ratingOptions'])))) {
                        $trklib->replace_rating($trackerId, $_REQUEST['itemId'], $i, $user, $_REQUEST["ins_{$i}"]);
                        $hasVoted = true;
                    }
                } elseif ($f['type'] == '*' || $f['type'] == 'STARS') {
                    $i = $f['fieldId'];
                    if (isset($_REQUEST["ins_{$i}"])) {
                        $trklib->replace_star($_REQUEST["ins_{$i}"], $trackerId, $_REQUEST['itemId'], $f, $user);
                        $hasVoted = true;
                    }
                }
            }
            if ($hasVoted) {
                // Must strip NULL for remove my vote case
                $url = preg_replace('/[(\\?)|&]vote=y/', '$1', preg_replace('/[(\\?)|&]ins_[0-9]+=-?[0-9|N|U|L]*/', '$1', $_SERVER['REQUEST_URI']));
                // reduce duplicate itemIds in query string
                $occurences = preg_match_all('/[(\\?)|&]itemId=[0-9]+/', $url, $matches);
                if ($params['list_mode'] == 'y' && $occurences > 0) {
                    $url = preg_replace('/[(\\?)|&]itemId=[0-9]+/', '$1', $url, $occurences);
                } elseif ($occurences > 1) {
                    $url = preg_replace('/&itemId=[0-9]+/', '', $url, $occurences - 1);
                }
                header("Location: {$url}");
                die;
            }
        }
        if (!empty($showwatch) && $showwatch == 'y' && $prefs['feature_user_watches'] == 'y' && $tiki_p_watch_trackers == 'y' && !empty($user)) {
            if (isset($_REQUEST['watch']) && isset($_REQUEST['trackerId']) && $_REQUEST['trackerId'] == $trackerId) {
                if ($_REQUEST['watch'] == 'add') {
                    $tikilib->add_user_watch($user, 'tracker_modified', $trackerId, 'tracker', $tracker_info['name'], "tiki-view_tracker.php?trackerId=" . $trackerId);
                } elseif ($_REQUEST['watch'] == 'stop') {
                    $tikilib->remove_user_watch($user, 'tracker_modified', $trackerId, 'tracker');
                }
            }
            if ($tikilib->user_watches($user, 'tracker_modified', $trackerId, 'tracker')) {
                $smarty->assign('user_watching_tracker', 'y');
            } else {
                $smarty->assign('user_watching_tracker', 'n');
            }
        } else {
            $smarty->clear_assign('user_watching_tracker');
        }
        if (empty($showrss) || $showrss == 'n') {
            $smarty->assign('showrss', 'n');
        } else {
            $smarty->assign('showrss', 'y');
        }
        if (empty($listfields)) {
            foreach ($allfields['data'] as $f) {
                $listfields[] = $f['fieldId'];
            }
        }
        if (!empty($popup)) {
            $popupfields = $popup;
        } else {
            $popupfields = array();
        }
        if ($t = $trklib->get_tracker_options($trackerId)) {
            $tracker_info = array_merge($tracker_info, $t);
        }
        $smarty->assign_by_ref('tracker_info', $tracker_info);
        //$query_array = array();
        //$quarray = array();
        //TikiLib::parse_str($_SERVER['QUERY_STRING'],$query_array);
        if (isset($stickypopup) && $stickypopup == 'y') {
            $stickypopup = true;
        } else {
            $stickypopup = false;
        }
        $smarty->assign_by_ref('stickypopup', $stickypopup);
        if (!isset($showtitle)) {
            $showtitle = 'n';
        }
        $smarty->assign_by_ref('showtitle', $showtitle);
        if (!isset($showlinks)) {
            $showlinks = 'n';
        }
        $smarty->assign_by_ref('showlinks', $showlinks);
        if (!isset($showdesc)) {
            $showdesc = 'n';
        }
        $smarty->assign_by_ref('showdesc', $showdesc);
        if (!isset($showinitials)) {
            $showinitials = 'n';
        }
        $smarty->assign_by_ref('showinitials', $showinitials);
        if (!isset($shownbitems)) {
            $shownbitems = 'n';
        }
        $smarty->assign_by_ref('shownbitems', $shownbitems);
        if (!isset($showstatus)) {
            $showstatus = 'n';
        }
        $smarty->assign_by_ref('showstatus', $showstatus);
        if (!isset($showfieldname)) {
            $showfieldname = 'y';
        }
        $smarty->assign_by_ref('showfieldname', $showfieldname);
        if (!isset($showitemrank)) {
            $showitemrank = 'n';
        }
        $smarty->assign_by_ref('showitemrank', $showitemrank);
        if (!isset($showdelete)) {
            $showdelete = 'n';
        }
        $smarty->assign_by_ref('showdelete', $showdelete);
        if (!isset($showpenditem)) {
            $showpenditem = 'n';
        }
        $smarty->assign_by_ref('showpenditem', $showpenditem);
        if (!isset($showcloseitem)) {
            $showcloseitem = 'n';
        }
        $smarty->assign_by_ref('showcloseitem', $showcloseitem);
        if (!isset($showopenitem)) {
            $showopenitem = 'n';
        }
        $smarty->assign_by_ref('showopenitem', $showopenitem);
        if (!isset($showpagination)) {
            $showpagination = 'y';
        }
        $smarty->assign_by_ref('showpagination', $showpagination);
        if (!isset($sortchoice)) {
            $sortchoice = '';
        } else {
            foreach ($sortchoice as $i => $sc) {
                $sc = explode('|', $sc);
                $sortchoice[$i] = array('value' => $sc[0], 'label' => empty($sc[1]) ? $sc[0] : $sc[1]);
            }
        }
        $smarty->assign_by_ref('sortchoice', $sortchoice);
        if (!isset($status)) {
            $status = 'o';
        }
        $tr_status = $status;
        $smarty->assign_by_ref('tr_status', $tr_status);
        if (!isset($list_mode)) {
            $list_mode = 'y';
        }
        $smarty->assign_by_ref('list_mode', $list_mode);
        if (!isset($showcreated)) {
            $showcreated = $tracker_info['showCreated'];
        }
        $smarty->assign_by_ref('showcreated', $showcreated);
        if (!isset($showlastmodif)) {
            $showlastmodif = $tracker_info['showLastModif'];
        }
        $smarty->assign_by_ref('showlastmodif', $showlastmodif);
        if (!isset($more)) {
            $more = 'n';
        }
        $smarty->assign_by_ref('more', $more);
        if (!isset($moreurl)) {
            $moreurl = 'tiki-view_tracker.php';
        }
        $smarty->assign_by_ref('moreurl', $moreurl);
        if (!isset($url)) {
            $url = '';
        }
        $smarty->assign_by_ref('url', $url);
        if (!isset($export)) {
            $export = 'n';
        }
        $smarty->assign_by_ref('export', $export);
        if (!empty($ldelim)) {
            $smarty->left_delimiter = $ldelim;
        }
        if (!empty($rdelim)) {
            $smarty->right_delimiter = $rdelim;
        }
        if (isset($checkbox)) {
            $check = array('ix' => -1, 'type' => 'checkbox');
            $cb = explode('/', $checkbox);
            if (isset($cb[0])) {
                $check['fieldId'] = $cb[0];
            }
            if (isset($cb[1])) {
                $check['name'] = $cb[1];
            }
            if (isset($cb[2])) {
                $check['title'] = $cb[2];
            }
            if (isset($cb[3])) {
                $check['submit'] = $cb[3];
            }
            if (isset($cb[4])) {
                $check['action'] = $cb[4];
            }
            if (isset($cb[5])) {
                $check['tpl'] = $cb[5];
            }
            if (isset($cb[6]) && $cb[6] == 'radio') {
                $check['radio'] = 'y';
                $check['type'] = 'radio';
            }
            if (isset($cb[6]) && $cb[6] == 'dropdown') {
                $check['dropdown'] = 'y';
            }
            // is this actually used?
            $smarty->assign_by_ref('checkbox', $check);
        }
        if (isset($_REQUEST["tr_sort_mode{$iTRACKERLIST}"])) {
            $sort_mode = $_REQUEST["tr_sort_mode{$iTRACKERLIST}"];
        } elseif (!isset($sort_mode)) {
            if (!empty($tracker_info['defaultOrderKey'])) {
                if ($tracker_info['defaultOrderKey'] == -1) {
                    $sort_mode = 'lastModif';
                } elseif ($tracker_info['defaultOrderKey'] == -2) {
                    $sort_mode = 'created';
                } elseif ($tracker_info['defaultOrderKey'] == -3) {
                    $sort_mode = 'itemId';
                } else {
                    $sort_mode = 'f_' . $tracker_info['defaultOrderKey'];
                }
                if (isset($tracker_info['defaultOrderDir'])) {
                    $sort_mode .= "_" . $tracker_info['defaultOrderDir'];
                } else {
                    $sort_mode .= "_asc";
                }
            } else {
                $sort_mode = '';
            }
        } elseif ($sort_mode != 'created_asc' && $sort_mode != 'lastModif_asc' && $sort_mode != 'created_desc' && $sort_mode != 'lastModif_desc' && !preg_match('/f_[0-9]+_(asc|desc)/', $sort_mode)) {
            return tra('Incorrect param') . ' sort_mode';
        }
        $tr_sort_mode = $sort_mode;
        $smarty->assign_by_ref('tr_sort_mode', $tr_sort_mode);
        if (isset($compute)) {
            $max = -1;
            // to avoid confusion compute is on what you see or all the items
        } elseif (!isset($max)) {
            $max = $prefs['maxRecords'];
        }
        if (isset($_REQUEST['tr_offset']) && (!isset($forceoffset) || $forceoffset == 'n')) {
            $tr_offset = $_REQUEST['tr_offset'];
        } else {
            if (isset($offset) && $offset >= 0) {
                $tr_offset = $offset;
            } else {
                $tr_offset = 0;
            }
        }
        $smarty->assign_by_ref('tr_offset', $tr_offset);
        $tr_initial = '';
        if ($showinitials == 'y') {
            if (isset($_REQUEST['tr_initial'])) {
                //$query_array['tr_initial'] = $_REQUEST['tr_initial'];
                $tr_initial = $_REQUEST['tr_initial'];
            }
            $smarty->assign('initials', explode(' ', 'a b c d e f g h i j k l m n o p q r s t u v w x y z'));
        }
        $smarty->assign_by_ref('tr_initial', $tr_initial);
        if (isset($view) && $view == 'user' || isset($view_user) || isset($_REQUEST['tr_user'])) {
            if ($f = $trklib->get_field_id_from_type($trackerId, 'u', '1%')) {
                $filterfield[] = $f;
                $filtervalue[] = '';
                if (!isset($_REQUEST['tr_user'])) {
                    $exactvalue[] = isset($view) ? empty($user) ? 'Anonymous' : $user : $view_user;
                } else {
                    $exactvalue[] = $_REQUEST['tr_user'];
                    $smarty->assign_by_ref('tr_user', $exactvalue);
                }
                if ($tracker_info['writerCanModify'] == 'y') {
                    $skip_status_perm_check = true;
                }
            }
        }
        if (isset($view) && $view == 'page' && isset($_REQUEST['page'])) {
            if (($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'))) {
                $filterfield[] = $f;
                $filtervalue[] = '';
                $exactvalue[] = $_REQUEST['page'];
            }
        }
        if (isset($view) && $view == 'ip') {
            if ($f = $trklib->get_field_id_from_type($trackerId, 'I', '1%')) {
                $filterfield[] = $f;
                $filtervalue[] = '';
                $ip = $tikilib->get_ip_address();
                $exactvalue[] = $ip;
            }
        }
        if (!isset($filtervalue)) {
            $filtervalue = '';
        } else {
            foreach ($filtervalue as $i => $f) {
                if ($f == '#user') {
                    $filtervalue[$i] = $user;
                } else {
                    if ($f == '#default_group') {
                        $filtervalue[$i] = $_SESSION['u_info']['group'];
                    }
                }
            }
        }
        if (!isset($exactvalue)) {
            $exactvalue = '';
        } else {
            foreach ($exactvalue as $i => $f) {
                if ($f == '#user') {
                    $exactvalue[$i] = $user;
                }
            }
        }
        if (!empty($_REQUEST['itemId']) && (empty($ignoreRequestItemId) || $ignoreRequestItemId != 'y')) {
            $itemId = $_REQUEST['itemId'];
        }
        if (isset($itemId)) {
            if (is_string($itemId) && strstr($itemId, ':')) {
                // JB Tiki7: This doesn't quite make sense as itemId is an array
                $itemId = explode(':', $itemId);
                //			 Probably just some redundant code TOKIL
            }
            $filter['tti.`itemId`'] = $itemId;
        }
        $newItemRateField = false;
        $status_types = $trklib->status_types();
        $smarty->assign('status_types', $status_types);
        if (!isset($filterfield)) {
            $filterfield = '';
        } else {
            if (!empty($filterfield)) {
                if (!empty($filtervalue)) {
                    $fvs = $filtervalue;
                    unset($filtervalue);
                    for ($i = 0, $count_ff = count($filterfield); $i < $count_ff; ++$i) {
                        $filtervalue[] = isset($fvs[$i]) ? $fvs[$i] : '';
                    }
                }
                if (!empty($exactvalue)) {
                    $evs = $exactvalue;
                    unset($exactvalue);
                    for ($i = 0, $count_ff2 = count($filterfield); $i < $count_ff2; ++$i) {
                        if (isset($evs[$i])) {
                            if (is_array($evs[$i])) {
                                // already processed
                                $exactvalue[] = $evs[$i];
                            } elseif (preg_match('/(not)?categories\\(([0-9]+)\\)/', $evs[$i], $matches)) {
                                global $categlib;
                                include_once 'lib/categories/categlib.php';
                                if (ctype_digit($matches[2]) && $matches[2] > 0) {
                                    $filter = array('identifier' => $matches[2], 'type' => 'descendants');
                                } else {
                                    $filter = NULL;
                                }
                                $categs = $categlib->getCategories($filter, true, false);
                                $l = array($matches[2]);
                                foreach ($categs as $cat) {
                                    $l[] = $cat['categId'];
                                }
                                if (empty($matches[1])) {
                                    $exactvalue[] = $l;
                                } else {
                                    $exactvalue[] = array('not' => $l);
                                }
                            } elseif (preg_match('/(not)?preference\\((.*)\\)/', $evs[$i], $matches)) {
                                if (empty($matches[1])) {
                                    $exactvalue[] = $prefs[$matches[2]];
                                } else {
                                    $exactvalue[] = array('not' => $prefs[$matches[2]]);
                                }
                            } elseif (preg_match('/(not)?field\\(([0-9]+)(,([0-9]+|user)(,([0-9]+))?)?\\)/', $evs[$i], $matches)) {
                                // syntax field(fieldId, user, trackerId) or field(fieldId)(need the REQUEST['itemId'] or field(fieldId, itemId) or field(fieldId, user)
                                if (empty($matches[4]) && !empty($_REQUEST['itemId'])) {
                                    // user the itemId of the url
                                    $matches[4] = $_REQUEST['itemId'];
                                }
                                if (!empty($matches[4]) && $matches[4] == 'user') {
                                    if (!empty($matches[6])) {
                                        // pick the user item of this tracker
                                        $t_i = $trklib->get_tracker($matches[6]);
                                        $matches[4] = $trklib->get_user_item($matches[6], $t_i, $user);
                                    } elseif ($prefs['userTracker'] == 'y') {
                                        //pick the generic user tracker
                                        global $userlib;
                                        $utid = $userlib->get_tracker_usergroup($user);
                                        $matches[4] = $trklib->get_item_id($utid['usersTrackerId'], $utid['usersFieldId'], $user);
                                    }
                                }
                                if (!empty($matches[4])) {
                                    $l = $trklib->get_item_value(0, $matches[4], $matches[2]);
                                    $field = $trklib->get_tracker_field($matches[2]);
                                    if ($field['type'] == 'r') {
                                        $refItemId = $l;
                                        $l = $trklib->get_item_value($field['options_array'][0], $refItemId, $field['options_array'][3]);
                                    }
                                }
                                if (empty($matches[1])) {
                                    $exactvalue[] = $l;
                                } else {
                                    $exactvalue[] = array('not' => $l);
                                }
                            } elseif (preg_match('/(less|greater|lessequal|greaterequal)\\((.+)\\)/', $evs[$i], $matches)) {
                                $conv = array('less' => '<', 'greater' => '>', 'lessequal' => '<=', 'greaterequal' => '>=');
                                $field = $trklib->get_tracker_field($filterfield[$i]);
                                if ($field['type'] == 'f' || $field['type'] == 'j') {
                                    if ($matches[2] == 'now') {
                                        $matches[2] = $tikilib->now;
                                    } elseif (($r = strtotime($matches[2])) !== false) {
                                        $matches[2] = $r;
                                    }
                                }
                                $exactvalue[] = array($conv[$matches[1]] => $matches[2]);
                            } elseif (preg_match('/not\\((.+)\\)/', $evs[$i], $matches)) {
                                $exactvalue[] = array('not' => $matches[1]);
                            } else {
                                $exactvalue[] = $evs[$i];
                            }
                        } else {
                            $exactvalue[] = '';
                        }
                    }
                }
            }
        }
        if ($tiki_p_admin_trackers != 'y' && $perms['tiki_p_view_trackers'] != 'y' && $tracker_info['writerCanModify'] == 'y' && $user && $userCreatorFieldId) {
            //patch this should be in list_items
            if ($filterfield != $userCreatorFieldId || is_array($filterfield) && !in_array(${$userCreatorFieldId}, $filterfield)) {
                if (is_array($filterfield)) {
                    $filterfield[] = $userCreatorFieldId;
                } elseif (empty($filterfield)) {
                    $filterfield = $userCreatorFieldId;
                } else {
                    $filterfield = array($filterfield, $fieldId);
                }
                if (is_array($exactvalue)) {
                    $exactvalue[] = $user;
                } elseif (empty($exactvalue)) {
                    $exactvalue = $user;
                } else {
                    $exactvalue = array($exactvalue, $user);
                }
            }
        }
        if ($tiki_p_admin_trackers != 'y' && $perms['tiki_p_view_trackers'] != 'y' && $user && $groupCreatorFieldId) {
            if ($filterfield != $groupCreatorFieldId || is_array($filterfield) && !in_array($groupCreatorFieldId, $filterfield)) {
                $groups = $userlib->get_user_groups($user);
                if (is_array($filterfield)) {
                    $filterfield[] = $groupCreatorFieldId;
                } elseif (empty($filterfield)) {
                    $filterfield = $groupCreatorFieldId;
                } else {
                    $filterfield = array($filterfield, $fieldId);
                }
                if (is_array($exactvalue)) {
                    $exactvalue[] = array_merge($exactvalue, $groups);
                } elseif (empty($exactvalue)) {
                    $exactvalue = $groups;
                } else {
                    $exactvalue = array_merge(array($exactvalue), $groups);
                }
                global $group;
                // awful trick - but the filter garantee that the group is ok
                $smarty->assign_by_ref('ours', $group);
                $perms = array_merge($perms, $trklib->get_special_group_tracker_perm($tracker_info));
            }
        }
        for ($i = 0, $count_allf = count($allfields['data']); $i < $count_allf; $i++) {
            if ($allfields['data'][$i]['type'] == 'C') {
                $infoComputed = $trklib->get_computed_info($allfields['data'][$i]['options_array'][0], $trackerId, $allfields['data']);
                if (!empty($infoComputed)) {
                    $allfields['data'][$i] = array_merge($infoComputed, $allfields['data'][$i]);
                }
            } elseif ($allfields["data"][$i]['type'] == 'w') {
                /* keep track of dynamic list items referring to user selectors */
                $refFieldId = $allfields["data"][$i]['options_array'][3];
                $refField = $trklib->get_tracker_field($refFieldId);
                if ($refField['type'] == 'u') {
                    $allfields["data"][$i]['type'] = $refField['type'];
                }
            }
            if ((in_array($allfields["data"][$i]['fieldId'], $listfields) or in_array($allfields["data"][$i]['fieldId'], $popupfields)) and $allfields["data"][$i]['isPublic'] == 'y') {
                $passfields["{$allfields["data"][$i]['fieldId']}"] = $allfields["data"][$i];
            }
            if (isset($check['fieldId']) && $allfields["data"][$i]['fieldId'] == $check['fieldId']) {
                $passfields["{$allfields["data"][$i]['fieldId']}"] = $allfields["data"][$i];
                if (!in_array($allfields["data"][$i]['fieldId'], $listfields)) {
                    $allfields["data"][$i]['isPublic'] == 'n';
                }
                //don't show it
                $check['ix'] = count($passfields) - 1;
            }
            if ($allfields["data"][$i]['name'] == 'page' && empty($filterfield) && empty($displayList) && !empty($view) && $view == 'page') {
                $filterfield = $allfields["data"][$i]['fieldId'];
                $filtervalue = $_REQUEST['page'];
            }
            if (isset($tracker_info['useRatings']) and $tracker_info['useRatings'] == 'y' and $allfields["data"][$i]['type'] == 's' and $allfields["data"][$i]['name'] == 'Rating') {
                $newItemRateField = $allfields["data"][$i]['fieldId'];
            }
        }
        $nonPublicFieldsWarning = '';
        if ($tiki_p_edit === 'y') {
            foreach ($allfields['data'] as $field) {
                if ($field['isPublic'] !== 'y' && in_array($field['fieldId'], array_merge($listfields, $popupfields))) {
                    $nonPublicFieldsWarning = tra('You have attempted to view data of a tracker field which is not public. You need to ask the admin to change the setting to public for this field.');
                }
            }
        }
        $smarty->assign('nonPublicFieldsWarning', $nonPublicFieldsWarning);
        $smarty->assign_by_ref('filterfield', $filterfield);
        $smarty->assign_by_ref('filtervalue', $filtervalue);
        $smarty->assign_by_ref('fields', $passfields);
        $smarty->assign_by_ref('exactvalue', $exactvalue);
        $smarty->assign_by_ref('listfields', $listfields);
        $smarty->assign_by_ref('popupfields', $popupfields);
        $smarty->assign('editableFields', $editable);
        if (!empty($filterfield)) {
            $urlquery['filterfield'] = is_array($filtervalue) ? implode(':', $filterfield) : $filterfield;
            if (!is_array($filtervalue)) {
                $filtervalue = array($filtervalue);
            }
            $urlquery['filtervalue'] = is_array($filtervalue) ? implode(':', $filtervalue) : $filtervalue;
            $urlquery['exactvalue'] = is_array($exactvalue) ? implode(':', $exactvalue) : $exactvalue;
            $urlquery['trackerId'] = $trackerId;
            $smarty->assign('urlquery', $urlquery);
        } else {
            $smarty->assign('urlquery', '');
        }
        if (!empty($export) && $export != 'n' && $perms['tiki_p_export_tracker'] == 'y') {
            $smarty->loadPlugin('smarty_function_service');
            $exportParams = array('controller' => 'tracker', 'action' => 'export', 'trackerId' => $trackerId);
            if (!empty($fields)) {
                $exportParams['displayedFields'] = is_array($fields) ? implode(':', $fields) : $fields;
            }
            if (is_array($filterfield)) {
                foreach ($filterfield as $i => $fieldId) {
                    $exportParams["f_{$fieldId}"] = empty($filtervalue[$i]) ? $exactvalue[$i] : $filtervalue[$i];
                }
            } elseif (!empty($filterfield)) {
                $exportParams["f_{$filterfield}"] = empty($filtervalue) ? $exactvalue : $filtervalue;
            }
            $exportUrl = smarty_function_service($exportParams, $smarty);
            $smarty->assign('exportUrl', $exportUrl);
        }
        if (!empty($_REQUEST['delete'])) {
            $itemToDelete = Tracker_Item::fromId($_REQUEST['delete']);
            if ($itemToDelete->canRemove()) {
                $trklib->remove_tracker_item($_REQUEST['delete']);
            }
            if (!empty($urlafterdelete)) {
                header("Location: {$urlafterdelete}");
                exit;
            }
        }
        if (!empty($_REQUEST['closeitem'])) {
            $itemToModify = Tracker_Item::fromId($_REQUEST['closeitem']);
            if ($itemToModify->canModify()) {
                $trklib->change_status(array(array('itemId' => $_REQUEST['closeitem'])), 'c');
            }
        }
        if (!empty($_REQUEST['penditem'])) {
            $itemToModify = Tracker_Item::fromId($_REQUEST['penditem']);
            if ($itemToModify->canModify()) {
                $trklib->change_status(array(array('itemId' => $_REQUEST['penditem'])), 'p');
            }
        }
        if (!empty($_REQUEST['openitem'])) {
            $itemToModify = Tracker_Item::fromId($_REQUEST['openitem']);
            if ($itemToModify->canModify()) {
                $trklib->change_status(array(array('itemId' => $_REQUEST['openitem'])), 'o');
            }
        }
        if (!empty($calendarfielddate)) {
            global $calendarlib;
            include_once 'lib/calendar/calendarlib.php';
            $focusDate = empty($_REQUEST['todate']) ? $tikilib->now : $_REQUEST['todate'];
            $focus = $calendarlib->infoDate($focusDate);
            if (!empty($calendardelta)) {
                if ($calendardelta[0] == '-') {
                    $focus = $calendarlib->focusPrevious($focus, str_replace('-', '', $calendardelta));
                } else {
                    $focus = $calendarlib->focusNext($focus, str_replace('+', '', $calendardelta));
                }
            }
            $calendarlib->focusStartEnd($focus, $calendarviewmode, $calendarbeginmonth, $startPeriod, $startNextPeriod);
            $cell = $calendarlib->getTableViewCells($startPeriod, $startNextPeriod, $calendarviewmode, $calendarlib->firstDayofWeek($user));
            if (is_array($filterfield) == false) {
                $filterfield = array($filterfield);
            }
            if (is_array(${$filtervalue}) == false) {
                $filtervalue = array($filtervalue);
            }
            $filterfield[] = $calendarfielddate[0];
            $filtervalue[] = '';
            $exactvalue[] = array('>=' => $startPeriod['date']);
            $filterfield[] = empty($calendarfielddate[1]) ? $calendarfielddate[0] : $calendarfielddate[1];
            $filtervalue[] = '';
            $exactvalue[] = array('<' => $startNextPeriod['date']);
        }
        if (count($passfields)) {
            // Optimization: Group category fields using AND logic indicated by sub-array
            $catfilters = array();
            $catfiltervalue = array();
            $catfilternotvalue = array();
            if (!empty($filterfield)) {
                foreach ($filterfield as $k => $ff) {
                    $filterfieldinfo = $trklib->get_tracker_field($ff);
                    if ($filterfieldinfo['type'] == 'e') {
                        $catfilters[] = $k;
                        if (!empty($filtervalue[$k]) && empty($exactvalue[$k])) {
                            // Some people use filtervalue instead of exactvalue for category filters
                            $exactvalue[$k] = $filtervalue[$k];
                            for ($i = 0; $i < $k; $i++) {
                                if (!isset($exactvalue[$i])) {
                                    $exactvalue[$i] = '';
                                }
                            }
                        }
                        if (array_key_exists('not', array($exactvalue[$k]))) {
                            $catfilternotfield[0] = $ff;
                            $catfilternotvalue[] = array($exactvalue[$k]);
                        } else {
                            $catfilterfield[0] = $ff;
                            $catfiltervalue[] = array($exactvalue[$k]);
                        }
                    }
                }
            }
            if ($catfilters) {
                foreach ($catfilters as $cf) {
                    unset($filterfield[$cf]);
                    unset($exactvalue[$cf]);
                }
                if ($catfiltervalue) {
                    // array_merge is used because it reindexes
                    $filterfield = array_merge($filterfield, $catfilterfield);
                    $exactvalue = array_merge($exactvalue, array($catfiltervalue));
                }
                if ($catfilternotvalue) {
                    $filterfield = array_merge($filterfield, $catfilternotfield);
                    $exactvalue[] = array('not' => $catfilternotvalue);
                }
            }
            // End Optimization
            $items = $trklib->list_items($trackerId, $tr_offset, $max, $tr_sort_mode, $passfields, !empty($calendarfielddate) ? null : $filterfield, $filtervalue, $tr_status, $tr_initial, $exactvalue, $filter, $allfields, $skip_status_perm_check);
            if (isset($silent) && $silent == 'y' && empty($items['cant'])) {
                return;
            }
            if ($items['cant'] == 1 && isset($goIfOne) && ($goIfOne == 'y' || $goIfOne == 1)) {
                header('Location: tiki-view_tracker_item.php?itemId=' . $items['data'][0]['itemId'] . '&amp;trackerId=' . $items['data'][0]['trackerId']);
                die;
            }
            if ($newItemRateField && !empty($items['data'])) {
                foreach ($items['data'] as $f => $v) {
                    $items['data'][$f]['my_rate'] = $tikilib->get_user_vote("tracker." . $trackerId . '.' . $items['data'][$f]['itemId'], $user);
                }
            }
            if ($tracker_info['useComments'] == 'y' && $tracker_info['showComments'] == 'y') {
                foreach ($items['data'] as $itkey => $oneitem) {
                    $items['data'][$itkey]['comments'] = $trklib->get_item_nb_comments($items['data'][$itkey]['itemId']);
                }
            }
            if ($tracker_info['useAttachments'] == 'y' && $tracker_info['showAttachments'] == 'y') {
                foreach ($items["data"] as $itkey => $oneitem) {
                    $res = $trklib->get_item_nb_attachments($items["data"][$itkey]['itemId']);
                    $items["data"][$itkey]['attachments'] = $res['attachments'];
                }
            }
            if (!empty($compute) && !empty($items['data'])) {
                $fs = preg_split('/ *: */', $compute);
                foreach ($fs as $fieldId) {
                    if (strstr($fieldId, "/")) {
                        list($fieldId, $oper) = preg_split('/ *\\/ */', $fieldId);
                        $oper = strtolower($oper);
                        if ($oper == 'average') {
                            $oper = 'avg';
                        } elseif ($oper != 'sum' && $oper != 'avg') {
                            $oper = 'sum';
                        }
                    } else {
                        $oper = 'sum';
                    }
                    foreach ($items['data'] as $i => $item) {
                        foreach ($item['field_values'] as $field) {
                            if ($field['fieldId'] == $fieldId) {
                                if (preg_match('/^ *$/', $field['value']) || !is_numeric($field['value'])) {
                                    $amount[$i] = '0';
                                } else {
                                    $amount[$i] = $field['value'];
                                }
                                break;
                            }
                        }
                    }
                    $value = array_sum($amount);
                    if ($oper == 'avg') {
                        $value = round($value / count($amount));
                    }
                    $computedFields[$fieldId][] = array_merge(array('computedtype' => 'n', 'operator' => $oper, 'value' => $value), $passfields[$fieldId]);
                }
                $smarty->assign_by_ref('computedFields', $computedFields);
            } else {
                $smarty->assign('computedFields', '');
            }
            if (!empty($calendarfielddate)) {
                foreach ($items['data'] as $i => $item) {
                    if (!empty($wiki)) {
                        $smarty->assign('fields', $item['field_values']);
                        $smarty->assign('item', $item);
                        $smarty->assign('wiki', "wiki:{$wiki}");
                        $smarty->assign('showpopup', 'n');
                        $items['data'][$i]['over'] = $smarty->fetch('tracker_pretty_item.tpl');
                    }
                    if (!empty($tplwiki)) {
                        $smarty->assign('fields', $item['field_values']);
                        $smarty->assign('item', $item);
                        $smarty->assign('wiki', "tplwiki:{$tplwiki}");
                        $smarty->assign('showpopup', 'n');
                        $items['data'][$i]['over'] = $smarty->fetch('tracker_pretty_item.tpl');
                    }
                    if (empty($items['data'][$i]['over'])) {
                        $items['data'][$i]['over'] = $trklib->get_isMain_value($trackerId, $item['itemId']);
                    }
                    $items['data'][$i]['visible'] = 'y';
                }
                $trklib->fillTableViewCell($items['data'], $calendarfielddate, $cell);
                $smarty->assign('cell', $cell);
                $smarty->assign('show_calendar_module', 'y');
                $calendarlib->getDayNames($calendarlib->firstDayofWeek($user), $daysnames, $daysnames_abr);
                $smarty->assign('daysnames_abr', $daysnames_abr);
                $smarty->assign('focusmonth', TikiLib::date_format("%m", $focusDate));
                $smarty->assign('module_params', array('viewmode' => 'n', 'showaction' => 'n', 'notitle' => empty($calendartitle) ? 'y' : 'n', 'title' => $calendartitle, 'viewnavbar' => $calendarviewnavbar, 'decorations' => empty($calendartitle) ? 'n' : 'y'));
                $smarty->assign('tpl_module_title', tra($calendartitle));
                $smarty->assign('now', $tikilib->now);
                $smarty->assign('calendarViewMode', $calendarviewmode);
                $smarty->assign('viewmodelink', $calendarviewmode);
                $smarty->assign('viewmode', $calendarviewmode);
                $focus_prev = $calendarlib->focusPrevious($focus, $calendarviewmode);
                $smarty->assign('focus_prev', $focus_prev['date']);
                $focus_next = $calendarlib->focusNext($focus, $calendarviewmode);
                $smarty->assign('focus_next', $focus_next['date']);
                $smarty->assign('daystart', $startPeriod['date']);
                $dayend = $calendarlib->infoDate($startNextPeriod['date'] - 1);
                $smarty->assign('dayend', $dayend['date']);
                $smarty->assign('today', TikiLib::make_time(0, 0, 0, TikiLib::date_format('%m'), TikiLib::date_format('%d'), TikiLib::date_format('%Y')));
                $smarty->assign('sticky_popup', $calendarstickypopup);
                $smarty->assign('calendar_popup', $calendarpopup);
                $smarty->assign('showpopup', 'n');
                global $headerlib;
                include_once 'lib/headerlib.php';
                $headerlib->add_cssfile('css/calendar.css', 20);
                return $smarty->fetch('modules/mod-calendar_new.tpl');
            }
            if (!empty($wiki)) {
                $tpl = "wiki:{$wiki}";
            } elseif (!empty($tplwiki)) {
                $tpl = "tplwiki:{$tplwiki}";
            } elseif (empty($tpl)) {
                $tpl = '';
            }
            if (!empty($tpl)) {
                $smarty->security = true;
            }
            $smarty->assign('tpl', $tpl);
            if (!empty($itemId) && $showpagination == 'y' && !empty($_REQUEST['cant'])) {
                $smarty->assign('max', 1);
                $smarty->assign('count_item', $_REQUEST['cant']);
                $smarty->assign('offset_arg', 'reloff');
                $smarty->assign('tr_offset', $_REQUEST['reloff']);
            } else {
                $smarty->assign_by_ref('max', $max);
                $smarty->assign_by_ref('item_count', $items['cant']);
                $smarty->assign_by_ref('count_item', $items['cant']);
                $smarty->assign('offset_arg', 'tr_offset');
            }
            $smarty->assign_by_ref('items', $items["data"]);
            $smarty->assign('daformat', $tikilib->get_long_date_format() . " " . tra("at") . " %H:%M");
            if (!empty($params['googlemap']) && $params['googlemap'] == 'y') {
                $smarty->assign('trackerlistmapview', true);
                $smarty->assign('trackerlistmapname', "trackerlistgmap_{$iTRACKERLIST}");
                // Check for custom bubble text
                $unlimitedallfields = $trklib->list_tracker_fields($trackerId);
                $markerfields = array();
                foreach ($unlimitedallfields["data"] as $f) {
                    if ($f["type"] == 'G' && $f["options_array"][0] == 'y' && !empty($f["options_array"][1])) {
                        $markerfields = explode('|', $f["options_array"][1]);
                        break;
                    }
                }
                // Generate Google map plugin data
                if (!empty($params["googlemapicon"])) {
                    $googlemapicon = $params["googlemapicon"];
                } else {
                    $googlemapicon = '';
                }
                global $gmapobjectarray;
                $gmapobjectarray = array();
                foreach ($items["data"] as $i) {
                    if (!empty($params["url"])) {
                        $href = str_replace('itemId', $i["itemId"], $params["url"]);
                    } else {
                        $href = 'tiki-view_tracker_item.php?itemId=' . $i["itemId"];
                    }
                    $markertext = '';
                    $markertitle = $i["value"];
                    foreach ($markerfields as $k => $m) {
                        foreach ($i["field_values"] as $f) {
                            if ($f["fieldId"] == $m) {
                                if ($k == 0 && !empty($f["value"])) {
                                    $markertitle = preg_replace("/[\r\n|\r|\n]/", "<br />", htmlspecialchars($f["value"]));
                                } elseif (!empty($f["value"])) {
                                    if ($markertext) {
                                        $markertext .= '<br /><br />';
                                    }
                                    $markertext .= preg_replace("/[\r\n|\r|\n]/", "<br />", htmlspecialchars($f["value"]));
                                }
                                break;
                            }
                        }
                    }
                    $gmapobjectarray[] = array('type' => 'trackeritem', 'id' => $i["itemId"], 'title' => $markertitle, 'href' => $href, 'icon' => $googlemapicon, 'text' => $markertext);
                }
            } else {
                $smarty->assign('trackerlistmapview', false);
            }
            if ($prefs['feature_score'] == 'y' && isset($items['data'])) {
                foreach ($items['data'] as $score_item) {
                    $item_info = $trklib->get_tracker_item($score_item['itemId']);
                    $currentItemId = $score_item['itemId'];
                    $tikilib->score_event($user, 'trackeritem_read', $currentItemId);
                    $tikilib->score_event($item_info['createdBy'], 'trackeritem_is_read', "{$user}:{$currentItemId}");
                }
            }
            $tracker = $trklib->get_tracker($trackerId, 0, -1);
            /*foreach ($query_array as $k=>$v) {
            			if (!is_array($v)) { //only to avoid an error: eliminate the params that are not simple (ex: if you have in the same page a tracker list plugin and a tracker plugin, filling the tracker plugin interfers with the tracker list. In any case this is buggy if two tracker list plugins in the same page and if one needs the query value....
            				$quarray[] = urlencode($k) ."=". urlencode($v);
            			}
            		}
            		if (is_array($quarray)) {
            			$query_string = implode("&amp;",$quarray);
            		} else {
            			$quering_string = '';
            		}
            		$smarty->assign('query_string', $query_string);
            		*/
            if (!$tracker) {
                $smarty->assign('msg', tra("Error in tracker ID"));
                return $smarty->fetch("error_raw.tpl");
            } else {
                $save_fc = null;
                if (!empty($wiki) && $params['force_compile'] === 'y') {
                    // some pretty trackers need to compile fresh for each item
                    $save_fc = $smarty->force_compile;
                    $smarty->force_compile = true;
                }
                //this options preloads the javascript for displaying sheets
                if (!empty($displaysheet) && $displaysheet == 'y') {
                    $headerlib = TikiLib::lib("header");
                    $sheetlib = TikiLib::lib("sheet");
                    $sheetlib->setup_jquery_sheet();
                    $headerlib->add_jq_onready('$("div.trackercontainer").sheet($.extend($.sheet.tikiOptions,{
							editable:false,
							buildSheet: true,
							minSize: {rows: 0, cols: 0}
						}));');
                    $smarty->assign('displaysheet', 'true');
                }
                //this method sets up the sheet just like it would for jquery.sheet, but assumes that the javascript will be handled elsewere
                if (!empty($tableassheet) && $tableassheet == 'y') {
                    $smarty->assign('tableassheet', 'true');
                }
                $smarty->assign('context', $params);
                try {
                    $str = $smarty->fetch('wiki-plugins/wikiplugin_trackerlist.tpl');
                } catch (SmartyException $e) {
                    $str = $e->getMessage();
                }
                if ($save_fc !== null) {
                    $smarty->force_compile = $save_fc;
                    // presumably will be false but put it back anyway
                }
                return $str;
            }
        } else {
            $smarty->assign('msg', tra("No field indicated"));
            return $smarty->fetch("error_raw.tpl");
        }
    }
    return $back;
}