+function common_set_cookie($key, $value, $expiration=0) {
+ $path = common_config('site', 'path');
+ $server = common_config('site', 'server');
+
+ if ($path && ($path != '/')) {
+ $cookiepath = '/' . $path . '/';
+ } else {
+ $cookiepath = '/';
+ }
+ return setcookie($key,
+ $value,
+ $expiration,
+ $cookiepath,
+ $server);
+}
+
+define('REMEMBERME', 'rememberme');
+define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
+
+function common_rememberme() {
+ $user = common_current_user();
+ if (!$user) {
+ return false;
+ }
+ $rm = new Remember_me();
+ $rm->code = common_good_rand(16);
+ $rm->user_id = $user->id;
+ $result = $rm->insert();
+ if (!$result) {
+ common_log_db_error($rm, 'INSERT', __FILE__);
+ return false;
+ }
+ common_set_cookie(REMEMBERME,
+ implode(':', array($rm->user_id, $rm->code)),
+ time() + REMEMBERME_EXPIRY);
+ return true;
+}
+
+function common_remembered_user() {
+ $user = NULL;
+ # Try to remember
+ $packed = $_COOKIE[REMEMBERME];
+ if ($packed) {
+ list($id, $code) = explode(':', $packed);
+ if ($id && $code) {
+ $rm = Remember_me::staticGet($code);
+ if ($rm && ($rm->user_id == $id)) {
+ $user = User::staticGet($rm->user_id);
+ if ($user) {
+ # successful!
+ $result = $rm->delete();
+ if (!$result) {
+ common_log_db_error($rm, 'DELETE', __FILE__);
+ $user = NULL;
+ } else {
+ common_set_user($user->nickname);
+ common_real_login(false);
+ # We issue a new cookie, so they can log in
+ # automatically again after this session
+ common_rememberme();
+ }
+ }
+ }
+ }
+ }
+ return $user;
+}
+
+# must be called with a valid user!
+
+function common_forgetme() {
+ common_set_cookie(REMEMBERME, '', 0);
+}
+