summaryrefslogtreecommitdiff
path: root/lib/site.lib.php
blob: e5c457bb052854656079e8ac8a3538d12c209661 (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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<?php

# determine if the user exists in the database and if so then
# set a few session variables indicating such
function validateUser($user, $pass) {

	global $db;
	
	# make sure that these variables are empty and even unset
	if ( isset($_SESSION['auth']) ) {
		unset($_SESSION['auth']);
	}

	# encrypt password with a simple md5 hash
	$md5Password = md5($pass);

	$sql = "
		SELECT * FROM users
		WHERE username = '$user'
			AND password = '$md5Password'
	";
	$db->SelectOne($sql);
	if ( $db->_rowCount == 1 ) {
		# if one record was returned then a user matching the credentials they
		# supplied was found in the database.  give them access.
		$_SESSION['auth']['status'] = "access_granted";
		$_SESSION['auth']['ipaddress'] = $_SERVER['REMOTE_ADDR'];
		
		# dump all the users info into a session var, but unset the
		# value of the password field
		$_SESSION['user'] = $db->_row;
		unset($_SESSION['user']['password']);

		# determine the users age and put it in the session so that we don't have
		# to calculate it over and over again as they view things. 31536000 is the 
		# number of seconds in a year.
		$_SESSION['user']['age'] = floor((time() - $db->_row['birthday'])/31536000);
		return true;
	} else {
		# not a valid user (not found in db)
		$_SESSION['systemMsg'] = "<span class='msgError'>Login incorrect.</span>";
		return false;
	}

}

	##------------------------------------------------------------------##

# a simple function to check if a user is logged in which also verifies
# that the request came from the same IP address as the original login
function isLoggedIn() {

	if (
		isset($_SESSION['auth']) &&
		($_SESSION['auth']['status'] == "access_granted") &&
		($_SESSION['auth']['ipaddress'] == $_SERVER['REMOTE_ADDR'])
	) {
		return true;
	} else {
		return false;
	}

}

	##------------------------------------------------------------------##

# this function will check to see if a user is logged in, and if not will
# redirect the user to the index page with an error.  we could use the
# isLoggedIn() function above directly, but that would require some if/thens
# on the top of each script that required a login and then a rediction too.
# this function just bundles all that into a neat package
function loginRequired() {

	global $config;

	if ( isLoggedIn() ) {
		return true;
	} else {
		header("Location: {$config->_rootUri}/");
		exit;
		return false;
	}

}

	##------------------------------------------------------------------##

# get a food category's name based on that categories id in the database
function getFoodCategoryName($category) {

	global $db;

	$sql = "
		SELECT fdgrp_desc
		FROM foodCats
		WHERE fdgrp_cd = '$category'
	";
	$db->SelectOne($sql);
	if ( $db->_rowCount == 1 ) {
		return $db->_row['fdgrp_desc'];
	} else {
		return false;
	}

}

	##------------------------------------------------------------------##

# get a nutrients description based on that nutrients nutr_no in the database
function getNutrientName($nutrient) {

	global $db;

	$sql = "
		SELECT nutrdesc
		FROM nutrientDefs
		WHERE nutr_no = '$nutrient'
	";
	$db->SelectOne($sql);
	if ( $db->_rowCount == 1 ) {
		return $db->_row['nutrdesc'];
	} else {
		return false;
	}

}

	##------------------------------------------------------------------##

# get any favorite foods based on user id
function getFavoriteFoods($user) {

	global $db;

	# if the user hasn't marked any foods as favorites to
	# show in the left sidebar dropdown, then just grab the
	# first 15, else grab just their favorites
	$sql = "
		SELECT count(*) AS favCount
		FROM userFoods
		WHERE favorite = '1'
	";
	$db->SelectOne($sql);

	if ( $db->_row['favCount'] == "0" ) {
		$sql = "
			SELECT * FROM userFoods
			WHERE user = '$user'
			ORDER BY description
			LIMIT 15
		";
	} else {
		$sql = "
			SELECT * FROM userFoods
			WHERE user = '$user'
				AND favorite = '1'
			ORDER BY description
		";
	}

	$db->Select($sql);
	if ( $db->_rowCount > 0 ) { 
		return $db->_rows;
	} else {
		return false;
	}

}

	##------------------------------------------------------------------##

# get any favorite meals based on user id
function getFavoriteMeals($user) {

	global $db;

	# if the user hasn't marked any meals as favorites to
	# show in the left sidebar dropdown, then just grab the
	# first 15, else grab just their favorites
	$sql = "
		SELECT count(*) AS favCount
		FROM userMeals
		WHERE favorite = '1'
	";
	$db->SelectOne($sql);

	if ( $db->_row['favCount'] == "0" ) {
		$sql = "
			SELECT * FROM userMeals
			WHERE user = '$user'
			ORDER BY description
			LIMIT 15
		";
	} else {
		$sql = "
			SELECT * FROM userMeals
			WHERE user = '$user'
			ORDER BY description
		";
	}

	$db->Select($sql);
	if ( $db->_rowCount > 0 ) { 
		return $db->_rows;
	} else {
		return false;
	}

}

	##------------------------------------------------------------------##

# get all meals based on user id
function getUserMeals($user) {

	global $db;

	$sql = "
		SELECT * FROM userMeals
		WHERE user = '$user'
		ORDER BY description
	";

	$db->Select($sql);
	if ( $db->_rowCount > 0 ) { 
		return $db->_rows;
	} else {
		return false;
	}

}

	##------------------------------------------------------------------##

# get all diaries based on user id
function getUserDiaries($user) {

	global $db;

	$sql = "
		SELECT * FROM userDiaries
		WHERE user = '$user'
		ORDER BY description
	";

	$db->Select($sql);
	if ( $db->_rowCount > 0 ) { 
		return $db->_rows;
	} else {
		return false;
	}

}

	##------------------------------------------------------------------##

# removes an item from the current meal in $_SESSION['currentMeal']
function removeCurrentMealItem($mealItem) {

    $objResponse = new xajaxResponse();

	# remove the selected meal item from the session
	if ( array_key_exists($mealItem, $_SESSION['currentMeal']) ) {
		unset($_SESSION['currentMeal'][$mealItem]);
    	$objResponse->addRemove("currentMealItem-$mealItem");
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgOkay'>The meal item was successfully removed.</span>");
		# if the session is empty then let the user know and remove
		# anything like links to "View meal", "Clear meal", etc.
		if ( count($_SESSION['currentMeal']) == 0 ) {
    		$objResponse->addAssign("divCurrentMeal", "innerHTML", "No items in meal.");
		}
	} else {
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgError'>The specified meal item doesn't exist.</span>");
	}

	return $objResponse;

}

	##------------------------------------------------------------------##

# removes all meal items from the current meal ($_SESSION['currentMeal'])
function clearCurrentMeal() {

    $objResponse = new xajaxResponse();

	# unset the current meal session variable
	if ( isset($_SESSION['currentMeal']) ) {
		unset($_SESSION['currentMeal']);
	}

	# if it's still set here, then something went terribly wrong, otherwise
	# clear the div and let the user know.
	if ( isset($_SESSION['currentMeal']) ) {
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgError'>There was an error. The current meal was not cleared.</span>");
	} else {
    	$objResponse->addAssign("divCurrentMeal", "innerHTML", "No items in meal.");
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgOkay'>The current meal was successfully cleared.</span>");
	}

	return $objResponse;

}

	##------------------------------------------------------------------##

# create form for editing a meal
function loadMealToEdit($meal) {

	global $config, $db;

	$objResponse = new xajaxResponse();

	$mealToEdit = "";

	$sql = sprintf ("
		SELECT userMeals.*, userMeals.id AS mealId, userMeals.description as mealDesc,
			userMealItems.*, userMealItems.id as itemId, userMealItems.description as itemDesc
		FROM userMeals LEFT JOIN userMealItems
			ON userMeals.id = userMealItems.meal
		WHERE userMeals.id = '%s' AND user = '%s'
		",
		$meal,
		$_SESSION['user']['id']
	);
	$db->Select($sql);

	if ( $db->_rowCount == 0 ) {
		$mealToEdit = "<span class='msgError'>The selected saved meal doesn't exist.</span><br />\n&lt;= Select a meal to edit.";
		$objResponse->addAssign("editMeal","innerHTML", $mealToEdit);
		return $objResponse;
	} else {
		$mealItems = $db->_rows;
		$mealDesc = htmlspecialchars($mealItems[0]['mealDesc'], ENT_QUOTES);
		$mealToEdit .= <<<HTML
			<div>
				<strong>Meal name</strong>: <input type='text' name='mealDesc' value='$mealDesc' size='25' />
			</div>
			<div id='editMealItems' style='margin-bottom: 1ex; overflow: hidden;'>

HTML;
		# here we grab and add all the possible predefined quantites
		# so that the user can change the quantity from, for example,
		# '1 large banana (7")' to '2 medium banana (5")' or something
		# to that effect
		foreach ( $mealItems as $key => $mealItem ) {
			$sql = sprintf ("
				SELECT seq AS weight, msre_desc
				FROM weights
				WHERE ndb_no = '%s'
				",
				$mealItem['food']
			);
			$db->Select($sql);
			$itemQuantities = $db->_rows;
			$mealItems[$key]['quantities'] = $itemQuantities;

			# we will use this array later, in the Modify action below
			# to identify which meal items we need to update.
			$itemIds[] = $mealItem['itemId'];

			$mealItemDesc = htmlspecialchars($mealItem['itemDesc'], ENT_QUOTES);
			$mealToEdit .= <<<HTML
			<div id='mealItem-{$mealItem['id']}'>
				<div>
					<a href='{$_SERVER['REQUEST_URI']}' onclick='verifyRemoveMealItem("{$mealItem['id']}"); return false;'><img src='{$config->_imgUri}/remove.png' alt='Del' title='Remove: $mealItemDesc' /></a>
					=&gt; <strong>Meal item</strong>: <input type='text' name='mealItemDesc-{$mealItem['id']}' id='mealItemDesc-{$mealItem['id']}' value='$mealItemDesc' size='25' />
				</div>
				<div style='margin-top: 1ex; margin-left: 3ex;'>
					<div style='margin-left: 2ex; margin-bottom: 1ex;'>
						=&gt; <strong>Amount</strong>: <input type='text' name='mealItemQuantity-{$mealItem['id']}' id='mealItemQuantity-{$mealItem['id']}' value='{$mealItem['quantity']}' size='2' />
						<select name='mealItemWeight-{$mealItem['id']}'>

HTML;

			foreach ( $itemQuantities as $itemQuantity ) {
				if ( $itemQuantity['weight'] == $mealItem['weight'] ) {
					$mealToEdit .= "							<option value='{$itemQuantity['weight']}' selected='selected'>{$itemQuantity['msre_desc']}</option>\n";
				} else {
					$mealToEdit .= "							<option value='{$itemQuantity['weight']}'>{$itemQuantity['msre_desc']}</option>\n";
				}
			}

			$mealToEdit .= <<<HTML
						</select>
					</div>
				</div>
			</div>

HTML;
		}

		if ( $mealItem['favorite'] == "1" ) {
			$mealToEdit .= "					<div><strong>Favorite</strong>: <input type='checkbox' name='favorite' id='favorite' checked='checked' /></div>\n";
		} else {
			$mealToEdit .= "					<div><strong>Favorite</strong>: <input type='checkbox' name='favorite' id='favorite' /></div>\n";
		}

		# separate itemIds with a comma
		$mealItemIds = implode(",",$itemIds);
		$mealToEdit .= <<<HTML
		</div>
		<div style='margin-top: 2ex;'>
			<input type='hidden' name='meal' value='$meal' />
			<input type='hidden' name='mealItemIds' value='$mealItemIds' />
			<input type='hidden' name='action' value='' />
			<input type='submit' name='doModifyMeal' value='Modify' onclick='document.formEditMeal.action.value = "Modify";' />
			<input type='submit' name='doDeleteMeal' value='Delete' onclick='document.formEditMeal.action.value = "Delete";' />
		</div>

HTML;
	}

    $objResponse->addAssign("editMeal","innerHTML", $mealToEdit);

	return $objResponse;

}

	##------------------------------------------------------------------##

# create form for editing a food
function loadFoodToEdit($food) {

	global $config, $db;

    $objResponse = new xajaxResponse();
	$foodToEdit = "";

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

	if ( $db->_rowCount == 0 ) {
		$foodToEdit = "<span class='msgError'>The selected saved food doesn't exist.</span><br />\n&lt;= Select a food to edit.";
    	$objResponse->addAssign("editFood","innerHTML", $foodToEdit);
		return $objResponse;
	} else {
		$foodItem = $db->_row;
		# here we grab and add all the possible predefined quantites
		# so that the user can change the quantity from, for example,
		# '1 large banana (7")' to '2 medium banana (5")' or something
		# to that effect
		$sql = sprintf ("
			SELECT seq AS weight, msre_desc
			FROM weights
			WHERE ndb_no = '%s'
			",
			$foodItem['food']
		);
		$db->Select($sql);
		$itemQuantities = $db->_rows;
		$foodItem['quantities'] = $itemQuantities;

		$foodDesc = htmlspecialchars($foodItem['description'], ENT_QUOTES);
		$foodToEdit .= <<<HTML
					<form action='edit_food' method='post' name='formEditFood' id='formEditFood' onsubmit='return validateEditFood("formEditFood");'>
						<div><strong>Food name</strong>: <input type='text' name='foodDesc' id='foodDesc' value='$foodDesc' size='25' /></div>
						<div style='margin-left: 3ex; margin-bottom: 1ex;'>
							=&gt; <strong>Amount</strong>: <input type='text' name='quantity' value='{$foodItem['quantity']}' size='2' />
							<select name='weight'>

HTML;

		foreach ( $itemQuantities as $itemQuantity ) {
			if ( $itemQuantity['weight'] == $foodItem['weight'] ) {
				$foodToEdit .= "								<option value='{$itemQuantity['weight']}' selected='selected'>{$itemQuantity['msre_desc']}</option>\n";
			} else {
				$foodToEdit .= "								<option value='{$itemQuantity['weight']}'>{$itemQuantity['msre_desc']}</option>\n";
			}
		}

		$foodToEdit .= <<<HTML
							</select>
						</div>
HTML;
		if ( $foodItem['favorite'] == "1" ) {
			$foodToEdit .= "					<div><strong>Favorite</strong>: <input type='checkbox' name='favorite' id='favorite' checked='checked' /></div>\n";
		} else {
			$foodToEdit .= "					<div><strong>Favorite</strong>: <input type='checkbox' name='favorite' id='favorite' /></div>\n";
		}
		$foodToEdit .= <<<HTML
						<div style='margin-top: 2ex;'>
							<input type='hidden' name='food' value='$food' />
							<input type='hidden' name='action' value='' />
							<input type='submit' name='doModifyFood' value='Modify' onclick='document.formEditFood.action.value = "Modify";' />
							<input type='submit' name='doDeleteFood' value='Delete' onclick='document.formEditFood.action.value = "Delete";' />
						</div>
					</form>

HTML;
	}

    $objResponse->addAssign("editFood","innerHTML", $foodToEdit);

	return $objResponse;

}

	##------------------------------------------------------------------##

# removes an item from a saved meal
function removeMealItem($mealItem) {

	global $db;

	$objResponse = new xajaxResponse();

	$sql = sprintf ("
		DELETE userMealItems.*
		FROM userMealItems INNER JOIN userMeals
			ON userMealItems.meal = userMeals.id
		INNER JOIN users
			ON userMeals.user = users.id
		WHERE users.id = '%s' AND userMealItems.id = '%s'
		",
		$_SESSION['user']['id'],
		$mealItem
	);
	$db->Modify($sql);

	if ( $db->_affectedRows == "1" ) {
		$objResponse->addRemove("mealItem-$mealItem");
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgOkay'>The meal item was successfully removed.</span>");
		return $objResponse;
	} else {
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgError'>There was an error.  The meal item was not meal.</span>");
		return $objResponse;
	}

}
	##------------------------------------------------------------------##

# removes an item from a diary
function removeDiaryItem($diaryItem) {

	global $db;

	$objResponse = new xajaxResponse();

	$sql = sprintf ("
		DELETE userDiaryItems.*
		FROM userDiaryItems INNER JOIN userDiaries
			ON userDiaryItems.diary = userDiaries.id
		WHERE userDiaries.user = '%s'
			AND userDiaryItems.id = '%s'
		",
		$_SESSION['user']['id'],
		$diaryItem
	);
	$db->Modify($sql);

	if ( $db->_affectedRows == "1" ) {
		$objResponse->addRemove("itemRow-$diaryItem");
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgOkay'>The diary item was successfully deleted.</span>");
		return $objResponse;
	} else {
		$objResponse->addAssign("systemMsgs", "innerHTML", "<span class='msgError'>There was an error.  The diary item was not deleted.</span>");
		return $objResponse;
	}

}

	##------------------------------------------------------------------##

# checks to see if a username already exists in the db during the registration process
function usernameExists($username) {

	global $db;

	$objResponse = new xajaxResponse();

	$sql = sprintf ("
		SELECT username FROM users
		WHERE username = '%s'
		",
		trim($username)
	);
	$db->Select($sql);
	if ( $db->_rowCount > 0 ) {
		$alert = "The login name you selected is already in use.  Please select another.";
		$objResponse->addAlert($alert);
		$objResponse->addScript("xajax.$('formRegisterUser').username.focus();");
		$objResponse->addScript("return false;");
	} else {
		$objResponse->addScript("xajax.$('formRegisterUser').submit();");
	}

	return $objResponse;

}

	##------------------------------------------------------------------##

# increment the "popularity" counter for the supplied ndb_no.
# table will be: foodDesc, userFoods, or userMeals ... we use it to determine
# which counter to increment.  the name corresponds to the relevant table
# so we can just plug it into the query directly

function incrementPopularityCounter($id, $table) {

	global $db;

	# we keep track of which items a user has selected during a given
	# session and we only allow a popularity counter to be incremented
	# for a given item once per session.  this isn't fool-proof, but it
	# should help to stem someone repeatedly clicking on the same item
	# in order to raise it's popularity artificially .. at least it will
	# be more of a hassle for someone to do it.
	if ( ! empty($_SESSION['popularity']) && in_array("$id{$table}", $_SESSION['popularity']) ) {
		# this user has already selected this item during this session
		# so don't increment the popularity counter
		return false;
	}

	switch ( $table ) {
		case "foodDescs":
			$idField = "ndb_no";
			break;
		case "userFoods":
			$idField = "id";
			break;
		case "userMeals":
			$idField = "id";
			break;
		default:
			# the table isn't valid
			return false;
	}

	$sql = sprintf ("
		UPDATE %s
			SET popularity = (popularity + 1)
		WHERE %s = '%s'
		",
		$table,
		$idField,
		$id
	);
	$db->Modify($sql);

	# add this food to the list so that this user can't trigger another
	# popularity increment for this food during this session.
	$_SESSION['popularity'][] = "$id{$table}"; 

	return true;

}

	##------------------------------------------------------------------##

?>