/** * Returns id by name($value) from table * * @param string $value * @return string */ public function filter($value) { if ($value === null) { return null; } $select = $this->_table->select()->where($this->_field . ' = ?', $value); $row = $this->_table->fetchRow($select); if ($row !== null) { return $row[reset($this->_table->info(Zend_Db_Table::PRIMARY))]; } else { return null; } }
/** * get thread of specific id * * @param id */ public function getThreadFromId($id) { if (!$id) { return null; } $threads_table = new Zend_Db_Table('threads'); $select = $threads_table->select()->where('id = ?', $id); return $threads_table->fetchRow($select); }
/** * (non-PHPdoc) * @see models/Sahara/Auth/Sahara_Auth_Session::setup() */ public function setup() { $table = new Zend_Db_Table('users'); $record = $table->fetchRow($table->select()->where('name = ?', $this->_authType->getUsername())->where('namespace = ?', $this->_config->institution)); /* User name exists, so no need to create account. */ if ($record) { return; } $table->insert(array('name' => $this->_authType->getUsername(), 'namespace' => $this->_config->institution, 'persona' => 'USER')); }
public static function getLastAccess($classroomId, $data) { $access = new Zend_Db_Table('content_access'); $select = $access->select()->where('classroom_id = ?', $classroomId)->order('content_access.id DESC'); $row = $access->fetchRow($select); if ($row) { return self::getPositionById($row->content_id, $data); } return 0; }
/** * Retorna el Rol del usuario actual * * @return string */ private function getRol() { $rolStr = 'guest'; if ($this->_auth->hasIdentity()) { $numRol = $this->_auth->getIdentity()->rol; $tablaRol = new Zend_Db_Table('roles'); $rol = $tablaRol->fetchRow($tablaRol->select()->from($tablaRol)->where('idRol = ?', $numRol)); $rolStr = $rol['rol']; } return $rolStr; }
public function indexAction() { $queries = (int) $this->getParam('queries', 1); $queries = max(1, $queries); $queries = min(500, $queries); $table = new Zend_Db_Table('World'); $worlds = array(); for ($i = 0; $i < $queries; $i += 1) { $worlds[] = $table->fetchRow(array('id = ?' => mt_rand(1, 10000)))->toArray(); } $this->_helper->json->sendJson($worlds); }
/** * Получаем информацию о разделе * * @param int $item_id * @param int $menu_id * * @return array */ public function getSection($item_id, $menu_id) { $menu = $this->getMenu($menu_id); if ($menu->type == 'router') { // получаем разделы меню привязонного к маршруту $item = $this->_modelItems->fetchRow($this->_modelItems->select()->where('route_id = ?', $item_id)->where('menu_id = ?', $menu->menu_id)); $itemRoute = Modules_Router_Model_Router::getInstance()->getItem($item_id); $return = $item ? $item->toArray() + $itemRoute : $itemRoute; $return['type'] = 'router'; $return['parent_id'] = $itemRoute['parent_route_id']; $return['name_route'] = $itemRoute['name']; $return['name'] = $item['name'] ? $item['name'] : $itemRoute['name']; unset($return['parent_route_id'], $return['childs']); } else { $return = $this->_modelItems->fetchRow($this->_modelItems->select()->where('item_id = ?', $item_id))->toArray(); } return $return; }
public function signAction() { $data = array(); if ($this->_hasParam('id')) { $id = Zend_filter::filterStatic($this->_getParam('id'), 'int'); if (Application_Model_Classroom::isAvailable($id)) { $session = new Zend_Session_Namespace('data'); $session->classroom_id = $id; $classroom = new Zend_Db_Table('classroom'); $row = $classroom->fetchRow(array('id = ?' => $id)); if (PAYMENT && $row->amount && $row->amount > 0) { $this->_redirect('/classroom/pay'); } else { $this->_redirect('/classroom/register'); } } } $this->view->messages = array('Unavailable'); }
/** * Checks if the user still has attempted and period * * @param integer $userId * @param integer $exerciseId */ public static function isDisabled($userId, $exerciseId) { $exercise = new Zend_Db_Table('exercise'); $db = Zend_Db_Table::getDefaultAdapter(); $select = $db->select()->from('exercise_note', 'COUNT(0) as total')->where('user_id = ?', $userId)->where('exercise_id = ?', $exerciseId); $result = $db->fetchRow($select); $where = array('id = ?' => $exerciseId, 'begin <= ?' => date('Y-m-d'), 'end >= ? OR end IS NULL' => date('Y-m-d')); $row = $exercise->fetchRow($where); if ($row) { if ($row->attempts === "0" || (int) $result['total'] < (int) $row->attempts) { return false; } else { return 'Number of attempts exec'; } } else { return 'Expired period'; } return false; }
/** * Returns true if the user can be authenticaed using the * supplied credential. The tests for success with this authentication * type are: * <ol> * <li>The user must exist.</li> * <li>The user must have database authorisation enabled * (auth_allowed = true).</li> * <li>The password must match the record password.</li> * </ol> * * @return boolean true if the user is authenticated * @see models/Sahara/Auth/Sahara_Auth_Type::authenticate() */ public function authenticate() { $table = new Zend_Db_Table('users'); $this->_record = $table->fetchRow($table->select()->where('name = ?', $this->_user)->where('namespace = ?', $this->_config->institution)); /* 1) User must exist. */ if ($this->_record == null) { return false; } $allowed = (int) $this->_record->auth_allowed; if (is_string($allowed)) { $allowed = (int) $allowed && true; } /* 2) Authorisation must be enabled. */ if (!$allowed) { return false; } /* 3) Passwords must match. */ return $this->_record->password == sha1($this->_pass); }
public function getAdforSearch($id, $ad_type, $woeid) { $id = (int) $id; $ad_type = (int) $ad_type; $woeid = (int) $woeid; $table = new Zend_Db_Table('ads'); $select = $table->select()->setIntegrityCheck(false); $select->from(array('a' => 'ads'), array('a.*')); $select->joinLeft(array('u' => 'users'), 'a.user_owner = u.id', array('u.username')); $select->joinLeft(array('c' => 'commentsAdCount'), 'a.id = c.id_comment', array('c.count as comments_count')); $select->joinLeft(array('r' => 'readedAdCount'), 'a.id = r.id_ad', array('r.counter as readings_count')); $select->where('a.id = ?', $id); $select->where('a.type = ?', $ad_type); $select->where('a.woeid_code = ?', $woeid); //show only if user is active and not locked //$select->where('u.active = ?', 1); //$select->where('u.locked = ?', 0); $result = $table->fetchRow($select); if (!is_null($result)) { $result = $result->toArray(); } return $result; }
/** * Verify if user with given $id exists and has specified $password * * @param string $id user identity URL * @param string $password user password * @return bool */ public function checkUser($id, $password) { $select = $this->_usersTable->select()->where('openid = ?', $id)->where('password = ?', $password); $row = $this->_usersTable->fetchRow($select); return $row == null; }
/** * @description inject factor fields into form * @param array $formConfig * @param object $table * @param string $action * @param object $config * @param array $params * @return * @author Se# * @version 0.0.1 */ protected function _getFormConfig() { $config = self::$_info['config']; $params = self::$_info['params']; $factors = $this->_getFactorsList($config); $formConfig = array('class' => 'factor_form', 'elements' => array('do' => array('type' => 'hidden', 'options' => array('value' => 'factor')))); $formConfig['elements']['factorobjectId'] = array('type' => 'hidden', 'options' => array('value' => $params['id'])); $formConfig['elements']['factorobjectTable'] = array('type' => 'hidden', 'options' => array('value' => Evil_DB::scope2table($params['controller']))); $formConfig['elements']['factortype'] = array('type' => 'select', 'options' => array('label' => 'Choose factor type', 'multiOptions' => $factors)); $formConfig['elements']['factorcontent'] = array('type' => 'textarea', 'options' => array('rows' => '5', 'cols' => 40)); $userTable = new Zend_Db_Table(Evil_DB::scope2table('user')); $user = $userTable->fetchRow('id="' . Zend_Registry::get('userid') . '"'); if (!$user) { $userName = '******'; } else { $user = $user->toArray(); $userName = isset($user['nickname']) ? $user['nickname'] : 'User'; } $formConfig['elements']['factorauthor'] = array('type' => 'text', 'options' => array('label' => 'Please, introduce yourself', 'value' => $userName, 'readOnly' => true)); $formConfig['elements']['submit'] = array('type' => 'submit', 'options' => array('label' => 'Add')); return $formConfig; }
if (!empty($methodName)) { $methodName = strtolower($methodName[0]) . substr($methodName, 1); } } if (empty($packageName) || empty($methodName)) { header('HTTP/1.1 400 Bad Request'); die("Invalid package or method"); } //initialize database adapter $dbAdapter = new Zend_Db_Adapter_Pdo_Mysql(array('host' => DB_HOST, 'dbname' => DB_NAME, 'username' => DB_USER, 'password' => DB_PASSWORD, 'charset' => 'utf8')); Zend_Db_Table::setDefaultAdapter($dbAdapter); session_start(); $userId = isset($_SESSION['userId']) ? $_SESSION['userId'] : null; if (!empty($userId)) { $userTable = new Zend_Db_Table('User'); $currentUser = $userTable->fetchRow($userTable->select()->from($userTable, array('id', 'email', 'fullname', 'isSupporter'))->where('id = ?', $userId)); if (!empty($currentUser)) { Zend_Registry::set('currentUser', $currentUser); } } include_once 'acl.php'; $code = isAllowed($packageName, $methodName); if ($code != 200) { header("HTTP/1.1 {$code} " . httpStatusCode($code)); die; } //init the handler instance from packageName $packagePath = implode(DIRECTORY_SEPARATOR, array(DIR_ROOT, 'handlers', $packageName)) . '.php'; if (!file_exists($packagePath)) { header('HTTP/1.1 404 Not Found'); die("{$pkgName} is not found!");
public function indexAction() { $table = new Zend_Db_Table('World'); $result = $table->fetchRow(array('id = ?' => mt_rand(1, 10000))); $this->_helper->json->sendJson($result->toArray()); }
public function fetchRowMaster($where = null, $order = null) { $this->_db = CrFramework_Db_Control::getMasterAdapter(); $this->setDefaultAdapter($this->_db); logStd(get_class($this) . '->fetchRow()', 'Read from MASTER'); $row = parent::fetchRow($where, $order); return $row; }
public function isMyFriend($id_user, $id_friend) { $table = new Zend_Db_Table('friends'); $select = $table->select()->where('id_user = ?', $id_user)->where('id_friend = ?', $id_friend); return $table->fetchRow($select); }
public function accountAction() { // Leave if not ready if (empty($this->_session->mysql)) { return $this->_helper->redirector->gotoRoute(array('action' => 'db-info')); } $this->view->form = $form = new Install_Form_Account(); if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($this->getRequest()->getPost())) { return; } // Check passwords match $values = $form->getValues(); if ($values['password'] != $values['password_conf']) { $form->addError('Passwords must match.'); return; } // Create account // Connect again try { $config = $this->dbFormToConfig($this->_session->mysql); // Connect! $adapter = Zend_Db::factory($config['adapter'], $config['params']); $adapter->getServerVersion(); } catch (Exception $e) { $form->addError('Adapter Error: ' . $e->getMessage()); //$this->view->code = 1; //$this->view->error = 'Adapter Error: ' . $e->getMessage(); return; } // attempt to disable strict mode try { $adapter->query("SET SQL_MODE = ''"); } catch (Exception $e) { } try { // Preprocess $settingsTable = new Zend_Db_Table(array('db' => $adapter, 'name' => 'engine4_core_settings')); $usersTable = new Zend_Db_Table(array('db' => $adapter, 'name' => 'engine4_users')); $levelTable = new Zend_Db_Table(array('db' => $adapter, 'name' => 'engine4_authorization_levels')); // Get static salt $staticSalt = $settingsTable->find('core.secret')->current(); if (is_object($staticSalt)) { $staticSalt = $staticSalt->value; } else { if (!is_string($staticSalt)) { $staticSalt = ''; } } // Get superadmin level $superAdminLevel = $levelTable->fetchRow($levelTable->select()->where('flag = ?', 'superadmin')); if (is_object($superAdminLevel)) { $superAdminLevel = $superAdminLevel->level_id; } else { $superAdminLevel = 1; } // Temporarily save pw $originalPassword = $values['password']; // Adjust values $values['salt'] = (string) rand(1000000, 9999999); $values['password'] = md5($staticSalt . $values['password'] . $values['salt']); $values['level_id'] = $superAdminLevel; $values['enabled'] = 1; $values['verified'] = 1; $values['creation_date'] = date('Y-m-d H:i:s'); $values['creation_ip'] = ip2long($_SERVER['REMOTE_ADDR']); $values['displayname'] = $values['username']; // Try to write info to config/auth.php if (!$this->_writeAuthToFile($values['email'], 'seiran', $originalPassword)) { throw new Exception('Unable to write Auth to File'); } // Insert $row = $usersTable->createRow(); $row->setFromArray($values); $row->save(); // First Signup Increment // Engine_Api::_()->getDbtable('statistics', 'core')->increment('user.creations'); // Validate password if ($row->password != md5($staticSalt . $originalPassword . $row->salt)) { throw new Engine_Exception('Error creating password'); } // Log the user into the intaller $auth = Zend_Registry::get('Zend_Auth'); $auth->getStorage()->write($row->user_id); // Try to log the user into socialengine // Note: nasty hack try { $mainSessionName = 'PHPSESSID'; if (empty($_COOKIE[$mainSessionName])) { $mainSessionId = md5(mt_rand(0, time()) . serialize($_SERVER)); setcookie($mainSessionName, $mainSessionId, null, dirname($this->view->baseUrl()), $_SERVER['HTTP_HOST'], false, false); } else { $mainSessionId = $_COOKIE[$mainSessionName]; } $adapter->insert('engine4_core_session', array('id' => $mainSessionId, 'modified' => time(), 'lifetime' => 86400, 'data' => 'Zend_Auth|' . serialize(array('storage' => $row->user_id)))); } catch (Exception $e) { // Silence if (APPLICATION_ENV == 'development') { echo $e->__toString(); } } // Update some other stuff $settingsTable = new Zend_Db_Table(array('db' => $adapter, 'name' => 'engine4_core_settings')); // Save site name $row = $settingsTable->find('core.general.site.title')->current(); if (null === $row) { $row = $settingsTable->createRow(); $row->name = 'core.general.site.title'; } $row->value = $values['site_title']; $row->save(); // Save email $row = $settingsTable->find('core.license.email')->current(); if (null === $row) { $row = $settingsTable->createRow(); $row->name = 'core.license.email'; } if ($row->value != '*****@*****.**') { $row->value = $values['email']; $row->save(); } // Update profile fields try { $fieldValuesTable = new Zend_Db_Table(array('db' => $adapter, 'name' => 'engine4_user_fields_values')); $fieldValuesTable->insert(array('item_id' => 1, 'field_id' => 1, 'index' => 0, 'value' => 1)); } catch (Exception $e) { } } catch (Exception $e) { $form->addError('Error: ' . $e->getMessage()); return; } // Redirect if successful return $this->_helper->redirector->gotoRoute(array('action' => 'complete')); }
public function setup() { /* Load the user's record. */ $table = new Zend_Db_Table('users'); $record = $table->fetchRow($table->select()->where('name = ?', $this->_authType->getUsername())->where('namespace = ?', $this->_config->institution)); if (!$record) { $this->_logger->warn('User ' . $this->_authType->getUsername() . ' does not exist so cannot update their ' . ' details.'); return; } /* Load the user details. */ $fn = $this->_getAuthProperty($this->_fnFields); $sn = $this->_getAuthProperty($this->_snFields); $email = $this->_getAuthProperty($this->_emailFields); /* Compare and store. */ $needsSave = false; if ($fn && $record->first_name != $fn) { $record->first_name = $fn; $needsSave = true; } if ($sn && $record->last_name != $sn) { $record->last_name = $sn; $needsSave = true; } if ($email && $record->email != $email) { $record->email = $email; $needsSave = true; } if ($needsSave) { $record->save(); } }
/** * @description save vote into a DB and forwards to the next action * @param array $forward where to go after action is over * @return void * @author Se# * @version 0.0.1 */ public function _actionDefault() { // define if there are required fields if (!isset(self::$_info['params']['objectId']) || !isset(self::$_info['params']['objectTable'])) { self::$_info['controller']->_redirect('/'); } $params = self::$_info['params']; // for the more comfort $session = new Zend_Session_Namespace('evil-votes'); // get session $voteTable = new Zend_Db_Table(Evil_DB::scope2table('vote')); // get table; TODO: get name from a config // If there are votes and count for the current object, than get last mark from it if (isset($session->votes) && isset($session->votes[$params['objectId'] . $params['objectTable']])) { $params['mark'] += $session->votes[$params['objectId'] . $params['objectTable']]; } else { // otherwise get last mark from a DB $vote = $voteTable->fetchRow($voteTable->select()->where('objectId=?', $params['objectId'])->where('objectTable=?', $params['objectTable'])->order('ctime DESC')); $params['mark'] += $vote ? is_object($vote) ? $vote->mark : $vote['mark'] : 0; } $params['ctime'] = time(); // set creation time // insert data, clean off system params such as controller, action, etc $voteTable->insert($this->_cleanParams($params)); if (isset($session->votes)) { // Save current mark into session $session->votes[$params['objectId'] . $params['objectTable']] = $params['mark']; } // define where should forward $forward = isset(self::$_info['controller']->selfConfig['vote']['forward']) ? self::$_info['controller']->selfConfig['vote']['forward'] : array('list', self::$_info['controllerName'], null, array()); // forward call_user_func_array(array(self::$_info['controller'], '_forward'), $forward); //self::$_info['controller']->_forward($forward[0], $forward[1], $forward[2], $forward[3]); }
/** * Registers plugin custom recipients * @param $pluginName * @return Application_Model_Mappers_EmailTriggersMapper */ public function registerRecipients($pluginName) { $recipients = $this->_getRecipients($pluginName); if (is_array($recipients) && !empty($recipients)) { $recipientsTable = new Zend_Db_Table('email_triggers_recipient'); foreach ($recipients as $recipient) { if (null === ($row = $recipientsTable->fetchRow(array('recipient = ?' => $recipient)))) { $row = $recipientsTable->insert(array('recipient' => $recipient)); } } } return $this; }
public static function getFieldById($tablename, $id, $getField = 'Code') { $db = new Zend_Db_Table($tablename); $rowSet = $db->select()->where("id =?", $id); $result = $db->fetchRow($rowSet); if ($result) { $result = $result->toArray(); } if ($getField) { return $result[$getField] ? $result[$getField] : $result['Code']; } else { return $result['Code']; } }
/** * Decrypt url for password recovery * * @param String $urlEncrypt * @return array **/ private function decryptUrl($urlEncrypt) { if (empty($urlEncrypt)) { return false; } $tableUser = new Zend_Db_Table('user'); $decrypt = new Zend_Filter_Decrypt(); $decrypt->setVector(MAIL_VECTOR); $decrypted = $decrypt->filter($urlEncrypt); $array = explode('/', $decrypted); $user = $tableUser->fetchRow(array('id =?' => $array[1])); $date = date("d/m/Y", strtotime($array[3])); $data['user'] = $user; $data['date'] = $date; return $data; }
public function keyAction() { // Check params $key = $this->_getParam('key'); $user_id = $this->_getParam('uid'); $return = $this->_getParam('return'); if (strlen((string) $key) != 40 || !is_numeric($user_id)) { $this->view->status = false; $this->view->error = 'Invalid key or user id provided'; return; } // Try to get db if (!Zend_Registry::isRegistered('Zend_Db') || !($db = Zend_Registry::get('Zend_Db')) instanceof Zend_Db_Adapter_Abstract) { $this->view->status = false; $this->view->error = 'Database connection not available, please login manually.'; return; } // Try to pull from auth table $table = new Zend_Db_Table(array('name' => 'engine4_core_auth')); $row = $table->fetchRow(array('id = ?' => $key, 'user_id = ?' => $user_id, 'type = ?' => 'package', '(expires = 0 || expires > ?)' => time())); if (null === $row) { $this->view->status = false; $this->view->error = 'Unable to authenticate. Key is invalid or has expired'; return; } // Everything checked out // Write auth (only if not already written) $auth = Zend_Registry::get('Zend_Auth'); if (!$auth->getStorage()->read()) { $auth->getStorage()->write($row->user_id); } // Delete row $row->delete(); // Redirect if (null === $return) { return $this->_helper->redirector->gotoRoute(array(), 'manage', true); } else { return $this->_helper->redirector->gotoUrl($return); } }