1<?php
2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
3//
4// All Rights Reserved. See copyright.txt for details and a complete list of authors.
5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6// $Id$
7
8class Tiki_Formula_Function_TrackerField extends Math_Formula_Function
9{
10	function evaluate($element)
11	{
12		$default = 0;
13		$allowed = [ 'object', 'field' ];
14
15		if ($extra = $element->getExtraValues($allowed)) {
16			$this->error(tr('Unexpected values: %0', implode(', ', $extra)));
17		}
18
19		$object = $element->object;
20
21		if (! $object || count($object) != 2) {
22			$this->error(tra('Item must be provided and contain one argument: type, object-id'));
23		}
24
25		$type = $this->evaluateChild($object[0]);
26		$object = $this->evaluateChild($object[1]);
27
28		$field = $element->field;
29
30		if (! $field || count($field) != 1) {
31			$this->error(tra('Field must be provided and contain one argument: field permanent name'));
32		}
33		$field = $field[0];
34
35		if ($type != 'trackeritem') {
36			return $default;
37		}
38
39		return $this->fetchValue($object, $field, $default);
40	}
41
42	protected function fetchValue($object, $field, $default)
43	{
44		$trklib = TikiLib::lib('trk');
45		$item = $trklib->get_tracker_item($object);
46
47		if (! $item) {
48			return $default;
49		}
50
51		if (! $definition = Tracker_Definition::get($item['trackerId'])) {
52			return $default;
53		}
54
55		if (! $field = $definition->getFieldFromPermName($field)) {
56			return $default;
57		}
58
59		$fieldId = $field['fieldId'];
60
61		if (! isset($item[$fieldId])) {
62			return $default;
63		}
64
65		return $item[$fieldId];
66	}
67}
68