<?php
// Rate theme, and convert old cookie format to a new one
public function ratetheme($id, $rating) {
if (!is_numeric($rating)) { // make sure $rating is a valid number
return FALSE;
}
$rating = (int) $rating; // force $rating into an integer
if ($rating < 0 || $rating > 10) { // make sure $rating is within range
return FALSE;
}
$alreadyRated = FALSE;
$convertOldCookie = FALSE;
$themeIdList = array (); // list of theme IDs that have been rated by the user
// Handle old cookies
$oldCookieName = "rating_{$id}";
if (array_key_exists($oldCookieName, $_COOKIE)) {
$alreadyRated = TRUE;
$convertOldCookie = TRUE;
$themeIdList[] = $id; // add ID to the empty list
@setcookie($oldCookieName, '', time() - 86400); // delete old cookie
}
$cookieName = 'ratings';
if (array_key_exists($cookieName, $_COOKIE)) { // user already has a ratings cookie
$themeIdList = explode(',', "{$_COOKIE[$cookieName]}"); // turn the coma-separated list of theme IDs into an array
if ($themeIdList === FALSE) { // explode() returns FALSE when fed an empty string
$themeIdList = array ();
}
if (in_array("$id", $themeIdList)) { // theme ID present in the list
$alreadyRated = TRUE;
} else if ($alreadyRated) { // got an old cookie
$themeIdList[] = $id; // add ID to the list
}
if (!$alreadyRated || $convertOldCookie) { // Sanitize the list of theme IDs:
// no point in executing the following code if the theme has already been rated (no change),
// or if no old cookie needs to be converted to the new one
$sanitizedThemeIdList = array ();
foreach ($themeIdList as $value) {
if (is_numeric($value)) { // is $value a valid number?
$value = (int) $value; // convert the number string into an integer
if ($value > 0) { // is $value a valid theme ID?
$sanitizedThemeIdList[] = $value;
}
}
}
$themeIdList = $sanitizedThemeIdList; // replace $themeIdList with sanitized list
}
}
if (!$alreadyRated) { // theme hasn't been rated yet: update the database
$sql = 'UPDATE themes SET ratings=ratings+:rating, numratings=numratings+1 WHERE themeid=:id';
$args = array (
':rating' => $rating,
':id' => $id,
);
$this->db->query($sql, $args);
}
if (!$alreadyRated || $convertOldCookie) { // update cookie if needed
// Turn $themeIdList into a coma-separated list of IDs, and store it in a cookie:
@setcookie($cookiename, implode(',', $themeIdList), time()+(60*60*24*365*10)); // 10 years
}
return TRUE;
}