/** * Add a new user into a given project * * @param Integer $group_id Project id * @param User $user User to add * * @return Boolean */ function account_add_user_obj_to_group($group_id, User $user) { //user was found but if it's a pending account adding //is not allowed if (!$user->isActive() && !$user->isRestricted()) { $GLOBALS['Response']->addFeedback('error', $GLOBALS['Language']->getText('include_account', 'account_notactive', $user->getUserName())); return false; } //if not already a member, add it $res_member = db_query("SELECT user_id FROM user_group WHERE user_id=" . $user->getId() . " AND group_id='" . db_ei($group_id) . "'"); if (db_numrows($res_member) < 1) { //not already a member db_query("INSERT INTO user_group (user_id,group_id) VALUES (" . db_ei($user->getId()) . "," . db_ei($group_id) . ")"); //if no unix account, give them a unix_uid if ($user->getUnixStatus() == 'N' || !$user->getUnixUid()) { $user->setUnixStatus('A'); $um = UserManager::instance(); $um->assignNextUnixUid($user); $um->updateDb($user); } // Raise an event $em = EventManager::instance(); $em->processEvent('project_admin_add_user', array('group_id' => $group_id, 'user_id' => $user->getId(), 'user_unix_name' => $user->getUserName())); $GLOBALS['Response']->addFeedback('info', $GLOBALS['Language']->getText('include_account', 'user_added')); account_send_add_user_to_group_email($group_id, $user->getId()); group_add_history('added_user', $user->getUserName(), $group_id, array($user->getUserName())); return true; } else { $GLOBALS['Response']->addFeedback('error', $GLOBALS['Language']->getText('include_account', 'user_already_member')); } return false; }
/** * add identifier * * @author Matthias Pfefferle * @param User $pUser * @param AuthToken $pAuthToken * @return OnlineIdentity */ public function addIdentifier($pUser, $pCode) { $lAccessToken = $this->getAccessToken($pCode); // get params $lParamsArray = array(); // extract params parse_str($lAccessToken, $lParamsArray); $lJsonObject = json_decode(UrlUtils::sendGetRequest("https://graph.facebook.com/me?access_token=" . $lParamsArray['access_token'] . "&locale=en_US")); // facebook identifier $lIdentifier = "http://www.facebook.com/profile.php?id=" . $lJsonObject->id; // ask for online identity $lOnlineIdentity = OnlineIdentityTable::retrieveByAuthIdentifier($lIdentifier); // check if user already exists if ($lOnlineIdentity) { if ($lOnlineIdentity->getUserId() && $pUser->getId() == $lOnlineIdentity->getUserId()) { if (!$lOnlineIdentity->getActive()) { $lOnlineIdentity->setActive(true); } else { throw new sfException("online identity already added", 1); } } elseif ($lOnlineIdentity->getUserId() && $pUser->getId() != $lOnlineIdentity->getUserId()) { throw new sfException("online identity already added by someone else", 2); } } else { // check online identity $lOnlineIdentity = OnlineIdentityTable::addOnlineIdentity($lJsonObject->link, $lJsonObject->id, $this->aCommunityId); } // use api complete informations $this->completeOnlineIdentity($lOnlineIdentity, $lJsonObject, $pUser, $lIdentifier); // signup,add new AuthTokenTable::saveToken($pUser->getId(), $lOnlineIdentity->getId(), $lParamsArray['access_token'], null, true); // signup,add new return $lOnlineIdentity; }
private function _makeOperation() { $this->user = new oldUser($this->userLogin, $this->userPass); $this->userId = $this->user->getId(); $options = array('user_id' => $this->userId, 'chain_id' => 999, 'date' => date('Y-m-d', time() - 86400)); // Правильные операции, на вчера CreateObjectHelper::makeOperation($options); CreateObjectHelper::makeOperation($options); CreateObjectHelper::makeOperation($options); // Операция не выполнена $data = $options; $data['accepted'] = 0; CreateObjectHelper::makeOperation($data); // Дата операции установлена на завтра $data = $options; $data['accepted'] = 0; $data['date'] = date('Y-m-d', time() + 86400); CreateObjectHelper::makeOperation($data); // Дата операции установлена на завтра, но она отмечена выполненной $data = $options; $data['accepted'] = 1; $data['date'] = date('Y-m-d', time() + 86400); CreateObjectHelper::makeOperation($data); // Удалённая операция $data = $options; $data['accepted'] = 0; $data['deleted_at'] = '2010-02-02 02:02:02'; CreateObjectHelper::makeOperation($data); // Обычная операция, вне цепочки unset($options['deleted_at']); unset($options['chain_id']); CreateObjectHelper::makeOperation($options); }
/** * add identifier * * @author Matthias Pfefferle * @param User $pUser * @param AuthToken $pAuthToken * @return OnlineIdentity */ public function addIdentifier($pUser, $pOAuthToken) { $lAccessToken = $this->getAccessToken($pOAuthToken); // get params $lParams = $lAccessToken->params; $lParamsArray = array(); // extract params parse_str($lParams, $lParamsArray); // twitter identifier $lIdentifier = "http://twitter.com/account/profile?user_id=" . $lParamsArray['user_id']; // ask for online identity $lOnlineIdentity = OnlineIdentityTable::retrieveByAuthIdentifier($lIdentifier); // check if user already exists if ($lOnlineIdentity) { if ($lOnlineIdentity->getUserId() && $pUser->getId() == $lOnlineIdentity->getUserId()) { if (!$lOnlineIdentity->getActive()) { $lOnlineIdentity->setActive(true); } else { throw new sfException("online identity already added", 1); } } elseif ($lOnlineIdentity->getUserId() && $pUser->getId() != $lOnlineIdentity->getUserId()) { throw new sfException("online identity already added by someone else", 2); } } else { // check online identity $lOnlineIdentity = OnlineIdentityTable::addOnlineIdentity("http://twitter.com/" . $lParamsArray['screen_name'], $lParamsArray['user_id'], $this->aCommunityId); } // get api informations $lJson = OAuthClient::get($this->getConsumer(), $lParamsArray['oauth_token'], $lParamsArray['oauth_token_secret'], "https://api.twitter.com/1.1/users/show.json?user_id=" . $lParamsArray['user_id']); $lJsonObject = json_decode($lJson); $this->completeOnlineIdentity($lOnlineIdentity, $lJsonObject, $pUser, $lIdentifier); AuthTokenTable::saveToken($pUser->getId(), $lOnlineIdentity->getId(), $lParamsArray['oauth_token'], $lParamsArray['oauth_token_secret'], true); return $lOnlineIdentity; }
/** * Делаем основную работу * @param User $user * @return bool false в случае ошибки */ public function execute(User $user) { $this->_csvDataSource = new File_CSV_DataSource($this->_csvFileName); if (!$this->_testStructure()) { return false; } foreach ($this->_hydrateArrayHash() as $k => $csvOperation) { $csvOperation['ReceiptDate'] = preg_replace("/^[\\s\\S]*?(\\d{2})\\.(\\d{2})\\.(\\d{4})[\\s\\S]*?\$/", "\$3-\$2-\$1", $csvOperation['ReceiptDate']); $csvOperation['Value'] = str_replace(',', '.', $csvOperation['Value']); $account = array('user_id' => $user->getId(), 'name' => sprintf("%s (%s)", $csvOperation['Account'], $csvOperation['Currency']), 'currency_id' => $this->_getCurrencyId($csvOperation['Currency']), 'type_id' => 1); $category = !$csvOperation['Category'] ? null : array('user_id' => $user->getId(), 'name' => $csvOperation['Category'], 'custom' => 1, 'type' => $csvOperation['TransactionType'] == 'Доход' ? 1 : -1); switch ($csvOperation['TransactionType']) { case 'Доход': case 'Расход': $operation = array('user_id' => $user->getId(), 'date' => $csvOperation['ReceiptDate'], 'amount' => $csvOperation['Value'], 'comment' => $csvOperation['Comment'], 'type' => $csvOperation['TransactionType'] == 'Доход' ? Operation::TYPE_PROFIT : Operation::TYPE_EXPENSE, 'Account' => $this->_getRecordPointer('Account', $account['name'], $account), 'Category' => $this->_getRecordPointer('Category', $category['name'], $category)); break; case 'Перевод списание': $operation = array_merge($operation, array('user_id' => $user->getId(), 'date' => $csvOperation['ReceiptDate'], 'amount' => $csvOperation['Value'], 'comment' => $csvOperation['Comment'], 'type' => Operation::TYPE_TRANSFER, 'Account' => $this->_getRecordPointer('Account', $account['name'], $account))); break; case 'Перевод зачисление': $operation['transfer_amount'] = $csvOperation['Value']; $operation['TransferAccount'] = $this->_getRecordPointer('Account', $account['name'], $account); break; } if (isset($operation['TransferAccount']) && isset($operation['Account']) || isset($operation['type']) && $operation['type'] != 2) { $this->_getRecordPointer('Operation', $k, $operation); $operation = array(); } } $this->_setYmlData(); return true; }
/** * Привязываем счёт к счёту в банке * * @return void */ function binding() { if ($this->_user->getId() == 0) { $errorMessage = 'Необходимо авторизироваться'; } if (isset($_POST['account_id'])) { $account_id = (int) $_POST['account_id']; if ($account_id <= 0) { $errorMessage = 'Неверный идентификатор счёта'; } } else { $errorMessage = 'Необходимо указать счёт'; } if (!isset($errorMessage)) { $debetCard = new Account_DebetCard(); if (!$debetCard->binding($account_id)) { $errorMessage = 'Ошибка при привязывании счёта'; } } if (isset($errorMessage)) { $this->renderJsonError($errorMessage); } else { $this->renderJsonSuccess('Счёт успешно привязан'); } }
/** * add identifier * * @author Matthias Pfefferle * @param User $pUser * @param AuthToken $pAuthToken * @return OnlineIdentity */ public function addIdentifier($pUser, $pOAuthToken) { $lAccessToken = $this->getAccessToken($pOAuthToken); // get api informations $lJson = OAuthClient::get($this->getConsumer(), $lParamsArray['oauth_token'], $lParamsArray['oauth_token_secret'], "http://api.yigg.local/profiles/me"); $lJsonObject = json_decode($lJson); // ask for online identity $lOnlineIdentity = OnlineIdentityTable::retrieveByOriginalId($lJsonObject->id, $this->aCommunityId); // check if user already exists if ($lOnlineIdentity) { if ($lOnlineIdentity->getUserId() && $pUser->getId() == $lOnlineIdentity->getUserId()) { if (!$lOnlineIdentity->getActive()) { $lOnlineIdentity->setActive(true); } else { throw new sfException("online identity already added", 1); } } elseif ($lOnlineIdentity->getUserId() && $pUser->getId() != $lOnlineIdentity->getUserId()) { throw new sfException("online identity already added by someone else", 2); } } else { // get auth identifier foreach ($lJsonObject->urls as $url) { if ($url['type'] == "profile") { $lIdentifier = $url['value']; } } // check online identity $lOnlineIdentity = OnlineIdentityTable::addOnlineIdentity($lIdentifier, $lJsonObject->id, $this->aCommunityId); } $this->completeOnlineIdentity($lOnlineIdentity, $lJsonObject, $pUser, $lIdentifier); AuthTokenTable::saveToken($pUser->getId(), $lOnlineIdentity->getId(), $lParamsArray['oauth_token'], $lParamsArray['oauth_token_secret'], true); return $lOnlineIdentity; }
/** * Авторизовать пользователя * * @param User $user * @param bool $remember * @return void */ public function signIn(User $user, $remember = false) { $this->user = $user; $this->setAttribute('id', $user->getId(), 'user'); $this->setAuthenticated(true); $this->clearCredentials(); if ($remember) { $now = new DateTime(); $expired = clone $now; $expired->modify("-" . $this->getExpiration() . " sec"); // убить все старые кючи Doctrine::getTable('myAuthRememberKey')->removeOldKeys($expired)->execute(); // убить все ключи этого пользователя Doctrine::getTable('myAuthRememberKey')->removeKeysByUserId($user->getId())->execute(); // создать новый ключ $key = $this->generateRandomKey(); // сохранить ключ $rk = new myAuthRememberKey(); $rk->setRememberKey($key); $rk->setUser($user); $rk->setIpAddress($_SERVER['REMOTE_ADDR']); $rk->save(); // отдать ключ в виде печенья sfContext::getInstance()->getResponse()->setCookie($this->getCookieName(), $key, time() + $this->getExpiration()); } }
/** * Adds this new notification object to the backend storage. */ protected function insert() { global $wgEchoBackend, $wgEchoNotifications; $row = array('notification_event' => $this->event->getId(), 'notification_user' => $this->user->getId(), 'notification_anon_ip' => $this->user->isAnon() ? $this->user->getName() : $this->user->getId(), 'notification_timestamp' => $this->timestamp, 'notification_read_timestamp' => $this->readTimestamp, 'notification_bundle_hash' => '', 'notification_bundle_display_hash' => ''); // Get the bundle key for this event if web bundling is enabled $bundleKey = ''; if (!empty($wgEchoNotifications[$this->event->getType()]['bundle']['web'])) { wfRunHooks('EchoGetBundleRules', array($this->event, &$bundleKey)); } if ($bundleKey) { $hash = md5($bundleKey); $row['notification_bundle_hash'] = $hash; $lastStat = $wgEchoBackend->getLastBundleStat($this->user, $hash); // Use a new display hash if: // 1. there was no last bundle notification // 2. last bundle notification with the same hash was read if ($lastStat && !$lastStat->notification_read_timestamp) { $row['notification_bundle_display_hash'] = $lastStat->notification_bundle_display_hash; } else { $row['notification_bundle_display_hash'] = md5($bundleKey . '-display-hash-' . wfTimestampNow()); } } $wgEchoBackend->createNotification($row); wfRunHooks('EchoCreateNotificationComplete', array($this)); }
public function hasPersonalAnnotations() { if (!isset($this->hasPersonalAnnotations)) { $this->hasPersonalAnnotations = !$this->viewerUser->isAnon() && $this->viewerUser->getId() == $this->ownerUser->getId() && AchAwardingService::canEarnBadges($this->viewerUser) && !$this->viewerUser->getGlobalPreference('hidepersonalachievements'); } return $this->hasPersonalAnnotations; }
/** * @return bool|int|null */ protected function saveContent() { global $wgLogRestrictions; $dbw = wfGetDB(DB_MASTER); $log_id = $dbw->nextSequenceValue('logging_log_id_seq'); $this->timestamp = $now = wfTimestampNow(); $data = array('log_id' => $log_id, 'log_type' => $this->type, 'log_action' => $this->action, 'log_timestamp' => $dbw->timestamp($now), 'log_user' => $this->doer->getId(), 'log_user_text' => $this->doer->getName(), 'log_namespace' => $this->target->getNamespace(), 'log_title' => $this->target->getDBkey(), 'log_page' => $this->target->getArticleId(), 'log_comment' => $this->comment, 'log_params' => $this->params); $dbw->insert('logging', $data, __METHOD__); $newId = !is_null($log_id) ? $log_id : $dbw->insertId(); # And update recentchanges if ($this->updateRecentChanges) { $titleObj = SpecialPage::getTitleFor('Log', $this->type); RecentChange::notifyLog($now, $titleObj, $this->doer, $this->getRcComment(), '', $this->type, $this->action, $this->target, $this->comment, $this->params, $newId); } elseif ($this->sendToUDP) { # Don't send private logs to UDP if (isset($wgLogRestrictions[$this->type]) && $wgLogRestrictions[$this->type] != '*') { return true; } # Notify external application via UDP. # We send this to IRC but do not want to add it the RC table. $titleObj = SpecialPage::getTitleFor('Log', $this->type); $rc = RecentChange::newLogEntry($now, $titleObj, $this->doer, $this->getRcComment(), '', $this->type, $this->action, $this->target, $this->comment, $this->params, $newId); $rc->notifyRC2UDP(); } return $newId; }
/** * add identifier * * @author Matthias Pfefferle * @param User $pUser * @param AuthToken $pAuthToken * @return OnlineIdentity */ public function addIdentifier($pUser, $pCode) { $lAccessToken = $this->getAccessToken($pCode); // get params $lParamsArray = array(); // extract params $lAccessToken = json_decode($lAccessToken, true); $lJsonObject = json_decode(UrlUtils::sendGetRequest("https://api.flattr.com/rest/v2/user", array("Authorization: Bearer " . $lAccessToken["access_token"]))); // facebook identifier $lIdentifier = $lJsonObject->link; // ask for online identity $lOnlineIdentity = OnlineIdentityTable::retrieveByAuthIdentifier($lIdentifier); // check if user already exists if ($lOnlineIdentity) { if ($lOnlineIdentity->getUserId() && $pUser->getId() == $lOnlineIdentity->getUserId()) { if (!$lOnlineIdentity->getActive()) { $lOnlineIdentity->setActive(true); } else { throw new sfException("online identity already added", 1); } } elseif ($lOnlineIdentity->getUserId() && $pUser->getId() != $lOnlineIdentity->getUserId()) { throw new sfException("online identity already added by someone else", 2); } } else { // check online identity $lOnlineIdentity = OnlineIdentityTable::addOnlineIdentity($lJsonObject->link, $lJsonObject->username, $this->aCommunityId, $lIdentifier); } // use api complete informations $this->completeOnlineIdentity($lOnlineIdentity, $lJsonObject, $pUser, $lIdentifier); // signup,add new AuthTokenTable::saveToken($pUser->getId(), $lOnlineIdentity->getId(), $lAccessToken["access_token"], null, true); // signup,add new return $lOnlineIdentity; }
/** * Updates the aa_lastlogin value for the specified user * * @param User $user the user that just logged in * * @return bool return True to continue processing hooks */ static function updateLastLogin(User $user) { if (wfReadOnly()) { return true; } $now = time(); $db = wfGetDB(DB_MASTER); $method = __METHOD__; $requestMethod = self::ACCESS_METHOD_DEFAULT; if (class_exists("MobileContext") && MobileContext::singleton()->shouldDisplayMobileView()) { $requestMethod = self::ACCESS_METHOD_MOBILE; } $db->onTransactionIdle(function () use($user, $requestMethod, $now, $db, $method) { if ($db->getType() === 'mysql') { // MySQL-specific implementation $db->query("INSERT INTO " . $db->tableName('accountaudit_login') . "( aa_user, aa_method, aa_lastlogin ) VALUES (" . $db->addQuotes($user->getId()) . ", " . $db->addQuotes($requestMethod) . ", " . $db->addQuotes($db->timestamp($now)) . ") ON DUPLICATE KEY UPDATE aa_lastlogin = " . $db->addQuotes($db->timestamp($now)), $method); } else { $db->update('accountaudit_login', array('aa_lastlogin' => $db->timestamp($now)), array('aa_user' => $user->getId(), 'aa_method' => $requestMethod), $method); if ($db->affectedRows() == 0) { // no row existed for that user, method $db->insert('accountaudit_login', array('aa_user' => $user->getId(), 'aa_method' => $requestMethod, 'aa_lastlogin' => $db->timestamp($now)), $method, array('IGNORE')); } } }); // always return true, this should be a non-blocking hook on failure return true; }
public function addUserToHistory(User $user) { $ids = $this->getAttribute('user_history', array()); if (!in_array($user->getId(), $ids)) { array_unshift($ids, $user->getId()); $this->setAttribute('user_history', array_slice($ids, 0, 5)); } }
/** * Добавочное условие объединения: по ID пользователя * * @param User $user * @param string $joinAlias * @return myOperationQuery */ protected function addJoinAccountByUser(User $user, $joinAlias) { $rootAlias = $this->getRootAlias(); $this->modifyJoinAccountCondition("{$joinAlias}.user_id = ?", $joinAlias); $this->_params['join'][] = $user->getId(); $this->andWhere("{$rootAlias}.user_id = ?", $user->getId()); return $this; }
/** * Запрос для выборки зарезервированных средств * * @param array $accountIds массив ID счетов * @param User $user * @param string $alias * @return Doctrine_Query */ public function queryCountReserves(array $accountIds, User $user = null, $alias = 't') { $q = $this->createQuery($alias)->select("{$alias}.account_id, SUM({$alias}.amount) reserve")->innerJoin("{$alias}.Target tg")->andWhere("tg.done = 0")->andWhereIn("{$alias}.account_id", $accountIds)->groupBy("{$alias}.account_id"); if ($user) { $q->andWhere("{$alias}.user_id = ? AND tg.user_id = ?", array((int) $user->getId(), (int) $user->getId())); } return $q; }
public function testSetId() { $oldid = $this->User->getId(); $this->User->setId(666); if ($this->User->getId() != 666) { $this->fail(); } $this->User->setId($oldid); }
/** * @covers User::setId * @covers User::getId */ public function testSetId() { $id = 3; $actual = $this->user->getId(); $this->assertNotEquals($id, $actual); $this->user->setId($id); $actual = $this->user->getId(); $this->assertEquals($id, $actual); }
/** * Deletes all permissions for a user * @param User $user */ public function deleteForUser($user) { try { $this->db->delete("users_permissions", $this->db->quoteInto("userId = ?", $user->getId())); Logger::info("dropped all permissions for user " . $user->getId()); } catch (Exception $e) { throw $e; } }
/** * @param $user * @return Category или NULL */ public static function getDebtCategoryInstance(User $user) { static $debtCategoryByUserId = array(); if (!array_key_exists($user->getId(), $debtCategoryByUserId)) { $category = Doctrine::getTable('Category')->findOneBySystemIdAndUserId(Category::DEBT_SYSTEM_CATEGORY_ID, $user->getId()); $debtCategoryByUserId[$user->getId()] = $category !== false ? $category : null; } return $debtCategoryByUserId[$user->getId()]; }
/** * Speichert den aktuellen Tipp in der Datenbank * @return bool true, wenn das Speichern erfolgreich war, false sonst */ public function save() { $db = Database::getDbObject(); $stmt = $db->prepare("INSERT INTO `tipps`(`uid`, `spiel_id`, `heim`, `auswaerts`)\n VALUES(?, ?, ?, ?);"); $stmt->bind_param('iiii', $this->user->getId(), $this->spiel->getId(), $this->heim, $this->auswaerts); if (!$stmt->execute()) { return false; } return true; }
/** * Проверяем что из csv получился yaml */ public function testExecuteProducesYaml() { $csvImport = new myImportCsvVkoshelke($this->_csvData); $success = $csvImport->execute($this->_user); $this->assertTrue($success, 'Импорт должен завершиться успешно'); $yaml = $csvImport->getYmlData(); $yamlParser = new sfYamlParser(); $data = $yamlParser->parse($yaml); $this->assertEquals(array('user_id' => $this->_user->getId(), 'date' => '2010-06-08', 'amount' => '20000.00', 'comment' => 'Тане', 'type' => 0, 'Account' => 'Account_1', 'Category' => 'Category_1'), $data['Operation']['Operation_1']); $this->assertEquals(array('user_id' => $this->_user->getId(), 'date' => '2010-06-06', 'amount' => '100.00', 'comment' => '', 'type' => 2, 'Account' => 'Account_2', 'transfer_amount' => '300000.00', 'TransferAccount' => 'Account_1'), $data['Operation']['Operation_4']); }
public function validate($value) { $records = DB::getDataList(get_class($this->changedRecord), array('Email' => $value)); foreach ($records as $record) { if ($record->getId() == $this->changedRecord->getId()) { continue; } return false; } return true; }
public static function onDeleteAccount(User &$oldUser) { $dbw = wfGetDB(DB_MASTER); // Use master to be up to date $row = $dbw->selectRow('accountaudit_login', array('aa_user'), array('aa_user' => $oldUser->getId())); if ($row !== false) { $dbw->onTransactionIdle(function () use($dbw, $oldUser) { $dbw->delete('accountaudit_login', array('aa_user' => $oldUser->getId()), 'AccountAuditHooks::onDeleteAccount'); }); } }
/** * Get params for a user * @param User $user * @return array|null */ public static function getParams(User $user) { if ($user->getId()) { if (!isset($user->fr_user_params)) { // process cache... $user->fr_user_params = self::getUserParams($user->getId()); } return $user->fr_user_params; } return null; }
private function getUsers() { $users = User::select("1"); foreach ($users as $u) { $user = new User($u); $this->users .= <<<FFF <tr id="{$user->getId()}user"> <td class="name">{$user->getUsername()}</td> <td><span class="delUser" userid="{$user->getId()}">Trinti</span></td> </tr> FFF; } }
public function __construct() { $this->view = ViewManager::getInstance(); // get the current user and put it to the view if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_SESSION["currentuser"])) { $this->currentUser = new User($_SESSION["currentuser"]); //add current user to the view, since some views require it $this->view->setVariable("currentusername", $this->currentUser->getId()); } }
/** * Return recent activities for selected user of all active projects * * @param User $user * @param integer $count * @return array */ function paginateActivitiesByUser($user, $page = 1, $per_page = 30) { $objects_table = TABLE_PREFIX . 'project_objects'; $logs_table = TABLE_PREFIX . 'activity_logs'; $total_activities = array_var(db_execute_one("SELECT COUNT({$logs_table}.id) AS 'row_count' FROM {$logs_table}, {$objects_table} WHERE {$logs_table}.object_id = {$objects_table}.id AND {$logs_table}.created_by_id = ?", $user->getId()), 'row_count'); if ($total_activities) { $offset = ($page - 1) * $per_page; $activities = ActivityLogs::findBySQL("SELECT {$logs_table}.* FROM {$logs_table}, {$objects_table} WHERE {$logs_table}.object_id = {$objects_table}.id AND {$logs_table}.created_by_id = ? ORDER BY {$logs_table}.created_on DESC LIMIT {$offset}, {$per_page}", array($user->getId())); } else { $activities = null; } // if return array($activities, new Pager($page, $total_activities, $per_page)); }
public function executeRegister() { //If the user is logged in, don't let them register if ($this->getUser()->isAuthenticated()) { $this->error = 'You are already logged in. You can not register again.'; return sfView::ERROR; } if (!$this->hasRequestParameter('name') || !$this->hasRequestParameter('email') || !$this->hasRequestParameter('password')) { $this->error = 'Invalid Request.'; return sfView::ERROR; } $this->requestedUserType = '1'; //Create and populate the User object $user = new User(); $userName = str_replace(' ', '', strtolower($this->getRequestParameter('name'))); $user->setName($this->getRequestParameter('name')); $user->setEmail($this->getRequestParameter('email')); $user->setPassword($this->getRequestParameter('password')); $_SESSION['question'] = $this->getRequestParameter('question'); //$user->setPoints('10.11'); $user->setTypeUnconfirmed($this->requestedUserType); /* Username Duplication Check */ $unamequery = mysql_query("select * from user where username='******'"); $unamecount = mysql_num_rows($unamequery); $dupval = 2; duplicationCheck: if ($unamecount >= 1) { $newUsername = $userName . $dupval; $unamequery = mysql_query("select * from user where username='******'"); $unamecount = mysql_num_rows($unamequery); if ($unamecount >= 1) { $dupval++; goto duplicationCheck; } else { $userName = $newUsername; } } $user->setUsername($userName); //Try to save the User... throw an exception if something messes up if (!$user->save()) { throw new PropelException('User creation failed'); } mysql_query("insert into expert_category(user_id,category_id) values('" . $user->getId() . "','1')") or die(mysql_error()); mysql_query("insert into user_score(user_id,score) values('" . $user->getId() . "','1')") or die(mysql_error()); $this->sendConfirmationEmail($user, $_SESSION['question']); $this->user = $user; $this->forward('quickreg', 'confirmationcode'); //$this->redirect(sfConfig::get('app_rayku_url')."/quickreg/confirmationcodesent"); }
/** * Наполняет список операций из БД за период * @param DateTime $startDate * @param DateTime $endDate * @return void */ public function fill() { $alias = 'op'; $query = Doctrine::getTable('Operation')->createQuery($alias)->innerJoin("{$alias}.Account")->leftJoin("{$alias}.TransferAccount")->leftJoin("{$alias}.Category")->andWhere("{$alias}.user_id = ? ", $this->_user->getId()); if ($this->_periodStartDate) { $query = $query->andWhere("{$alias}.date >= ? ", $this->_periodStartDate->format('Y-m-d')); } if ($this->_periodEndDate) { $query = $query->andWhere("{$alias}.date <= ? ", $this->_periodEndDate->format('Y-m-d')); } if ($this->_acceptedOnly) { $query = $query->andWhere("{$alias}.accepted = 1"); } $this->_operations = $query->execute(array())->getData(); }