function web_controller_user_profile() { lets_use('user_self', 'billing_log'); $balance = user_self_balance(); $transactions = billing_log_get_user_transactions(user_self_id()); web_router_render_page('user', 'profile', ['balance' => $balance, 'transactions' => $transactions]); }
function billing_description_account_owner_names($accData) { lets_use('billing_account'); if (!$accData) { return []; } $users = $sources = $result = []; foreach ($accData as &$accInfo) { $id = $accInfo[BILLING_ACCOUNT_FIELD_ID]; $ownerId = $accInfo[BILLING_ACCOUNT_FIELD_OWNER_ID]; switch ($accInfo[BILLING_ACCOUNT_FIELD_TYPE]) { case BILLING_ACCOUNT_TYPE_USER_MAIN: case BILLING_ACCOUNT_TYPE_USER_LOCKED: $users[$id] = $ownerId; break; case BILLING_ACCOUNT_TYPE_INCOMING: $sources[$id] = $ownerId; break; case BILLING_ACCOUNT_TYPE_SYSTEM: default: $result[$id] = ''; break; } } lets_use('storage_db'); $userNames = storage_db_get_rows('users', ['id', 'name'], [['id', $users]], [], 'id'); $sourcesNames = storage_db_get_rows('money_source', ['id', 'name'], ['id', $sources], [], 'id'); foreach ($users as $accId => $userId) { $result[$accId] = isset($userNames[$userId]) ? $userNames[$userId]['name'] : ''; } foreach ($sources as $accId => $sourceId) { $result[$accId] = isset($sourcesNames[$sourceId]) ? $sourcesNames[$sourceId]['name'] : ''; } return $result; }
function web_router_call($controller, $action, $uri) { $module = 'web_controller_' . $controller; lets_use($module); // pre dispatch $function = $module . '_precall'; if (function_exists($function)) { try { $function(); } catch (Exception $e) { web_router_error($e->getMessage()); // @todo show error only in debug return; } } // dispatch $function = $module . '_' . $action; if (!function_exists($function)) { web_router_notfound($uri); return; } try { $function(); } catch (Exception $e) { web_router_error(''); return; } }
function core_init($appRole) { global $_core_start_time; $_core_start_time = microtime(1); lets_use('core_config'); core_config_load(); }
function billing_log_get_user_transactions($userId) { lets_use('billing_account', 'billing_transaction', 'billing_description'); $userMain = billing_account_get_account($userId, BILLING_ACCOUNT_TYPE_USER_MAIN, false); $acc[] = $userMain; $acc[] = billing_account_get_account($userId, BILLING_ACCOUNT_TYPE_USER_LOCKED, false); $acc = array_filter($acc); if (!$acc) { return []; } $tr = billing_transaction_get_accounts_transactions($acc); $types = billing_description_transaction_types(); $accIds = array_unique(array_merge(array_column($tr, BILLING_TRANSACTION_FIELD_ACC_FROM), array_column($tr, BILLING_TRANSACTION_FIELD_ACC_TO))); $accData = billing_account_get_accounts($accIds); $ownersNames = billing_description_account_owner_names($accData); foreach ($tr as &$transaction) { $transaction['str_type'] = isset($types[$transaction[BILLING_TRANSACTION_FIELD_TYPE]]) ? $types[$transaction[BILLING_TRANSACTION_FIELD_TYPE]] : $types[0]; $transaction['target_action'] = $transaction[BILLING_TRANSACTION_FIELD_ACC_FROM] == $userId ? 'в счет' : 'из'; $transaction['prefix'] = $transaction[BILLING_TRANSACTION_FIELD_TYPE] == BILLING_TRANSACTION_TYPE_REFILL ? 'источника' : ''; if ($transaction[BILLING_TRANSACTION_FIELD_ACC_FROM] == $userMain) { $transaction['target_owner'] = $ownersNames[$transaction[BILLING_TRANSACTION_FIELD_ACC_TO]]; } else { $transaction['target_owner'] = $ownersNames[$transaction[BILLING_TRANSACTION_FIELD_ACC_FROM]]; } $transaction['success'] = $transaction['status'] == BILLING_TRANSACTION_STATUS_SUCCESS; } return $tr; }
/** * @param $redisId * * @return Redis|bool */ function _storage_nosql_connect($redisId) { static $allConnectionsConfig; static $connections; lets_use('core_config'); if (isset($connections[$redisId])) { return $connections[$redisId]; } if (!isset($allConnectionsConfig)) { $allConnectionsConfig = core_config_get('redis', []); } if (!isset($allConnectionsConfig[$redisId])) { core_error('redis config not found for id:' . serialize($redisId)); return false; } $connectionConfig = $allConnectionsConfig[$redisId]; $connection = new Redis(); $connected = $connection->connect($connectionConfig['host'], $connectionConfig['port'], $connectionConfig['connect_timeout']); if (!$connected) { core_error('Cannot connect redis driver'); return false; } $connection->setOption(Redis::OPT_READ_TIMEOUT, $connectionConfig['read_timeout']); return $connections[$redisId] = $connection; }
function billing_account_get_accounts($accIds) { lets_use('storage_db'); if (!$accIds) { return []; } return storage_db_get_rows(BILLING_ACCOUNT_DB_TABLE, '*', [[BILLING_ACCOUNT_FIELD_ID, $accIds]]); }
function web_controller_index_index() { lets_use('user_self'); if (user_self_id()) { web_router_call('order', 'list', ''); return; } web_router_render_page('index', 'index'); }
function billing_balance_set_account_amount($accountId, $amount) { lets_use('storage_db'); $bind = [BILLING_BALANCE_FIELD_ACCOUNT_ID => $accountId, BILLING_BALANCE_FIELD_AMOUNT => _billing_balance_pack_money($amount)]; $res = storage_db_set(BILLING_BALANCE_DB_TABLE, $bind); if (!$res) { core_error('cant set money amount: ' . json_encode($bind)); return false; } return true; }
function user_self_balance() { lets_use('billing_balance', 'billing_account'); $userId = user_self_id(); core_log('user_id: ' . $userId, __FUNCTION__); if (!$userId) { return 0; } $account = billing_account_get_user_main_account($userId); return billing_balance_get_account_amount($account); }
function billing_transaction_get_accounts_transactions($accounts) { lets_use('storage_db'); $income = storage_db_get_rows(BILLING_TRANSACTION_DB_TABLE, '*', [[BILLING_TRANSACTION_FIELD_ACC_TO, $accounts]]); $outcome = storage_db_get_rows(BILLING_TRANSACTION_DB_TABLE, '*', [[BILLING_TRANSACTION_FIELD_ACC_FROM, $accounts]]); $result = []; foreach ($income as $transaction) { $result[$transaction[BILLING_TRANSACTION_FIELD_STARTED] << 32 | $transaction[BILLING_TRANSACTION_FIELD_ID]] = $transaction; } foreach ($outcome as $transaction) { $result[$transaction[BILLING_TRANSACTION_FIELD_STARTED] << 32 | $transaction[BILLING_TRANSACTION_FIELD_ID]] = $transaction; } krsort($result); return $result; }
function web_controller_auth_register() { if (web_router_get_method() !== 'POST') { web_router_render_page('auth', 'register', []); return; } $email = web_router_get_param('email'); if (!$email) { web_router_render_page('auth', 'register', ['msg' => 'Введите email', 'wrong' => 'email']); return; } preg_match('/[\\w\\d]+@[\\w\\d]+[\\w\\d\\.]+/', $email, $matches); if (!isset($matches[0])) { web_router_render_page('auth', 'register', ['msg' => 'Введите корректный email', 'wrong' => 'email']); return; } lets_use('user_register'); $authUserId = user_register_get_user_id_by_email($email); if ($authUserId) { web_router_render_page('auth', 'register', ['msg' => 'Пользователь с таким email уже существует', 'wrong' => 'email']); return; } $userName = web_router_get_param('name'); if (!$userName) { web_router_render_page('auth', 'register', ['msg' => 'Введите ваше имя', 'wrong' => 'name']); return; } $pass = web_router_get_param('pass'); if (!$pass || mb_strlen($pass) < 6) { web_router_render_page('auth', 'register', ['msg' => 'Пароль должен быть задан и не менее 6ти символов', 'wrong' => 'pass']); return; } $userId = user_register_new_user($userName, $email, $pass); if (!$userId) { web_router_render_page('auth', 'register', ['msg' => 'Ошибка при сохранении пользвателя, повторите позднее', 'wrong' => 'error']); return; } lets_use('user_session'); $secret = user_session_get_secret($userId); $token = user_session_build_token($userId, $secret); user_session_write_session_cookie($userId, $token, 86400 * 30); web_router_redirect('/'); }
function _billing_locks_unlock($accountId) { lets_use('storage_lock'); $lockId = _billing_locks_get_lock_key($accountId); return storage_lock_release($lockId); }
function storage_db_transaction_begin($table) { global $_storage_db_started_transactions; $part = _storage_db_get_part($table); // transaction already started if (isset($_storage_db_started_transactions[$part])) { $_storage_db_started_transactions[$part][$table] = $table; return true; } $part = _storage_db_get_part($table); $connection = _storage_db_get_connection($part); $res = mysqli_begin_transaction($connection); if (_storage_db_check($connection, $table, 'TRANSACTION BEGIN:' . $part)) { return false; } if (!$res) { trigger_error('cant start transaction on part: ' . $part . ' for table ' . $table); return false; } $_storage_db_started_transactions[$part][$table] = $table; lets_use('core_shutdown'); core_shutdown_add_check('db_transactions_end_check', 'storage_db_transactions_end_check', false); return $res; }
function user_register_get_user_id_by_email($email) { lets_use('storage_db'); $authUserId = storage_db_get_value('users', 'id', [['email', $email]]); return $authUserId; }
function web_controller_order_mine() { lets_use('storage_db', 'order_storage', 'user_self'); $posts = order_storage_get_by_user(user_self_id()); $authors = []; if ($posts) { $authors = storage_db_get_rows('users', '*', [['id', array_unique(array_column($posts, 'author_id'))]], [], 'id'); } web_router_render_page('order', 'list', ['posts' => $posts, 'authors' => $authors]); }
<?php lets_sure_loaded('web_render'); lets_use('core'); global $_web_render_global_params; global $_web_render_scope_params; $_web_render_global_params = []; $_web_render_scope_params = []; /** * @param $key * @param string $default * * @return string|array */ function _v($key, $default = '') { global $_web_render_global_params; global $_web_render_scope_params; if (array_key_exists($key, $_web_render_scope_params)) { return $_web_render_scope_params[$key]; } if (array_key_exists($key, $_web_render_global_params)) { return $_web_render_global_params[$key]; } return $default; } function _e($string) { return nl2br(htmlspecialchars(strip_tags($string, '<br><br/><br />'))); } function web_render_page_content($module, $template, $data = [], $layout = 'main')
function storage_lock_release($lockId) { lets_use('storage_nosql', 'core_config'); return storage_nosql_set(CORE_CONFIG_REDIS_MAIN, 'cLock:' . $lockId, null); }
function web_controller_billing_refill() { lets_use('web_router', 'billing_balance', 'billing_account', 'billing_transaction', 'billing_locks', 'user_self'); $incomingSource = 1; // благотоврительный фонд $sum = (double) web_router_get_param('sum'); $sum = round($sum, 2); $accountFrom = billing_account_get_income_account($incomingSource); $accountTo = billing_account_get_user_main_account(user_self_id()); $trId = billing_transaction_register($accountFrom, $accountTo, $sum); if (!$trId) { // cant register transaction billing_transaction_fail($trId); web_router_render_page('billing', 'refill', ['result' => false, 'msg' => 'Ошибка сервера, повторите позже.']); return; } $lockRes = billing_locks_lock_transaction($trId, [$accountFrom, $accountTo]); if (!$lockRes) { // cant lock transaction billing_transaction_fail($trId); web_router_render_page('billing', 'refill', ['result' => false, 'msg' => 'В данный момент операция невозможна, повторите позже']); return; } $movementPossible = billing_balance_check_sum_available($accountFrom, $sum); if (!$movementPossible) { // not enough money billing_transaction_fail($trId); billing_locks_unlock_transaction($trId); web_router_render_page('billing', 'refill', ['result' => false, 'msg' => 'На исходящем счете недостаточно денег']); return; } $dbTransactionLock = billing_balance_storage_transaction_start(); if (!$dbTransactionLock) { // cant begin db transaction billing_transaction_fail($trId); billing_locks_unlock_transaction($trId); web_router_render_page('billing', 'refill', ['result' => false, 'msg' => 'Не удалось начать транзакцию']); return; } $moveRes = billing_balance_process_move($accountFrom, $accountTo, $sum, $trId); if (!$moveRes) { // cant move money billing_balance_storage_transaction_rollback(); billing_transaction_fail($trId); billing_locks_unlock_transaction($trId); web_router_render_page('billing', 'refill', ['result' => false, 'msg' => 'Не удалось перевести деньги']); return; } $transactionCommit = billing_balance_storage_transaction_commit(); if ($transactionCommit) { // cant commit db transaction billing_transaction_fail($trId); billing_locks_unlock_transaction($trId); web_router_render_page('billing', 'refill', ['result' => false, 'msg' => 'Не удалось завершить транзакцию']); return; } billing_transaction_success($trId); billing_locks_unlock_transaction($trId); $moneyNow = billing_balance_get_account_amount($accountTo); web_router_render_page('billing', 'refill', ['result' => true, 'msg' => $sum . ' денежных единиц успешно переведены вам на счет. На вашем счету теперь: ' . $moneyNow]); }
function user_session_write_session_cookie($userId, $token, $ttl = 86400) { lets_use('web_response'); web_response_set_cookie(USER_SESSION_COOKIE_UID, $userId, $ttl); web_response_set_cookie(USER_SESSION_COOKIE_TOKEN, $token, $ttl); }
function order_storage_get_author_list($userId) { lets_use('storage_db'); return storage_db_get_rows('orders', '*', null, ['ORDER BY' => 'id DESC']); }
<?php chdir('..'); error_reporting(1); ini_set("display_errors", 1); require_once 'letsload.php'; lets_use('core', 'web_router'); core_init('web'); web_router_route($_SERVER['REQUEST_URI'], $_GET, $_POST);