send($msg); if (!$resp) { // no response to our call return FALSE; } if (!$resp->faultCode()) { // no error, get the session id $val = $resp->value(); $data = XML_RPC_decode($val); return $data; } else { // an error occured return FALSE; } } /** * Performs a XML RPC to check if a user has a specific right on this project * * @param $origo_session * The Origo session id to identify the user * @param $right * The right to check * * @return * If the user has the right on this project */ function _sess_xmlrpc_is_allowed_project($origo_session, $right, $noproject = FALSE) { require_once 'XML/RPC.php'; // get the project ID if ($noproject) { $project_id = 0; } else { $result = db_query("SELECT * FROM {variable} WHERE name='origo_project_id'"); $variable = db_fetch_object($result); $project_id = unserialize($variable->value); } // perform XML RPC $params = array(new XML_RPC_Value($origo_session, 'string'), new XML_RPC_Value($right, 'string'), new XML_RPC_Value($project_id, 'int')); $msg = new XML_RPC_Message('authorization.is_allowed_project', $params); $cli = new XML_RPC_Client(variable_get('origo_api_path', ''), variable_get('origo_api_host', '')); $resp = $cli->send($msg); if (!$resp) { // no response to our call return FALSE; } if (!$resp->faultCode()) { // no error, get the answer $val = $resp->value(); $data = XML_RPC_decode($val); return $data; } else { // an error occured return FALSE; } } /** * Decrypt text (helper function to decode the origo cookie) * * @param $content * The encrypted text * @param $iv * The initialization vector * @param $key * The secret key * * @return * The decrypted text */ function _decryptAES($content, $iv, $key) { // set algorithm $cp = mcrypt_module_open('rijndael-128', '', 'ofb', ''); // key size $ks = mcrypt_enc_get_key_size($cp); // key $key = substr(md5($key), 0, $ks); // initialize encryption mcrypt_generic_init($cp, $key, $iv); // decrypt string $decrypted = mdecrypt_generic($cp, $content); // deinit mcrypt_generic_deinit($cp); // close mcrypt module mcrypt_module_close($cp); return trim($decrypted); } /** * Reads and decodes the Origo Cookie and logs in the user */ function _sess_load_origo_user() { global $user; // read and decrypt the Origo Cookie $userdata = unserialize($_COOKIE['origo_session']); if ($userdata === FALSE) { $origo_session_id = FALSE; } else { $userdata['password'] = _decryptAES($userdata['password']['encrypted'], $userdata['password']['iv'], variable_get('origo_cookie_secret', '')); // Log in the user into Origo $origo_session_id = _sess_xmlrpc_login((string)($userdata['username']), (string)($userdata['password'])); } if ($origo_session_id === FALSE) { //cookie does not contain a correct user, so we log in an anonymous user setcookie('origo_session', '', time() - 42000, '/', variable_get('origo_cookie_domain', '')); $user = drupal_anonymous_user(); return; } // check if the user already exists in the local database $user = db_fetch_object(db_query("SELECT u.* FROM {users} u WHERE u.name = '%s'", $userdata['username'])); if ($user && $user->uid > 0) { // user is already in database, we just need to update the data // add the Origo session id to the user object and store it $data = unserialize($user->data); $data['origo_session'] = $origo_session_id; $v = serialize($data); $user->data = $v; db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", $v, $user->uid); } else { // user is not in drupal database, so we create a new user $data['origo_session'] = $origo_session_id; $fields[] = 'data'; $values[] = serialize($data); $s[] = "'%s'"; $fields[] = 'name'; $values[] = $userdata['username']; $s[] = "'%s'"; $fields[] = 'init'; $values[] = $userdata['username']; $s[] = "'%s'"; $fields[] = 'pass'; $values[] = md5($userdata['password']); $s[] = "'%s'"; $fields[] = 'status'; $values[] = 1; $s[] = "%d"; $fields[] = 'uid'; $values[] = db_last_insert_id('users', 'uid'); $s[] = "%d"; db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values); $user = db_fetch_object(db_query("SELECT u.* FROM {users} u WHERE u.name = '%s'", $userdata['username'])); } // check if the user is a project owner or member $is_owner = _sess_xmlrpc_is_allowed_project($data['origo_session'], 'website_edit_owner'); $is_member = _sess_xmlrpc_is_allowed_project($data['origo_session'], 'website_edit_member'); $is_admin = _sess_xmlrpc_is_allowed_project($data['origo_session'], 'project_global_admin', TRUE); if ($is_admin) { $roles = array('5' => TRUE); } elseif ($is_owner) { $roles = array('3' => TRUE); } elseif ($is_member) { $roles = array('4' => TRUE); } else { $roles = array(); } // set user roles in database if (is_array($roles)) { db_query('DELETE FROM {users_roles} WHERE uid = %d', $user->uid); foreach (array_keys($roles) as $rid) { if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { db_query('INSERT IGNORE INTO {users_roles} (uid, rid) VALUES (%d, %d)', $user->uid, $rid); } } } // load user and fetch role from database $user = drupal_unpack($user); $user->roles = array(); if ($user->uid) { $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; } else { $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user'; } $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user->uid); while ($role = db_fetch_object($result)) { $user->roles[$role->rid] = $role->name; } } function sess_read($key) { global $user; // Write and Close handlers are called after destructing objects since PHP 5.0.5 // Thus destructors can use sessions but session handler can't use objects. // So we are moving session closure before destructing objects. register_shutdown_function('session_write_close'); if (!isset($_COOKIE[session_name()]) && !isset($_COOKIE['origo_session'])) { // there is neither a drupal session nor a drupal session $user = drupal_anonymous_user(); return ''; } if (isset($_COOKIE[session_name()])) { // There is a drupal sessio cookie, try to fetch the session from the database $user = db_fetch_object(db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = '%s'", $key)); if ($user && $user->uid > 0) { // We found the client's session record and they are an authenticated user if (isset($_COOKIE['origo_session'])) { // if there is an Origo session cookie, get the username from there $userdata = unserialize($_COOKIE['origo_session']); if ($userdata['username'] == $user->name) { //the drupal session has the same user as the Origo session, so we can load the user from the local drupal session $user = drupal_unpack($user); // Add roles element to $user $user->roles = array(); $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; $result = db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d", $user->uid); while ($role = db_fetch_object($result)) { $user->roles[$role->rid] = $role->name; } } else { // the user in the origo session cookie is different, so we have to load the user from our Origo session cookie _sess_load_origo_user(); return ''; } } else { // there is a local drupal session, but no Origo session cookie. Perhaps user logged out on another site. // We have to destroy the local session to log out the user here too. // Save session information, containing potential warning- and errormessages // (usecase: new user registration, containing the registration-message) $session = isset($user->session) ? $user->session : ''; db_query("DELETE FROM {sessions} WHERE sid = '%s'", $key); $user = drupal_anonymous_user($session); } } else { // We didn't find the client's record (session has expired), or they are an anonymous user. if (isset($_COOKIE['origo_session'])) { // if there is an Origo session cookie, try to load the user from there _sess_load_origo_user(); return ''; } else { // we could not authenticate the user, so we log in an anonymous user $session = isset($user->session) ? $user->session : ''; $user = drupal_anonymous_user($session); } } return $user->session; } else { //no active drupal session _sess_load_origo_user(); return ''; } } function sess_write($key, $value) { global $user; // If saving of session data is disabled or if the client doesn't have a session, // and one isn't being created ($value), do nothing. This keeps crawlers out of // the session table. This reduces memory and server load, and gives more useful // statistics. We can't eliminate anonymous session table rows without breaking // the throttle module and the "Who's Online" block. if (!session_save_session() || ($user->uid == 0 && empty($_COOKIE[session_name()]) && empty($value))) { return TRUE; } db_query("UPDATE {sessions} SET uid = %d, cache = %d, hostname = '%s', session = '%s', timestamp = %d WHERE sid = '%s'", $user->uid, isset($user->cache) ? $user->cache : '', ip_address(), $value, time(), $key); if (db_affected_rows()) { // Last access time is updated no more frequently than once every 180 seconds. // This reduces contention in the users table. if ($user->uid && time() - $user->access > variable_get('session_write_interval', 180)) { db_query("UPDATE {users} SET access = %d WHERE uid = %d", time(), $user->uid); } } else { // If this query fails, another parallel request probably got here first. // In that case, any session data generated in this request is discarded. @db_query("INSERT INTO {sessions} (sid, uid, cache, hostname, session, timestamp) VALUES ('%s', %d, %d, '%s', '%s', %d)", $key, $user->uid, isset($user->cache) ? $user->cache : '', ip_address(), $value, time()); } return TRUE; } /** * Called when an anonymous user becomes authenticated or vice-versa. */ function sess_regenerate() { $old_session_id = session_id(); // We code around http://bugs.php.net/bug.php?id=32802 by destroying // the session cookie by setting expiration in the past (a negative // value). This issue only arises in PHP versions before 4.4.0, // regardless of the Drupal configuration. // TODO: remove this when we require at least PHP 4.4.0 if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 42000, '/'); } session_regenerate_id(); db_query("UPDATE {sessions} SET sid = '%s' WHERE sid = '%s'", session_id(), $old_session_id); } /** * Counts how many users have sessions. Can count either anonymous sessions or authenticated sessions. * * @param int $timestamp * A Unix timestamp representing a point of time in the past. * The default is 0, which counts all existing sessions. * @param boolean $anonymous * TRUE counts only anonymous users. * FALSE counts only authenticated users. * @return int * The number of users with sessions. */ function sess_count($timestamp = 0, $anonymous = TRUE) { $query = $anonymous ? ' AND uid = 0' : ' AND uid > 0'; return db_result(db_query('SELECT COUNT(sid) AS count FROM {sessions} WHERE timestamp >= %d'. $query, $timestamp)); } /** * Called by PHP session handling with the PHP session ID to end a user's session. * * @param string $sid * the session id */ function sess_destroy_sid($sid) { db_query("DELETE FROM {sessions} WHERE sid = '%s'", $sid); } /** * End a specific user's session * * @param string $uid * the user id */ function sess_destroy_uid($uid) { db_query('DELETE FROM {sessions} WHERE uid = %d', $uid); } function sess_gc($lifetime) { // Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough // value. For example, if you want user sessions to stay in your database // for three weeks before deleting them, you need to set gc_maxlifetime // to '1814400'. At that value, only after a user doesn't log in after // three weeks (1814400 seconds) will his/her session be removed. db_query("DELETE FROM {sessions} WHERE timestamp < %d", time() - $lifetime); return TRUE; } /** * Determine whether to save session data of the current request. * * This function allows the caller to temporarily disable writing of session data, * should the request end while performing potentially dangerous operations, such as * manipulating the global $user object. See http://drupal.org/node/218104 for usage * * @param $status * Disables writing of session data when FALSE, (re-)enables writing when TRUE. * @return * FALSE if writing session data has been disabled. Otherwise, TRUE. */ function session_save_session($status = NULL) { static $save_session = TRUE; if (isset($status)) { $save_session = $status; } return ($save_session); }