/** * function used to build HMAC code for an array * @return: string */ function euplatesc_mac($data, $key = NULL) { $str = NULL; foreach ($data as $d) { if ($d === NULL || strlen($d) == 0) { $str .= '-'; } else { $str .= strlen($d) . $d; } } $key = pack('H*', $key); return hmacsha1($key, $str); }
function lftokenValidateServerToken($token, $key) { $parts = explode(',', $token); $signature = array_pop($parts); $serverkey = hmacsha1(base64_decode($key), "Server Key"); $temp = base64_encode(hmacsha1($serverkey, implode(',', $parts))); if (count($parts) > 1) { $timestamp = strtotime($parts[1]); $duration = $parts[2]; } else { $timestamp = time() - 1; $duration = 0; } return $signature == $temp && time() - $timestamp < $duration; }
function logoutSession() { global $cfg, $db; $cfg['username'] = ''; // Footer $cfg['access_media'] = ''; // Header opensearch $sid = cookie('netjukebox_sid'); $sign = randomKey(); $session_seed = randomKey(); // Update current session mysql_query('UPDATE session SET logged_in = 0, ip = "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '", user_agent = "' . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']) . '", sign = "' . mysql_real_escape_string($sign) . '", seed = "' . mysql_real_escape_string($session_seed) . '" WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"'); if (mysql_affected_rows($db) == 0) { // Create new session $sid = randomKey(); mysql_query('INSERT INTO session (logged_in, create_time, ip, user_agent, sid, sign, seed) VALUES ( 0, ' . (int) time() . ', "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '", "' . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']) . '", "' . mysql_real_escape_string($sid) . '", "' . mysql_real_escape_string($sign) . '", "' . mysql_real_escape_string($session_seed) . '")'); setcookie('netjukebox_sid', $sid, time() + 31536000, null, null, NJB_HTTPS, true); @ob_flush(); flush(); } // +------------------------------------------------------------------------+ // | Login | // +------------------------------------------------------------------------+ $query = mysql_query('SELECT username FROM user WHERE username = "******"'); $user = mysql_fetch_assoc($query); $anonymous = $user['username']; $action = get('action'); if (NJB_SCRIPT == 'index.php' && substr($action, 0, 4) == 'view') { $url = 'index.php?'; $get = getAll(); foreach ($get as $key => $value) { $url .= rawurlencode($key) . '=' . rawurlencode($value) . '&'; } $url = substr($url, 0, -5); } else { $url = 'index.php'; } $cfg['align'] = true; require_once NJB_HOME_DIR . 'include/header.inc.php'; ?> <script type="text/javascript"> <!-- if (hmacsha1('key', 'The quick brown fox jumps over the lazy dog') != 'de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9') { document.write('<table cellspacing="10" cellpadding="0" class="error">'); document.write('<tr>'); document.write(' <td valign="top"><img src="<?php echo $cfg['img']; ?> medium_message_error.png" alt=""><\/td>'); document.write(' <td valign="top"><strong>JavaScript error<\/strong><br>Unexpected SHA1 checksum result.<\/td>'); document.write('<\/tr>'); document.write('<\/table>'); } else if (typeof XMLHttpRequest == 'undefined') { document.write('<table cellspacing="10" cellpadding="0" class="error">'); document.write('<tr>'); document.write(' <td valign="top"><img src="<?php echo $cfg['img']; ?> medium_message_error.png" alt=""><\/td>'); document.write(' <td valign="top"><strong>Native XMLHttpRequest support is required<\/strong><br>'); document.write(' Enable XMLHttpRequest or get a modern web browser.<\/td>'); document.write('<\/tr>'); document.write('<\/table>'); } else { document.write('<form action="<?php echo $url; ?> " method="post" name="loginform" id="loginform" onSubmit="loginStage1(this.username.value); return false;">'); document.write(' <input type="hidden" name="authenticate" value="validate">'); document.write(' <input type="hidden" name="hash1" value="">'); document.write(' <input type="hidden" name="hash2" value="">'); document.write(' <input type="hidden" name="sign" value="">'); document.write('<table cellspacing="0" cellpadding="0" class="warning">'); document.write('<tr class="space"><td colspan="5"><\/td><\/tr>'); document.write('<tr>'); document.write(' <td class="space"><\/td>'); document.write(' <td>Username:<\/td>'); document.write(' <td class="space"><\/td>'); document.write(' <td><input type="text" name="username" value="<?php echo addslashes(html($anonymous)); ?> " maxlength="255" class="login" onKeyUp="anonymousPassword();"><\/td>'); document.write(' <td class="space"><\/td>'); document.write('<\/tr>'); document.write('<tr>'); document.write(' <td><\/td>'); document.write(' <td>Password:<\/td>'); document.write(' <td><\/td>'); document.write(' <td><input type="password" name="password" class="login"><\/td>'); document.write(' <td><\/td>'); document.write('<\/tr>'); document.write('<tr class="space"><td colspan="5"><\/td><\/tr>'); document.write('<tr>'); document.write(' <td><\/td>'); document.write(' <td colspan="3" align="right"><input type="submit" value="login" class="button"><\/td>'); document.write(' <td><\/td>'); document.write('<\/tr>'); document.write('<tr class="space"><td colspan="5"><\/td><\/tr>'); document.write('<tr>'); document.write(' <td><\/td>'); document.write(' <td colspan="3" class="line"><\/td>'); document.write(' <td><\/td>'); document.write('<\/tr>'); document.write('<tr class="space"><td colspan="5"><\/td><\/tr>'); <?php if ($cfg['admin_login_message'] == '') { ?> document.write('<tr>'); document.write(' <td><\/td>'); document.write(' <td colspan="3"><span class="login_message">Cookies and JavaScript are required to login.<br>'); document.write(' Browser must support native XMLHttpRequest.<\/span><\/td>'); document.write(' <td><\/td>'); document.write('<\/tr>'); <?php } else { ?> document.write('<tr>'); document.write(' <td><\/td>'); document.write(' <td colspan="3"><span class="login_message">'); document.write(' <?php echo addslashes(bbcode($cfg['admin_login_message'])); ?> <\/span><\/td>'); document.write(' <td><\/td>'); document.write('<\/tr>'); <?php } ?> document.write('<tr class="space"><td colspan="5"><\/td><\/tr>'); document.write('<\/table>'); document.write('<\/form>'); } function initialize() { if (typeof XMLHttpRequest != 'undefined') { document.loginform.username.focus(); document.loginform.username.select(); anonymousPassword(); } } function anonymousPassword() { if (<?php echo $anonymous ? 'true' : 'false'; ?> && document.loginform.username.value == '<?php echo addslashes(html($anonymous)); ?> ') { document.loginform.password.value = ''; document.loginform.password.className = 'login readonly'; // document.loginform.password.disabled = true; } else { document.loginform.password.className = 'login'; // document.loginform.password.disabled = false; } } function loginStage1(username) { document.loginform.username.value = ''; document.loginform.username.value = username; document.loginform.username.className = 'login readonly'; document.loginform.password.className = 'login readonly'; ajaxRequest('json.php', loginStage2, 'action=loginStage1&username='******'UTF-8' ? 'encodeURIComponent' : 'escape'; ?> (username) + '&sign=<?php echo hmacsha1($cfg['server_seed'], $sign); ?> '); } function loginStage2(data) { // data.user_seed, data.session_seed, data.sign; var password = document.loginform.password.value; document.loginform.password.value = ''; if (<?php echo $anonymous ? 'true' : 'false'; ?> && document.loginform.username.value == '<?php echo addslashes(html($anonymous)); ?> ') password = '******'; document.loginform.hash1.value = hmacsha1(password, data.user_seed); document.loginform.hash2.value = hmacsha1(hmacsha1(password, data.session_seed), data.session_seed); document.loginform.sign.value = data.sign; password = ''; setTimeout('document.loginform.submit();', <?php echo $cfg['login_delay']; ?> ); } //--> </script> <?php require_once NJB_HOME_DIR . 'include/footer.inc.php'; exit; }
function doModel() { osc_run_hook('before_search'); if (osc_rewrite_enabled()) { // IF rewrite is not enabled, skip this part, preg_match is always time&resources consuming task $p_sParams = "/" . Params::getParam('sParams', false, false); if (preg_match_all('|\\/([^,]+),([^\\/]*)|', $p_sParams, $m)) { $l = count($m[0]); for ($k = 0; $k < $l; $k++) { switch ($m[1][$k]) { case osc_get_preference('rewrite_search_country'): $m[1][$k] = 'sCountry'; break; case osc_get_preference('rewrite_search_region'): $m[1][$k] = 'sRegion'; break; case osc_get_preference('rewrite_search_city'): $m[1][$k] = 'sCity'; break; case osc_get_preference('rewrite_search_city_area'): $m[1][$k] = 'sCityArea'; break; case osc_get_preference('rewrite_search_category'): $m[1][$k] = 'sCategory'; break; case osc_get_preference('rewrite_search_user'): $m[1][$k] = 'sUser'; break; case osc_get_preference('rewrite_search_pattern'): $m[1][$k] = 'sPattern'; break; default: // custom fields if (preg_match("/meta(\\d+)-?(.*)?/", $m[1][$k], $results)) { $meta_key = $m[1][$k]; $meta_value = $m[2][$k]; $array_r = array(); if (Params::existParam('meta')) { $array_r = Params::getParam('meta'); } if ($results[2] == '') { // meta[meta_id] = meta_value $meta_key = $results[1]; $array_r[$meta_key] = $meta_value; } else { // meta[meta_id][meta_key] = meta_value $meta_key = $results[1]; $meta_key2 = $results[2]; $array_r[$meta_key][$meta_key2] = $meta_value; } $m[1][$k] = 'meta'; $m[2][$k] = $array_r; } break; } Params::setParam($m[1][$k], $m[2][$k]); } Params::unsetParam('sParams'); } } $uriParams = Params::getParamsAsArray(); $searchUri = osc_search_url($uriParams); if ($this->uri != 'feed') { if (str_replace("%20", '+', $searchUri) != str_replace("%20", '+', WEB_PATH . $this->uri)) { $this->redirectTo($searchUri, 301); } } //////////////////////////////// //GETTING AND FIXING SENT DATA// //////////////////////////////// $p_sCategory = Params::getParam('sCategory'); if (!is_array($p_sCategory)) { if ($p_sCategory == '') { $p_sCategory = array(); } else { $p_sCategory = explode(",", $p_sCategory); } } $p_sCityArea = Params::getParam('sCityArea'); if (!is_array($p_sCityArea)) { if ($p_sCityArea == '') { $p_sCityArea = array(); } else { $p_sCityArea = explode(",", $p_sCityArea); } } $p_sCity = Params::getParam('sCity'); if (!is_array($p_sCity)) { if ($p_sCity == '') { $p_sCity = array(); } else { $p_sCity = explode(",", $p_sCity); } } $p_sRegion = Params::getParam('sRegion'); if (!is_array($p_sRegion)) { if ($p_sRegion == '') { $p_sRegion = array(); } else { $p_sRegion = explode(",", $p_sRegion); } } $p_sCountry = Params::getParam('sCountry'); if (!is_array($p_sCountry)) { if ($p_sCountry == '') { $p_sCountry = array(); } else { $p_sCountry = explode(",", $p_sCountry); } } $p_sUser = Params::getParam('sUser'); if (!is_array($p_sUser)) { if ($p_sUser == '') { $p_sUser = ''; } else { $p_sUser = explode(",", $p_sUser); } } $p_sLocale = Params::getParam('sLocale'); if (!is_array($p_sLocale)) { if ($p_sLocale == '') { $p_sLocale = ''; } else { $p_sLocale = explode(",", $p_sLocale); } } $p_sPattern = trim(strip_tags(Params::getParam('sPattern'))); // ADD TO THE LIST OF LAST SEARCHES if (osc_save_latest_searches() && (!Params::existParam('iPage') || Params::getParam('iPage') == 1)) { $savePattern = osc_apply_filter('save_latest_searches_pattern', $p_sPattern); if ($savePattern != '') { LatestSearches::newInstance()->insert(array('s_search' => $savePattern, 'd_date' => date('Y-m-d H:i:s'))); } } $p_bPic = Params::getParam('bPic'); $p_bPic = $p_bPic == 1 ? 1 : 0; $p_bPremium = Params::getParam('bPremium'); $p_bPremium = $p_bPremium == 1 ? 1 : 0; $p_sPriceMin = Params::getParam('sPriceMin'); $p_sPriceMax = Params::getParam('sPriceMax'); //WE CAN ONLY USE THE FIELDS RETURNED BY Search::getAllowedColumnsForSorting() $p_sOrder = Params::getParam('sOrder'); if (!in_array($p_sOrder, Search::getAllowedColumnsForSorting())) { $p_sOrder = osc_default_order_field_at_search(); } $old_order = $p_sOrder; //ONLY 0 ( => 'asc' ), 1 ( => 'desc' ) AS ALLOWED VALUES $p_iOrderType = Params::getParam('iOrderType'); $allowedTypesForSorting = Search::getAllowedTypesForSorting(); $orderType = osc_default_order_type_at_search(); foreach ($allowedTypesForSorting as $k => $v) { if ($p_iOrderType == $v) { $orderType = $k; break; } } $p_iOrderType = $orderType; $p_sFeed = Params::getParam('sFeed'); $p_iPage = 0; if (is_numeric(Params::getParam('iPage')) && Params::getParam('iPage') > 0) { $p_iPage = intval(Params::getParam('iPage')) - 1; } if ($p_sFeed != '') { $p_sPageSize = 1000; } $p_sShowAs = Params::getParam('sShowAs'); $aValidShowAsValues = array('list', 'gallery'); if (!in_array($p_sShowAs, $aValidShowAsValues)) { $p_sShowAs = osc_default_show_as_at_search(); } // search results: it's blocked with the maxResultsPerPage@search defined in t_preferences $p_iPageSize = intval(Params::getParam('iPagesize')); if ($p_iPageSize > 0) { if ($p_iPageSize > osc_max_results_per_page_at_search()) { $p_iPageSize = osc_max_results_per_page_at_search(); } } else { $p_iPageSize = osc_default_results_per_page_at_search(); } //FILTERING CATEGORY $bAllCategoriesChecked = false; $successCat = false; if (count($p_sCategory) > 0) { foreach ($p_sCategory as $category) { $successCat = $this->mSearch->addCategory($category) || $successCat; } } else { $bAllCategoriesChecked = true; } //FILTERING CITY_AREA foreach ($p_sCityArea as $city_area) { $this->mSearch->addCityArea($city_area); } $p_sCityArea = implode(", ", $p_sCityArea); //FILTERING CITY foreach ($p_sCity as $city) { $this->mSearch->addCity($city); } $p_sCity = implode(", ", $p_sCity); //FILTERING REGION foreach ($p_sRegion as $region) { $this->mSearch->addRegion($region); } $p_sRegion = implode(", ", $p_sRegion); //FILTERING COUNTRY foreach ($p_sCountry as $country) { $this->mSearch->addCountry($country); } $p_sCountry = implode(", ", $p_sCountry); // FILTERING PATTERN if ($p_sPattern != '') { $this->mSearch->addPattern($p_sPattern); $osc_request['sPattern'] = $p_sPattern; } else { // hardcoded - if there isn't a search pattern, order by dt_pub_date desc if ($p_sOrder == 'relevance') { $p_sOrder = 'dt_pub_date'; foreach ($allowedTypesForSorting as $k => $v) { if ($p_iOrderType == 'desc') { $orderType = $k; break; } } $p_iOrderType = $orderType; } } // FILTERING USER if ($p_sUser != '') { $this->mSearch->fromUser($p_sUser); } // FILTERING LOCALE $this->mSearch->addLocale($p_sLocale); // FILTERING IF WE ONLY WANT ITEMS WITH PICS if ($p_bPic) { $this->mSearch->withPicture(true); } // FILTERING IF WE ONLY WANT PREMIUM ITEMS if ($p_bPremium) { $this->mSearch->onlyPremium(true); } //FILTERING BY RANGE PRICE $this->mSearch->priceRange($p_sPriceMin, $p_sPriceMax); //ORDERING THE SEARCH RESULTS $this->mSearch->order($p_sOrder, $allowedTypesForSorting[$p_iOrderType]); //SET PAGE if ($p_sFeed == 'rss') { // If param sFeed=rss, just output last 'osc_num_rss_items()' $this->mSearch->page(0, osc_num_rss_items()); } else { $this->mSearch->page($p_iPage, $p_iPageSize); } // CUSTOM FIELDS $custom_fields = Params::getParam('meta'); $fields = Field::newInstance()->findIDSearchableByCategories($p_sCategory); $table = DB_TABLE_PREFIX . 't_item_meta'; if (is_array($custom_fields)) { foreach ($custom_fields as $key => $aux) { if (in_array($key, $fields)) { $field = Field::newInstance()->findByPrimaryKey($key); switch ($field['e_type']) { case 'TEXTAREA': case 'TEXT': case 'URL': if ($aux != '') { $aux = "%{$aux}%"; $sql = "SELECT fk_i_item_id FROM {$table} WHERE "; $str_escaped = Search::newInstance()->dao->escape($aux); $sql .= $table . '.fk_i_field_id = ' . $key . ' AND '; $sql .= $table . ".s_value LIKE " . $str_escaped; $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')'); } break; case 'DROPDOWN': case 'RADIO': if ($aux != '') { $sql = "SELECT fk_i_item_id FROM {$table} WHERE "; $str_escaped = Search::newInstance()->dao->escape($aux); $sql .= $table . '.fk_i_field_id = ' . $key . ' AND '; $sql .= $table . ".s_value = " . $str_escaped; $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')'); } break; case 'CHECKBOX': if ($aux != '') { $sql = "SELECT fk_i_item_id FROM {$table} WHERE "; $sql .= $table . '.fk_i_field_id = ' . $key . ' AND '; $sql .= $table . ".s_value = 1"; $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')'); } break; case 'DATE': if ($aux != '') { $y = (int) date('Y', $aux); $m = (int) date('n', $aux); $d = (int) date('j', $aux); $start = mktime('0', '0', '0', $m, $d, $y); $end = mktime('23', '59', '59', $m, $d, $y); $sql = "SELECT fk_i_item_id FROM {$table} WHERE "; $sql .= $table . '.fk_i_field_id = ' . $key . ' AND '; $sql .= $table . ".s_value >= " . $start . " AND "; $sql .= $table . ".s_value <= " . $end; $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql . ')'); } break; case 'DATEINTERVAL': if (is_array($aux) && (!empty($aux['from']) && !empty($aux['to']))) { $from = $aux['from']; $to = $aux['to']; $start = $from; $end = $to; $sql = "SELECT fk_i_item_id FROM {$table} WHERE "; $sql .= $table . '.fk_i_field_id = ' . $key . ' AND '; $sql .= $start . " >= " . $table . ".s_value AND s_multi = 'from'"; $sql1 = "SELECT fk_i_item_id FROM {$table} WHERE "; $sql1 .= $table . ".fk_i_field_id = " . $key . " AND "; $sql1 .= $end . " <= " . $table . ".s_value AND s_multi = 'to'"; $sql_interval = "select a.fk_i_item_id from (" . $sql . ") a where a.fk_i_item_id IN (" . $sql1 . ")"; $this->mSearch->addConditions(DB_TABLE_PREFIX . 't_item.pk_i_id IN (' . $sql_interval . ')'); } break; default: break; } } } } osc_run_hook('search_conditions', Params::getParamsAsArray()); // RETRIEVE ITEMS AND TOTAL $key = md5(osc_base_url() . $this->mSearch->toJson()); $found = null; $cache = osc_cache_get($key, $found); $aItems = null; $iTotalItems = null; if ($cache) { $aItems = $cache['aItems']; $iTotalItems = $cache['iTotalItems']; } else { $aItems = $this->mSearch->doSearch(); $iTotalItems = $this->mSearch->count(); $_cache['aItems'] = $aItems; $_cache['iTotalItems'] = $iTotalItems; osc_cache_set($key, $_cache, OSC_CACHE_TTL); } $iStart = $p_iPage * $p_iPageSize; $iEnd = min(($p_iPage + 1) * $p_iPageSize, $iTotalItems); $iNumPages = ceil($iTotalItems / $p_iPageSize); // works with cache enabled ? osc_run_hook('search', $this->mSearch); //preparing variables... $countryName = $p_sCountry; if (strlen($p_sCountry) == 2) { $c = Country::newInstance()->findByCode($p_sCountry); if ($c) { $countryName = $c['s_name']; } } $regionName = $p_sRegion; if (is_numeric($p_sRegion)) { $r = Region::newInstance()->findByPrimaryKey($p_sRegion); if ($r) { $regionName = $r['s_name']; } } $cityName = $p_sCity; if (is_numeric($p_sCity)) { $c = City::newInstance()->findByPrimaryKey($p_sCity); if ($c) { $cityName = $c['s_name']; } } $this->_exportVariableToView('search_start', $iStart); $this->_exportVariableToView('search_end', $iEnd); $this->_exportVariableToView('search_category', $p_sCategory); // hardcoded - non pattern and order by relevance $p_sOrder = $old_order; $this->_exportVariableToView('search_order_type', $p_iOrderType); $this->_exportVariableToView('search_order', $p_sOrder); $this->_exportVariableToView('search_pattern', $p_sPattern); $this->_exportVariableToView('search_from_user', $p_sUser); $this->_exportVariableToView('search_total_pages', $iNumPages); $this->_exportVariableToView('search_page', $p_iPage); $this->_exportVariableToView('search_has_pic', $p_bPic); $this->_exportVariableToView('search_only_premium', $p_bPremium); $this->_exportVariableToView('search_country', $countryName); $this->_exportVariableToView('search_region', $regionName); $this->_exportVariableToView('search_city', $cityName); $this->_exportVariableToView('search_price_min', $p_sPriceMin); $this->_exportVariableToView('search_price_max', $p_sPriceMax); $this->_exportVariableToView('search_total_items', $iTotalItems); $this->_exportVariableToView('items', $aItems); $this->_exportVariableToView('search_show_as', $p_sShowAs); $this->_exportVariableToView('search', $this->mSearch); // json $json = $this->mSearch->toJson(); $encoded_alert = base64_encode(osc_encrypt_alert($json)); // Create the HMAC signature and convert the resulting hex hash into base64 $stringToSign = osc_get_alert_public_key() . $encoded_alert; $signature = hex2b64(hmacsha1(osc_get_alert_private_key(), $stringToSign)); $server_signature = Session::newInstance()->_set('alert_signature', $signature); $this->_exportVariableToView('search_alert', $encoded_alert); // calling the view... if (count($aItems) === 0) { header('HTTP/1.1 404 Not Found'); } osc_run_hook("after_search"); if (!Params::existParam('sFeed')) { $this->doView('search.php'); } else { if ($p_sFeed == '' || $p_sFeed == 'rss') { // FEED REQUESTED! header('Content-type: text/xml; charset=utf-8'); $feed = new RSSFeed(); $feed->setTitle(__('Latest listings added') . ' - ' . osc_page_title()); $feed->setLink(osc_base_url()); $feed->setDescription(__('Latest listings added in') . ' ' . osc_page_title()); if (osc_count_items() > 0) { while (osc_has_items()) { if (osc_count_item_resources() > 0) { osc_has_item_resources(); $feed->addItem(array('title' => osc_item_title(), 'link' => htmlentities(osc_item_url(), ENT_COMPAT, "UTF-8"), 'description' => osc_item_description(), 'country' => osc_item_country(), 'region' => osc_item_region(), 'city' => osc_item_city(), 'city_area' => osc_item_city_area(), 'category' => osc_item_category(), 'dt_pub_date' => osc_item_pub_date(), 'image' => array('url' => htmlentities(osc_resource_thumbnail_url(), ENT_COMPAT, "UTF-8"), 'title' => osc_item_title(), 'link' => htmlentities(osc_item_url(), ENT_COMPAT, "UTF-8")))); } else { $feed->addItem(array('title' => osc_item_title(), 'link' => htmlentities(osc_item_url(), ENT_COMPAT, "UTF-8"), 'description' => osc_item_description(), 'country' => osc_item_country(), 'region' => osc_item_region(), 'city' => osc_item_city(), 'city_area' => osc_item_city_area(), 'category' => osc_item_category(), 'dt_pub_date' => osc_item_pub_date())); } } } osc_run_hook('feed', $feed); $feed->dumpXML(); } else { osc_run_hook('feed_' . $p_sFeed, $aItems); } } }
# Three different ways to compute the HMAC in PHP. # Since PHP 5.0.12 there is a native method 'hash_hmac', please use this if you can # For PHP 4, the "Local implementation" may be easiest (but please consider upgrading to PHP5) $secret = "Kah942*$7sdp0)"; $plaintext = "10000GBP2007-10-20Internet Order 123454aD37dJATestMerchant2007-10-11T11:00:00Z"; # result should be x58ZcRVL1H6y+XSeBGrySJ9ACVo= # PEAR Crypt_HMAC # install using "pear install Crypt_HMAC" require '/usr/share/php/Crypt/HMAC.php'; print "PHP5 native implementation computed: " . base64_encode(hash_hmac('sha1',$plaintext,$secret,true)) . "\n"; print "PEAR Crypt_HMAC computed: " . base64_encode(pack('H*',hmacsha1_pear($secret,$plaintext))) . "\n"; print "Local implementation computed: " . base64_encode(pack('H*',hmacsha1($secret,$plaintext))) . "\n"; function hmacsha1_pear($key,$data) { $Crypt_HMAC = new Crypt_HMAC($key, 'sha1'); return $Crypt_HMAC->hash($data); } //Calculate HMAC-SHA1 according to RFC2104 // http://www.ietf.org/rfc/rfc2104.txt function hmacsha1($key,$data) { $blocksize=64; $hashfunc='sha1'; if (strlen($key)>$blocksize) $key=pack('H*', $hashfunc($key)); $key=str_pad($key,$blocksize,chr(0x00)); $ipad=str_repeat(chr(0x36),$blocksize);
$ipad = str_repeat(chr(0x36), $blocksize); $opad = str_repeat(chr(0x5c), $blocksize); $hmac = pack('H*', $hashfunc(($key ^ $opad) . pack('H*', $hashfunc(($key ^ $ipad) . $data)))); return bin2hex($hmac); } /* * Used to encode a field for Amazon Auth * (taken from the Amazon S3 PHP example library) */ function hex2b64($str) { $raw = ''; for ($i = 0; $i < strlen($str); $i += 2) { $raw .= chr(hexdec(substr($str, $i, 2))); } return base64_encode($raw); } if (count($argv) != 3) { echo "Usage: " . $argv[0] . " <S3 Policy File> <S3 secret key>\n"; exit(1); } $policy = file_get_contents($argv[1]); $secret = $argv[2]; /* * Base64 encode the Policy Document and then * create HMAC SHA-1 signature of the base64 encoded policy * using the secret key. Finally, encode it for Amazon Authentication. */ $base64_policy = base64_encode($policy); $signature = hex2b64(hmacsha1($secret, $base64_policy)); echo "S3_POLICY=\"" . $base64_policy . "\"\nS3_SIGNATURE=\"" . $signature . "\"\n";
function authenticateStream() { global $cfg, $db; header('Expires: Mon, 9 Oct 2000 18:00:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate'); $track_id = get('track_id'); $stream_id = (int) get('stream_id'); $sid = get('sid'); $hash = get('hash'); $query = mysql_query('SELECT logged_in, idle_time, user_id, ip FROM session WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"'); $session = mysql_fetch_assoc($query); $query = mysql_query('SELECT access_stream FROM user WHERE user_id = ' . (int) $session['user_id']); $user = mysql_fetch_assoc($query); if ($session['logged_in'] && $session['idle_time'] + $cfg['session_lifetime'] > time() && $session['ip'] == $_SERVER['REMOTE_ADDR'] && $hash == hmacsha1($cfg['server_seed'], $track_id . $stream_id . $sid) && $user['access_stream']) { mysql_query('UPDATE session SET idle_time = ' . (int) time() . ', hit_counter = hit_counter + 1, visit_counter = visit_counter + ' . (time() > $session['idle_time'] + 3600 ? 1 : 0) . ' WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"'); return true; } header('HTTP/1.1 403 Forbidden'); exit; }
function updateUser($user_id) { global $cfg, $db; authenticate('access_admin', false, true, true); $new_username = post('new_username'); $new_password = post('new_password'); $chk_password = post('chk_password'); $access_media = post('access_media') ? 1 : 0; $access_popular = post('access_popular') ? 1 : 0; $access_favorite = post('access_favorite') ? 1 : 0; $access_playlist = post('access_playlist') ? 1 : 0; $access_play = post('access_play') ? 1 : 0; $access_add = post('access_add') ? 1 : 0; $access_stream = post('access_stream') ? 1 : 0; $access_download = post('access_download') ? 1 : 0; $access_cover = post('access_cover') ? 1 : 0; $access_record = post('access_record') ? 1 : 0; $access_statistics = post('access_statistics') ? 1 : 0; $access_admin = post('access_admin') ? 1 : 0; $query = mysql_query('SELECT user_id FROM user WHERE user_id = ' . (int) $user_id); if (mysql_fetch_row($query) == false && $user_id != '0') { message(__FILE__, __LINE__, 'error', '[b]Error[/b][br]user_id not found in database'); } $query = mysql_query('SELECT user_id FROM user WHERE user_id != ' . (int) $user_id . ' AND username = "******"'); if (mysql_fetch_row($query)) { message(__FILE__, __LINE__, 'warning', '[b]Username already exist[/b][br]Choose another username[br][url=users.php?action=editUser&user_id=' . rawurlencode($user_id) . '][img]small_back.png[/img]Back to previous page[/url]'); } if ($new_password == hmacsha1(hmacsha1('', $cfg['session_seed']), $cfg['session_seed'])) { $password_set = false; } else { $password_set = true; } if (preg_match('#^[0-9a-f]{40}$#', $new_password) == false) { message(__FILE__, __LINE__, 'error', '[b]Password error[/b][br]This is not a valid hash'); } if ($new_password != $chk_password) { message(__FILE__, __LINE__, 'warning', '[b]Passwords are not identical[/b][br][url=users.php?action=editUser&user_id=' . rawurlencode($user_id) . '][img]small_back.png[/img]Back to previous page[/url]'); } if (!$password_set && $user_id == '0' && $new_username != $cfg['anonymous_user']) { message(__FILE__, __LINE__, 'warning', '[b]Password must be set for a new user[/b][br][url=users.php?action=editUser&user_id=0][img]small_back.png[/img]Back to previous page[/url]'); } if ($new_username == '') { message(__FILE__, __LINE__, 'warning', '[b]Username must be set[/b][br][url=users.php?action=editUser&user_id=' . rawurlencode($user_id) . '][img]small_back.png[/img]Back to previous page[/url]'); } if ($access_admin == false) { if (checkAdminAcount($user_id) == false) { message(__FILE__, __LINE__, 'warning', '[b]There must be at least one user with admin privilege[/b][br][url=users.php?action=editUser&user_id=' . rawurlencode($user_id) . '][img]small_back.png[/img]Back to previous page[/url]'); } } if (($password_set || $user_id == '0') && $new_username == $cfg['anonymous_user']) { $new_password = hmacsha1(hmacsha1($cfg['anonymous_user'], $cfg['session_seed']), $cfg['session_seed']); $password_set = true; } if ($user_id == '0') { mysql_query('INSERT INTO user (username) VALUES ("")'); $user_id = mysql_insert_id($db); } if ($password_set) { mysql_query('UPDATE user SET username = "******", password = "******", seed = "' . mysql_real_escape_string($cfg['session_seed']) . '", version = 1, access_media = ' . (int) $access_media . ', access_popular = ' . (int) $access_popular . ', access_favorite = ' . (int) $access_favorite . ', access_playlist = ' . (int) $access_playlist . ', access_play = ' . (int) $access_play . ', access_add = ' . (int) $access_add . ', access_stream = ' . (int) $access_stream . ', access_download = ' . (int) $access_download . ', access_cover = ' . (int) $access_cover . ', access_record = ' . (int) $access_record . ', access_statistics = ' . (int) $access_statistics . ', access_admin = ' . (int) $access_admin . ' WHERE user_id = ' . (int) $user_id); mysql_query('UPDATE session SET logged_in = 0 WHERE user_id = ' . (int) $user_id); } else { mysql_query('UPDATE user SET username = "******", access_media = ' . (int) $access_media . ', access_popular = ' . (int) $access_popular . ', access_favorite = ' . (int) $access_favorite . ', access_playlist = ' . (int) $access_playlist . ', access_play = ' . (int) $access_play . ', access_add = ' . (int) $access_add . ', access_stream = ' . (int) $access_stream . ', access_download = ' . (int) $access_download . ', access_cover = ' . (int) $access_cover . ', access_record = ' . (int) $access_record . ', access_statistics = ' . (int) $access_statistics . ', access_admin = ' . (int) $access_admin . ' WHERE user_id = ' . (int) $user_id); } }
/* //* overlay plugin 1.0
$s3keystart = $GLOBALS['settings']['s3']['paths']['job-input']['@attributes']['value']; $s3acl = $GLOBALS['settings']['s3']['upload']['default-acl']['@attributes']['value']; $aws_secret_access_key = $GLOBALS['settings']['s3']['secret-key']['@attributes']['value']; $aws_access_key = $GLOBALS['settings']['s3']['access-key']['@attributes']['value']; $s3timestamp = $GLOBALS['settings']['s3']['file-expiration']['@attributes']['value']; $s3filename = $s3keystart . "/" . sha1(time() . $qn) . ".\${filename}"; //what extension to use? //$s3redirect=str_replace("{uri}",$this_server_url,$s3redirect); //$s3redirect=str_replace("{qid}",$qn,$s3redirect); $policy_doc = "{'expiration': '{$s3timestamp}','conditions': [ {'bucket': '{$s3bucket}'},['starts-with', '\$key', '{$s3keystart}'],{'acl': '{$s3acl}'},{'success_action_redirect': '{$s3redirect}'},['starts-with', '\$Content-Type', ''],['content-length-range', 0, 104857600000]]}"; $policy_doc_encoded = base64_encode($policy_doc); //echo $policy_doc."<br/>"; //$signature = urlencode(base64_encode(hash_hmac("sha1",utf8_encode($policy_doc_encoded),$aws_secret_access_key,true))); //$signature = (base64_encode(hash_hmac("sha1",($policy_doc_encoded),$aws_secret_access_key))); //$signature = base64_encode(hash_hmac('sha256', $policy_doc, $aws_secret_access_key, true)); $signature = hex2b64(hmacsha1($aws_secret_access_key, $policy_doc_encoded)); //echo $signature."<br/>"; echo "<form style='display:inline;' action='https://{$s3bucket}.s3.amazonaws.com/' method='post' enctype='multipart/form-data'>"; echo "<input type='hidden' name='key' value='{$s3filename}'>"; echo "<input type='hidden' name='AWSAccessKeyId' value='{$aws_access_key}'>"; echo "<input type='hidden' name='acl' value='{$s3acl}'>"; echo "<input type='hidden' name='success_action_redirect' value='{$s3redirect}'>"; echo "<input type='hidden' name='policy' value='{$policy_doc_encoded}'>"; echo "<input type='hidden' name='signature' value='{$signature}'>"; echo "<input type='hidden' name='Content-Type' value='application/octet-stream'>"; echo "<input name='file' value='Browse...' type='file' style='background-color:" . rcolor() . ";display:inline;'><input type='submit' value='"; echo getTranslation("Start File Upload", $settings); echo "' style='background-color:" . rcolor() . ";display:inline;'>"; echo "</form>"; } else { echo getTranslation("Not available in demo", $settings);
function randomHex() { ob_start(); phpinfo(); $data = ob_get_contents(); ob_end_clean(); return hmacsha1(uniqid('', true), $data); }
function euplatesc_mac($data, $key) { $str = NULL; foreach ($data as $d) { if ($d === NULL || strlen($d) == 0) { $str .= '-'; } else { $str .= strlen($d) . $d; } } $key = pack('H*', $key); // convertim codul secret intr-un string binar return hmacsha1($key, $str); }
function sign_hmacsha1($key, $data) { return base64_encode(hmacsha1($key, $data)); }
function decode_url($url) { // return str_replace(array('&', '&'), '&', base64_decode(rawurldecode($url))); // We extract the SHA1 and the URL. $s = rawurldecode($url); $hmac = substr($s, 0, 40); $encrypted_url = substr($s, 40, strlen($s) - 40); // Make sure hmac is correct if ($hmac != hmacsha1($_SESSION['randomkey'], $encrypted_url)) { echo "Wrong hmac."; exit; // Violent, but effective. } // Decrypt the URL: $cleartext_url = XORDecrypt64($encrypted_url, $_SESSION['randomkey']); return str_replace(array('&', '&'), '&', $cleartext_url); // --- SSE end }
function doModel() { //specific things for this class switch ($this->action) { case 'bulk_actions': break; case 'regions': //Return regions given a countryId $regions = Region::newInstance()->findByCountry(Params::getParam("countryId")); echo json_encode($regions); break; case 'cities': //Returns cities given a regionId $cities = City::newInstance()->findByRegion(Params::getParam("regionId")); echo json_encode($cities); break; case 'location': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term")); foreach ($cities as $k => $city) { $cities[$k]['label'] = $city['label'] . " (" . $city['region'] . ")"; } echo json_encode($cities); break; case 'location_countries': // This is the autocomplete AJAX $countries = Country::newInstance()->ajax(Params::getParam("term")); echo json_encode($countries); break; case 'location_regions': // This is the autocomplete AJAX $regions = Region::newInstance()->ajax(Params::getParam("term"), Params::getParam("country")); echo json_encode($regions); break; case 'location_cities': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term"), Params::getParam("region")); echo json_encode($cities); break; case 'delete_image': // Delete images via AJAX $ajax_photo = Params::getParam('ajax_photo'); $id = Params::getParam('id'); $item = Params::getParam('item'); $code = Params::getParam('code'); $secret = Params::getParam('secret'); $json = array(); if ($ajax_photo != '') { $files = Session::newInstance()->_get('ajax_files'); $success = false; foreach ($files as $uuid => $file) { if ($file == $ajax_photo) { $filename = $files[$uuid]; unset($files[$uuid]); Session::newInstance()->_set('ajax_files', $files); $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename); break; } } echo json_encode(array('success' => $success, 'msg' => $success ? _m('The selected photo has been successfully deleted') : _m("The selected photo couldn't be deleted"))); return false; } if (Session::newInstance()->_get('userId') != '') { $userId = Session::newInstance()->_get('userId'); $user = User::newInstance()->findByPrimaryKey($userId); } else { $userId = null; $user = null; } // Check for required fields if (!(is_numeric($id) && is_numeric($item) && preg_match('/^([a-z0-9]+)$/i', $code))) { $json['success'] = false; $json['msg'] = _m("The selected photo couldn't be deleted, the url doesn't exist"); echo json_encode($json); return false; } $aItem = Item::newInstance()->findByPrimaryKey($item); // Check if the item exists if (count($aItem) == 0) { $json['success'] = false; $json['msg'] = _m("The listing doesn't exist"); echo json_encode($json); return false; } if (!osc_is_admin_user_logged_in()) { // Check if the item belong to the user if ($userId != null && $userId != $aItem['fk_i_user_id']) { $json['success'] = false; $json['msg'] = _m("The listing doesn't belong to you"); echo json_encode($json); return false; } // Check if the secret passphrase match with the item if ($userId == null && $aItem['fk_i_user_id'] == null && $secret != $aItem['s_secret']) { $json['success'] = false; $json['msg'] = _m("The listing doesn't belong to you"); echo json_encode($json); return false; } } // Does id & code combination exist? $result = ItemResource::newInstance()->existResource($id, $code); if ($result > 0) { $resource = ItemResource::newInstance()->findByPrimaryKey($id); if ($resource['fk_i_item_id'] == $item) { // Delete: file, db table entry if (defined(OC_ADMIN)) { osc_deleteResource($id, true); Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'admin', osc_logged_admin_id()); } else { osc_deleteResource($id, false); Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'user', osc_logged_user_id()); } ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $item, 's_name' => $code)); $json['msg'] = _m('The selected photo has been successfully deleted'); $json['success'] = 'true'; } else { $json['msg'] = _m("The selected photo does not belong to you"); $json['success'] = 'false'; } } else { $json['msg'] = _m("The selected photo couldn't be deleted"); $json['success'] = 'false'; } echo json_encode($json); return true; break; case 'alerts': // Allow to register to an alert given (not sure it's used on admin) $encoded_alert = Params::getParam("alert"); $alert = osc_decrypt_alert(base64_decode($encoded_alert)); // check alert integrity / signature $stringToSign = osc_get_alert_public_key() . $encoded_alert; $signature = hex2b64(hmacsha1(osc_get_alert_private_key(), $stringToSign)); $server_signature = Session::newInstance()->_get('alert_signature'); if ($server_signature != $signature) { echo '-2'; return false; } $email = Params::getParam("email"); $userid = Params::getParam("userid"); if (osc_is_web_user_logged_in()) { $userid = osc_logged_user_id(); $user = User::newInstance()->findByPrimaryKey($userid); $email = $user['s_email']; } if ($alert != '' && $email != '') { if (osc_validate_email($email)) { $secret = osc_genRandomPassword(); if ($alertID = Alerts::newInstance()->createAlert($userid, $email, $alert, $secret)) { if ((int) $userid > 0) { $user = User::newInstance()->findByPrimaryKey($userid); if ($user['b_active'] == 1 && $user['b_enabled'] == 1) { Alerts::newInstance()->activate($alertID); echo '1'; return true; } else { echo '-1'; return false; } } else { $aAlert = Alerts::newInstance()->findByPrimaryKey($alertID); osc_run_hook('hook_email_alert_validation', $aAlert, $email, $secret); } echo "1"; } else { echo "0"; } return true; } else { echo '-1'; return false; } } echo '0'; return false; break; case 'runhook': // run hooks $hook = Params::getParam('hook'); if ($hook == '') { echo json_encode(array('error' => 'hook parameter not defined')); break; } switch ($hook) { case 'item_form': osc_run_hook('item_form', Params::getParam('catId')); break; case 'item_edit': $catId = Params::getParam("catId"); $itemId = Params::getParam("itemId"); osc_run_hook("item_edit", $catId, $itemId); break; default: osc_run_hook('ajax_' . $hook); break; } break; case 'custom': // Execute via AJAX custom file if (Params::existParam('route')) { $routes = Rewrite::newInstance()->getRoutes(); $rid = Params::getParam('route'); $file = '../'; if (isset($routes[$rid]) && isset($routes[$rid]['file'])) { $file = $routes[$rid]['file']; } } else { // DEPRECATED: Disclosed path in URL is deprecated, use routes instead // This will be REMOVED in 3.4 $file = Params::getParam('ajaxfile'); } if ($file == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || stripos($file, '/admin/') !== false) { //If the file is inside an "admin" folder, it should NOT be opened in frontend echo json_encode(array('error' => 'no valid ajaxFile')); break; } if (!file_exists(osc_plugins_path() . $file)) { echo json_encode(array('error' => "ajaxFile doesn't exist")); break; } require_once osc_plugins_path() . $file; break; case 'check_username_availability': $username = osc_sanitize_username(Params::getParam('s_username')); if (!osc_is_username_blacklisted($username)) { $user = User::newInstance()->findByUsername($username); if (isset($user['s_username'])) { echo json_encode(array('exists' => 1, 's_username' => $username)); } else { echo json_encode(array('exists' => 0, 's_username' => $username)); } } else { echo json_encode(array('exists' => 1, 's_username' => $username)); } break; case 'ajax_upload': // Include the uploader class require_once LIB_PATH . "AjaxUploader.php"; $uploader = new AjaxUploader(); $original = pathinfo($uploader->getOriginalName()); $filename = uniqid("qqfile_") . "." . $original['extension']; $result = $uploader->handleUpload(osc_content_path() . 'uploads/temp/' . $filename); $result['uploadName'] = $filename; echo htmlspecialchars(json_encode($result), ENT_NOQUOTES); break; case 'ajax_validate': $id = Params::getParam('id'); if (!is_numeric($id)) { echo json_encode(array('success' => false)); die; } $secret = Params::getParam('secret'); $item = Item::newInstance()->findByPrimaryKey($id); if ($item['s_secret'] != $secret) { echo json_encode(array('success' => false)); die; } $nResources = ItemResource::newInstance()->countResources($id); $result = array('success' => $nResources < osc_max_images_per_item(), 'count' => $nResources); echo json_encode($result); break; case 'delete_ajax_upload': $files = Session::newInstance()->_get('ajax_files'); $success = false; $filename = ''; if (isset($files[Params::getParam('qquuid')]) && $files[Params::getParam('qquuid')] != '') { $filename = $files[Params::getParam('qquuid')]; unset($files[Params::getParam('qquuid')]); Session::newInstance()->_set('ajax_files', $files); $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename); } echo json_encode(array('success' => $success, 'uploadName' => $filename)); break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
public function check($access, $cache = false, $validate_sign = false, $disable_counter = false) { global $cfg; if ($cache == false && headers_sent() == false) { header('Expires: Mon, 9 Oct 2000 18:00:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate'); } $sid = $this->app->getCookie('netjukebox_sid'); $authenticate = $this->app->request->params('authenticate'); $result = $this->app->db->query(' SELECT logged_in, user_id, idle_time, ip, user_agent, sign, seed, skin, random_blacklist, thumbnail, thumbnail_size, stream_id, download_id, player_id FROM session WHERE sid = BINARY "' . $this->app->db->real_escape_string($sid) . '"'); $session = $result->fetch_assoc(); //setSkin($session['skin']); // Validate login if ($authenticate == 'validate') { $username = $this->app->request->post('username'); $hash1 = $this->app->request->post('hash1'); $hash2 = $this->app->request->post('hash2'); $sign = $this->app->request->post('sign'); if ($session['ip'] == '') { message(__FILE__, __LINE__, 'error', '[b]Login failed[/b][br]netjukebox requires cookies to login.[br]Enable cookies in your browser and try again.[br][url=index.php][img]small_login.png[/img]login[/url]'); } if ($session['ip'] != $_SERVER['REMOTE_ADDR']) { message(__FILE__, __LINE__, 'error', '[b]Login failed[/b][br]Unexpected IP address[br][url=index.php][img]small_login.png[/img]login[/url]'); } $query = mysql_query('SELECT ' . (string) round(microtime(true) * 1000) . ' - pre_login_time AS login_delay FROM session WHERE ip = "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '" ORDER BY pre_login_time DESC LIMIT 1'); $ip = mysql_fetch_assoc($query); $query = mysql_query('SELECT password, seed, version, user_id FROM user WHERE username = "******"'); $user = mysql_fetch_assoc($query); $user_id = $user['user_id']; if (($user['version'] == 0 && $user['password'] == sha1($hash1) || $user['version'] == 1 && $user['password'] == hmacsha1($hash1, $user['seed'])) && preg_match('#^[0-9a-f]{40}$#', $hash1) && preg_match('#^[0-9a-f]{40}$#', $hash2) && ($username == $cfg['anonymous_user'] && $hash2 == hmacsha1(hmacsha1($cfg['anonymous_user'], $session['seed']), $session['seed']) || $username != $cfg['anonymous_user'] && $hash2 != hmacsha1(hmacsha1('', $session['seed']), $session['seed'])) && $ip['login_delay'] > $cfg['login_delay'] && $session['user_agent'] == substr($_SERVER['HTTP_USER_AGENT'], 0, 255) && $session['sign'] == $sign) { mysql_query('UPDATE user SET password = "******", seed = "' . mysql_real_escape_string($session['seed']) . '", version = 1 WHERE username = "******"'); $sign = randomKey(); $sid = randomKey(); mysql_query('UPDATE session SET logged_in = 1, user_id = ' . (int) $user_id . ', login_time = ' . (int) time() . ', idle_time = ' . (int) time() . ', sid = "' . mysql_real_escape_string($sid) . '", sign = "' . mysql_real_escape_string($sign) . '", hit_counter = hit_counter + ' . ($disable_counter ? 0 : 1) . ', visit_counter = visit_counter + ' . (time() > $session['idle_time'] + 3600 ? 1 : 0) . ' WHERE sid = BINARY "' . mysql_real_escape_string(cookie('netjukebox_sid')) . '"'); setcookie('netjukebox_sid', $sid, time() + 31536000, null, null, NJB_HTTPS, true); @ob_flush(); flush(); } else { logoutSession(); } } else { // Validate current session $user_id = $session['user_id']; if ($session['logged_in'] && $session['ip'] == $_SERVER['REMOTE_ADDR'] && $session['user_agent'] == substr($_SERVER['HTTP_USER_AGENT'], 0, 255) && $session['idle_time'] + $cfg['session_lifetime'] > time()) { mysql_query('UPDATE session SET idle_time = ' . (int) time() . ', hit_counter = hit_counter + ' . ($disable_counter ? 0 : 1) . ', visit_counter = visit_counter + ' . (time() > $session['idle_time'] + 3600 ? 1 : 0) . ' WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"'); } elseif ($access == 'access_always') { $cfg['access_media'] = false; $cfg['access_popular'] = false; $cfg['access_favorite'] = false; $cfg['access_cover'] = false; $cfg['access_stream'] = false; $cfg['access_download'] = false; $cfg['access_playlist'] = false; $cfg['access_play'] = false; $cfg['access_add'] = false; $cfg['access_record'] = false; $cfg['access_statistics'] = false; $cfg['access_admin'] = false; return true; } else { $app->ll->str('böla'); logoutSession(); } } // Username & user privalages unset($cfg['username']); $query = mysql_query('SELECT username, access_media, access_popular, access_favorite, access_cover, access_stream, access_download, access_playlist, access_play, access_add, access_record, access_statistics, access_admin FROM user WHERE user_id = ' . (int) $user_id); $cfg += mysql_fetch_assoc($query); // Validate privilege $access_validated = false; if (is_array($access)) { foreach ($access as $value) { if (isset($cfg[$value]) && $cfg[$value]) { $access_validated = true; } } } elseif (isset($cfg[$access]) && $cfg[$access]) { $access_validated = true; } elseif ($access == 'access_logged_in') { $access_validated = true; } elseif ($access == 'access_always') { $access_validated = true; } if ($access_validated == false) { message(__FILE__, __LINE__, 'warning', '[b]You have no privilege to access this page[/b][br][url=index.php?authenticate=logout][img]small_login.png[/img]Login as another user[/url]'); } // Validate signature if ($cfg['sign_validated'] == false && ($validate_sign || $authenticate == 'logoutAllSessions' || $authenticate == 'logoutSession')) { $cfg['sign'] = randomKey(); mysql_query('UPDATE session SET sign = "' . mysql_real_escape_string($cfg['sign']) . '" WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"'); if ($session['sign'] == getpost('sign')) { $cfg['sign_validated'] = true; } else { message(__FILE__, __LINE__, 'error', '[b]Signature expired[/b]'); } } else { $cfg['sign'] = $session['sign']; } // Logout if ($authenticate == 'logout' && $cfg['username'] != $cfg['anonymous_user']) { $query = mysql_query('SELECT user_id FROM session WHERE logged_in AND user_id = ' . (int) $user_id . ' AND idle_time > ' . (int) (time() - $cfg['session_lifetime'])); if (mysql_affected_rows($db) > 1) { logoutMenu(); } else { logoutSession(); } } elseif ($authenticate == 'logoutAllSessions' && $cfg['username'] != $cfg['anonymous_user']) { mysql_query('UPDATE session SET logged_in = 0 WHERE user_id = ' . (int) $user_id); logoutSession(); } elseif ($authenticate == 'logoutSession' || $authenticate == 'logout') { logoutSession(); } $cfg['user_id'] = $user_id; $cfg['sid'] = $sid; $cfg['session_seed'] = $session['seed']; $cfg['random_blacklist'] = $session['random_blacklist']; //$cfg['thumbnail'] = $session['thumbnail']; $cfg['thumbnail'] = 1; //$cfg['thumbnail_size'] = $session['thumbnail_size']; $cfg['thumbnail_size'] = 100; $cfg['stream_id'] = isset($cfg['encode_extension'][$session['stream_id']]) ? $session['stream_id'] : -1; $cfg['download_id'] = isset($cfg['encode_extension'][$session['download_id']]) ? $session['download_id'] : -1; $cfg['player_id'] = $session['player_id']; }
function loginStage1() { global $cfg, $db; header('Expires: Mon, 9 Oct 2000 18:00:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate'); $sid = cookie('netjukebox_sid'); $username = post('username'); $sign = post('sign'); $query = mysql_query('SELECT seed FROM user WHERE username = "******"'); $user = mysql_fetch_assoc($query); $query = mysql_query('SELECT ip, seed, sign FROM session WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"'); $session = mysql_fetch_assoc($query); if ($session['ip'] == '') { message(__FILE__, __LINE__, 'error', '[b]Login failed[/b][br]netjukebox requires cookies to login.[br]Enable cookies in your browser and try again.[br][url=index.php][img]small_login.png[/img]login[/url]'); } if ($session['ip'] != $_SERVER['REMOTE_ADDR']) { message(__FILE__, __LINE__, 'error', '[b]Login failed[/b][br]Unexpected IP address[br][url=index.php][img]small_login.png[/img]login[/url]'); } if (hmacsha1($cfg['server_seed'], $session['sign']) == $sign) { $sign = randomKey(); mysql_query('UPDATE session SET sign = "' . mysql_real_escape_string($sign) . '", pre_login_time = ' . (string) round(microtime(true) * 1000) . ' WHERE sid = BINARY "' . mysql_real_escape_string($sid) . '"'); } else { // login will fail! $sign = randomKey(); } // Always calculate fake seed to prevent script execution time differences $fake_seed = substr(hmacsha1($cfg['server_seed'], $username . 'NeZlFgqDoh9hc-BkczryQFIcpoBng3I_vXaWtOKS'), 0, 30); $fake_seed .= substr(hmacsha1($cfg['server_seed'], $username . 'g-FE6H0MJ1n0lNo2D7XLachV8WE-xmEcwsXNZqlQ'), 0, 30); $fake_seed = base64_encode(pack('H*', $fake_seed)); $fake_seed = str_replace('+', '-', $fake_seed); // modified Base64 for URL $fake_seed = str_replace('/', '_', $fake_seed); $data = array(); $data['user_seed'] = $user['seed'] == '' ? $fake_seed : $user['seed']; $data['session_seed'] = $session['seed']; $data['sign'] = $sign; echo safe_json_encode($data); }