summaryrefslogtreecommitdiff
path: root/view_diary.php
blob: 998338d4c289fbf7d0cdc433078a32b1bff8f5aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php

/**
 * Copyright (c) 2007 Nathan Kinkade
 * 
 * This code is offered under an MIT (X11) license.  For more information
 * about the terms of this license see the file LICENSE included with this
 * software or visit: http://www.opensource.org/licenses/mit-license.php
 */

# include the main site config where various global variables
# and libraries are included
require("config.php");

# the user must be logged in to access this script. if they are
# not then this function will send them back to the index page
loginRequired();

# implement the PRG (Post->Redirect->Get) method here so that
# users can use the back button freely without browser warnings.
if ( isset($_POST['action']) && ($_POST['action'] == "viewDiary") ) {
	# if $_POST['diary'] = "viewAllDiaries" then the user has selected
	# to view a list of all their diaries and not just one particular
	# diary, so we'll forward them to the appropriate page.  this is here
	# because the easiest way to give the user the option to see all their
	# diaries was to simply stick an option in the "Favorites" menu in the
	# left sidebar, and that form directs the user here.
	if ( $_POST['diary'] == "viewAllDiaries" ) {
		header("Location: {$config->_rootUri}/list_diaries");
		exit;
	} else {
		$queryString = "diary={$_POST['diary']}&action=viewDiary";
		header("Location: {$config->_rootUri}/{$config->_thisScript}?$queryString");
		exit;
	}
}

# don't go forward unless a diary was specified
if ( ! isset($_GET['diary']) ) {
	$_SESSION['systemMsg'] = "<span class='msgError'>You must specify a diary.</span>";
	header("{$config->_previousUri}");
	exit;
}

# initialize an array for all diary items
$diaryItems = array();

# initialize an array for the nutrition summary data
$summaryData = array();

$sql = sprintf ("
	SELECT * FROM userDiaries
	WHERE id = '%s' AND user = '%s'
	",
	$_GET['diary'],
	$_SESSION['user']['id']
);
$db->SelectOne($sql);

if ( $db->_rowCount != 1 ) {
	$_SESSION['systemMsg'] = "<span class='msgError'>The specified diary doesn't exist.</span>";
	header("Location: {$config->_previousUri}");
	exit;
} else {
	# add the diary name to the template
	$smarty->assign("diaryDesc", $db->_row['description']);

	# we browse diaries per day.  this is a way to page the data and make it more
	# manageable for people.  we will only show diary entries for the given day.
	# if a day was not submitted, then use the present day.  here we determine
	# which diary items to extract based on timestamp
	if ( isset($_GET['date']) ) {
		list($year,$month,$day) = explode("-", $_GET['date']);
		$startTime = mktime(0, 0, 0, $month, $day, $year);
		# there are 86400 seconds in a day, so just add this total to the
		# startTime, and this should effective cover the entire day
		$endTime = ($startTime + 86400);
		# format the date in the way that the calendar scripts understand
		# so that we can fix the initial date of the calendar
		$smarty->assign("calendarStartDate", "$month/$day/$year");
	} else {
		# use today.
		$startTime = mktime(0, 0, 0);
		# there are 86400 seconds in a day, so just add this total to the
		# startTime, and this should effective cover the entire day
		$endTime = ($startTime + 86400);
		# format the date in the way that the calendar scripts understand
		# so that we can fix the initial date of the calendar
		$smarty->assign("calendarStartDate", date("m/d/Y"));
	}
	
	# get the items associated with the diary for the selected day.
	$sql = sprintf ("
		SELECT * FROM userDiaryItems
		WHERE diary = '%s'
			AND timestamp >= '%s'
			AND timestamp <= '%s'
		ORDER BY timestamp
		",
		$_GET['diary'],
		$startTime,
		$endTime
	);
	$db->Select($sql);

	if ( $db->_rowCount > 0 ) {
		$diaryItems = $db->_rows;
		# figure the first and last years of the diary.  this will be used
		# to restrict which years are displayed on the diary navigation calendar
		$lastIndex = (count($diaryItems) - 1);
		$smarty->assign("firstYear", date("Y", $diaryItems[0]['timestamp']));
		$smarty->assign("lastYear", date("Y", $diaryItems[$lastIndex]['timestamp']));

		$summaryItems = array();

		foreach ( $diaryItems as $key => $diaryItem ) {
			# convert the timestamps to human readable dates
			$date = date("D, M jS, Y,  g:iA", $diaryItem['timestamp']);
			$diaryItems[$key]['date'] = $date;

			# if it happens to be a food or meal then break out the various
			# fields from the data field
			if ( $diaryItem['type'] == "Food" ) {
				list($food, $weight, $quantity, $description) = explode("::", $diaryItem['data']);
				$diaryItems[$key]['description'] = $description;
				$diaryItems[$key]['uri'] = "food=$food&weight=$weight&quantity=$quantity&description=$description&action=viewFood";

				# add the food to the summaryItems array
				$thisFood = array("food" => $food, "weight" => $weight, "quantity" => $quantity);
				$summaryItems[] = $thisFood;
			}

			if ( $diaryItem['type'] == "Meal" ) {
				list($meal, $description) = explode("::", $diaryItem['data']);
				$diaryItems[$key]['description'] = $description;
				$diaryItems[$key]['uri'] = "meal=$meal&description=$description&action=viewMeal";

				# add each food in the meal to the summaryItems array
				$sql = sprintf ("
					SELECT food, weight, quantity
					FROM userMealItems INNER JOIN userMeals
						ON userMealItems.meal = userMeals.id
					WHERE userMeals.id = '%s'
					",
					$meal
				);
				$db->Select($sql);
				if ( $db->_rowCount > 0 ) {
					foreach ( $db->_rows as $row ) {
						$thisFood = array("food" => $row['food'], "weight" => $row['weight'], "quantity" => $row['quantity']);
						$summaryItems[] = $thisFood;
					}
				}
			}

			if ( $diaryItem['type'] == "Note" ) {
				$diaryItems[$key]['description'] = $diaryItems[$key]['data'];

				# while we are looping the records, convert any carriage returns
				# in the data of Notes to <br />s so that the format is how the
				# user entered it into the textarea originally
				$diaryItems[$key]['data'] = preg_replace("/\n/", "<br />", $diaryItems[$key]['data']);
			}

		}

		$smarty->assign("diaryItems", $diaryItems);

		# Begin summary of diary data

		# because this data is tabular with the first column being nutrient names,
		# and because we have no way of knowing beforehand which nutrients each
		# food will add or share in the array, we add every possible nutrient to the
		# main summary data array and setup what is essentially a grid for each
		# nutrient which we will later go plugging in as we loop
		# through each food in the summary. after we have iterated through each of the foods,
		# adding its nutrients to the array, we will eliminate those nutrients with
		# totals of 0.
		# if the user is logged in then only lookup the nutrients they want to see
		# unless they wanted to see all nutrients, else just grab every nutrient
		if ( isLoggedIn() && (! isset($_GET['showall'])) ) {
			$sql = "
				SELECT nutrientDefs.nutr_no, nutrientDefs.units, nutrientDefs.nutrdesc
				FROM nutrientDefs RIGHT JOIN userNutrients
					ON nutrientDefs.nutr_no = userNutrients.nutrient
			";
		} else {
			$sql = "SELECT nutr_no, units, nutrdesc FROM nutrientDefs";
		}
		$db->Select($sql);
		foreach ( $db->_rows as $row ) {
			# setup a few variables regarding the foods
			$summaryData[$row['nutr_no']]['nutrientName'] = $row['nutrdesc'];
			$summaryData[$row['nutr_no']]['units'] = $row['units'];
			$summaryData[$row['nutr_no']]['total'] = 0;
			$summaryData[$row['nutr_no']]['percentDri'] = "--";
		}

		# now step through summaryItems and go adding things to the $summaryData array
		foreach ( $summaryItems as $food ) {
			# do things a little different if the user is logged in
			if ( isLoggedIn() ) {
				# the dris tables only give recommendations for ages 9-100, outside of that
				# we'll just use the average.
				if ( ($_SESSION['user']['age'] >= 9) && ($_SESSION['user']['age'] <= 100) ) {
					$age = $_SESSION['user']['age'];
				} else {
					$age = 0;
				}

				# NOTE: we must also check for and return IS NULL values in the table 'dris'
				# because most nutrients have no DRI and we need to return those as well
				if ( isset($_GET['showall']) ) {
					$smarty->assign("showAllNutrients", true);
					$sql = sprintf ("
						SELECT weights.gm_wgt, weights.amount, weights.msre_desc, nutrientDefs.nutrdesc, nutrientDefs.units,
							nutrientData.ndb_no, nutrientData.nutr_no, nutrientData.nutr_val, dris.dri
						FROM nutrientData LEFT JOIN weights
							ON nutrientData.ndb_no = weights.ndb_no
						LEFT JOIN nutrientDefs 
							ON nutrientData.nutr_no = nutrientDefs.nutr_no
						LEFT JOIN dris
							ON nutrientDefs.nutr_no = dris.nutr_no
						WHERE nutrientData.ndb_no = '%s'
							AND nutrientData.nutr_val > 0
							AND weights.ndb_no = '%s'
							AND weights.seq = '%s'
							AND ((dris.age_begin <= '%s' AND dris.age_end >= '%s') OR dris.id IS NULL)
							AND ((dris.gender = '%s') OR dris.id IS NULL)
						ORDER BY nutrientDefs.sr_order
						",
						$food['food'],
						$food['food'],
						$food['weight'],
						$age,
						$age,
						$_SESSION['user']['gender']
					);
				} else {
					$sql = sprintf ("
						SELECT weights.gm_wgt, weights.amount, weights.msre_desc, nutrientDefs.nutrdesc, nutrientDefs.units,
							nutrientData.ndb_no, nutrientData.nutr_no, nutrientData.nutr_val, dris.dri
						FROM nutrientData LEFT JOIN weights
							ON nutrientData.ndb_no = weights.ndb_no
						LEFT JOIN userNutrients
							ON nutrientData.nutr_no = userNutrients.nutrient
						LEFT JOIN nutrientDefs 
							ON nutrientData.nutr_no = nutrientDefs.nutr_no
						LEFT JOIN dris
							ON nutrientDefs.nutr_no = dris.nutr_no
						WHERE nutrientData.ndb_no = '%s'
							AND nutrientData.nutr_val > 0
							AND weights.ndb_no = '%s'
							AND weights.seq = '%s'
							AND userNutrients.user = '%s'
							AND ((dris.age_begin <= '%s' AND dris.age_end >= '%s') OR dris.id IS NULL)
							AND ((dris.gender = '%s') OR dris.id IS NULL)
						ORDER BY nutrientDefs.sr_order
						",
						$food['food'],
						$food['food'],
						$food['weight'],
						$_SESSION['user']['id'],
						$age,
						$age,
						$_SESSION['user']['gender']
					);
				}
			} else {
				if ( isset($_GET['showall']) ) {
					$smarty->assign("showAllNutrients", true);
					$sql = sprintf ("
						SELECT weights.gm_wgt, weights.amount, weights.msre_desc, nutrientDefs.nutrdesc, nutrientDefs.units,
							nutrientData.ndb_no, nutrientData.nutr_no, nutrientData.nutr_val, dris.dri
						FROM nutrientData LEFT JOIN weights
							ON nutrientData.ndb_no = weights.ndb_no
						LEFT JOIN nutrientDefs 
							ON nutrientData.nutr_no = nutrientDefs.nutr_no
						LEFT JOIN dris
							ON nutrientDefs.nutr_no = dris.nutr_no
						WHERE nutrientData.ndb_no = '%s'
							AND weights.ndb_no = '%s'
							AND weights.seq = '%s'
							AND nutrientData.nutr_val > 0
							AND (dris.gender = 'avg' OR dris.id IS NULL)
						ORDER BY nutrientDefs.sr_order
						",
						$food['food'],
						$food['food'],
						$food['weight']
					);
				} else {
					$sql = sprintf ("
						SELECT weights.gm_wgt, weights.amount, weights.msre_desc, nutrientDefs.nutrdesc, nutrientDefs.units,
							nutrientData.ndb_no, nutrientData.nutr_no, nutrientData.nutr_val, dris.dri
						FROM nutrientData LEFT JOIN weights
							ON nutrientData.ndb_no = weights.ndb_no
						LEFT JOIN nutrientDefs 
							ON nutrientData.nutr_no = nutrientDefs.nutr_no
						LEFT JOIN dris
							ON nutrientDefs.nutr_no = dris.nutr_no
						WHERE nutrientData.ndb_no = '%s'
							AND weights.ndb_no = '%s'
							AND weights.seq = '%s'
							AND nutrientData.nutr_val > 0
							AND nutrientDefs.is_default = '1'
							AND (dris.gender = 'avg' OR dris.id IS NULL)
						ORDER BY nutrientDefs.sr_order
						",
						$food['food'],
						$food['food'],
						$food['weight']
					);
				}
			}
			$db->Select($sql);
			$foodData = $db->_rows;
		
			# this number is the adjustment to each nutrient quantity reflecting
			# the ratio of the base amount relative to the quantity the user
			# selected.  since the value for amount  will be the same
			# for every selected record we just arbitrarily grab the value
			# from the first record in the returned set
			if ( $food['quantity'] ) {
				$factor = $food['quantity']/$foodData[0]['amount'];
			} else {
				$factor = 1;
			}
		
			# step through he results and add a value for nutrientQuantity to the
			# main mealData array based on nutr_no.  if the current nutr_no doesn't
			# exists in the array, then just skip it
			foreach ( $foodData as $nutrient ) {
				# check if this particular nutrient exists in the list of all nutrients
				# that we added earlier, if so, then plug in the data, if not it will
				# stay populated with the '--' that we added at the beginning
				#		if ( array_key_exists($nutrient['nutr_no'], $summaryData) ) {
					$nutrientQuantity = round(($nutrient['nutr_val'] * ($nutrient['gm_wgt']/100) * $factor),1);
		
					# add this amount to the total for this nutrient
					$summaryData[$nutrient['nutr_no']]['total'] += $nutrientQuantity;
		
					# calculate the current %DRI if one exists, based on the current total
					if ( ! empty($nutrient['dri']) ) { 
						$summaryData[$nutrient['nutr_no']]['percentDri'] =
							(round($summaryData[$nutrient['nutr_no']]['total']/$nutrient['dri'],3) * 100);
					}
					#	}
			}
		}
		
		# step through all the nutrients in $summaryData and eliminate all those
		# rows that have a nutrient total of 0, as they are useless
		foreach ( $summaryData as $nutr_no => $nutrient ) {
			if ( $nutrient['total'] == 0 ) {
				unset($summaryData[$nutr_no]);
			}
		}
		
		# if there is any summary data then assign it to the template
		if ( ! empty($summaryData) != 0 ) {
			$smarty->assign("summaryData", $summaryData); 
		}

		# End summary of diary data

	}
}

# grab the various parts.  these sections are not printed to the screen
# but rather dumped into smarty variables that will simply be printed
# in the template, so the order doesn't matter here at the moment
require("header.php");
require("sidebar_left.php");
require("sidebar_right.php");
require("footer.php");

$smarty->display("view_diary.tpl");

?>