static function getTranslation($key, $defaultContent = '') { /* are we in language debug mode */ if (SITE_CONFIG_LANGUAGE_SHOW_KEY == "key") { return strlen($defaultContent) ? $defaultContent : $key; } /* return the language translation if we can find it */ $constantName = "LANGUAGE_" . strtoupper($key); if (!defined($constantName)) { if (strlen($defaultContent)) { $db = Database::getDatabase(); $languageId = $db->getValue("SELECT id FROM language WHERE languageName = " . $db->quote(SITE_CONFIG_SITE_LANGUAGE)); if (!(int) $languageId) { return false; } // insert default key value $dbInsert = new DBObject("language_key", array("languageKey", "defaultContent", "isAdminArea")); $dbInsert->languageKey = $key; $dbInsert->defaultContent = $defaultContent; $dbInsert->isAdminArea = 0; $dbInsert->insert(); // set constant define("LANGUAGE_" . strtoupper($key), $defaultContent); return $defaultContent; } return "<font style='color:red;'>SITE ERROR: MISSING TRANSLATION *** <strong>" . $key . "</strong> ***</font>"; } return constant($constantName); }
public function __construct() { $this->connection = Database::getDatabase(); $this->userController = new UsersController(); $this->categoryController = new CategoryController(); $this->parentCategoryController = new ParentCategoryController(); }
public function POST() { // throw new RESTMethodNotImplementedException ('Pesquisa', 'POST'); $sk = new SecureKeyAuth(); $sk->checkAuth(); $params = $this->getPostParams(); $fields = implode(',', array_keys($params)); $keyparams = implode(',', array_map(function ($value) { return ':' . $value; }, array_keys($params))); $db = Database::getDatabase(); try { $st = $db->prepare("INSERT INTO pesquisa ({$fields}) VALUES ({$keyparams})"); foreach ($params as $field => $value) { $tipo = is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR; $st->bindValue(':' . $field, $value, $tipo); } if ($st->execute()) { $this->setResult(array('status' => 'OK')); } else { //$this->setResult($db->errorInfo()); $this->setResult(array('status' => 'ERROR', 'fields' => $fields, 'keyparams' => $keyparams, 'sqlerrorcode' => $db->errorCode())); } } catch (PDOException $ex) { throw new RESTObjectException('Database insert fail'); } }
public static function track($file, $rs = '') { $db = Database::getDatabase(); if (SITE_CONFIG_STATS_ONLY_COUNT_UNIQUE == 'yes') { // check whether the user has already visited today $sql = "SELECT * FROM stats WHERE ip = " . $db->quote(self::getIP()) . " AND page_title = " . $file->id . " AND DATE(dt) = " . $db->quote(date('Y-m-d')); $row = $db->getRows($sql); if (COUNT($row)) { return false; } } $file->updateVisitors(); $dt = date("Y-m-d H:i:s"); $referer = getenv('HTTP_REFERER'); $referer_is_local = self::refererIsLocal($referer); $url = full_url(); $img_search = ''; $ip = self::getIP(); $info = self::browserInfo(); $browser_family = $info['browser']; $browser_version = $info['version']; $os = $info['platform']; $os_version = ''; $user_agent = $info['useragent']; $country = self::getCountry($ip); $base_url = self::getBaseUrl($referer); $sql = "INSERT INTO stats (dt, referer, referer_is_local, url, page_title, country, img_search, browser_family, browser_version, os, os_version, ip, user_agent, base_url)\n VALUES (:dt, :referer, :referer_is_local, :url, :page_title, :country, :img_search, :browser_family, :browser_version, :os, :os_version, :ip, :user_agent, :base_url)"; $vals = array('dt' => $dt, 'referer_is_local' => $referer_is_local, 'referer' => $referer, 'url' => $url, 'page_title' => $file->id, 'country' => $country, 'img_search' => $img_search, 'ip' => $ip, 'browser_family' => $browser_family, 'browser_version' => $browser_version, 'os_version' => $os_version, 'os' => $os, 'user_agent' => $user_agent, 'base_url' => $base_url); $db->query($sql, $vals); return true; }
function __construct($id) { $db = Database::getDatabase(); $this->data = $db->querySingle(sprintf("select * from exception_logging where id = %d", $id)); if (!$this->data) { throw new NotFound(); } $this->data['error_info'] = unserialize(base64_decode($this->data['error_info'])); $pr = preg_quote(c()->getValue('report_format', 'app_root'), '#'); if (!$this->data['error_info']['callstack']) { $this->data['error_info']['callstack'] = array(); } $this->data['error_info']['callstack'] = array_merge(array(array('line' => $this->data['error_info']['line'], 'file' => $this->data['error_info']['file'], 'function' => 'throw', 'args' => array())), $this->data['error_info']['callstack']); foreach ($this->data['error_info']['callstack'] as &$csi) { if ($pr) { $csi['base_file'] = preg_replace("#^{$pr}/?#", '', $csi['file']); $csi['file'] = preg_replace("#^{$pr}/?#", '<R>/', $csi['file']); $csi['scm_link'] = $this->getWebSCMLink($csi['base_file'], $csi['line']); } if ($csi['class']) { $csi['call'] = sprintf('%s%s%s(%s)', $csi['class'], $csi['type'], $csi['function'], implode(', ', array_map(array($this, 'formatArgument'), $csi['args']))); } else { $csi['call'] = sprintf('%s(%s)', $csi['function'], implode(', ', array_map(array($this, 'formatArgument'), $csi['args']))); } } if ($fs = c()->getValue('report_format', 'interesting_custom_fields')) { $fs = explode(',', $fs); foreach ($fs as $f) { $this->data[$f] = $this->data['error_info'][$f]; } } }
/** * Constructor * Use $db->createResult( $parent, $name ) instead * * @param Database|Result|Row $parent * @param string $name */ function __construct($parent, $name) { if ($parent instanceof Database) { // basic result $this->db = $parent; $this->table = $this->db->getAlias($name); } else { // Row or Result // result referenced to parent $this->parent_ = $parent; $this->db = $parent->getDatabase(); // determine type of reference based on conventions and user hints $fullName = $name; $name = preg_replace('/List$/', '', $fullName); $this->table = $this->db->getAlias($name); $this->single = $name === $fullName; if ($this->single) { $this->key = $this->db->getPrimary($this->getTable()); $this->parentKey = $this->db->getReference($parent->getTable(), $name); } else { $this->key = $this->db->getBackReference($parent->getTable(), $name); $this->parentKey = $this->db->getPrimary($parent->getTable()); } } }
public function __construct($itemClass, $countSql, $pageSql, $page, $per_page) { $this->itemClass = $itemClass; $this->countSql = $countSql; $this->pageSql = $pageSql; $db = Database::getDatabase(); $num_records = intval($db->getValue($countSql)); parent::__construct($page, $per_page, $num_records); }
public function GET() { $st = Database::getDatabase()->select('total_de_votos'); $result = array(); while ($row = $st->fetch(PDO::FETCH_ASSOC)) { $result[] = (object) $row; } $this->setResult(array('status' => 'OK', 'content' => (object) $result)); }
static function loadAllByAccount($accountId) { $db = Database::getDatabase(true); $rs = $db->getRows('SELECT * FROM file_folder WHERE userId = ' . $db->quote($accountId) . ' ORDER BY folderName'); if (!is_array($rs)) { return false; } return $rs; }
static function getBannedType() { $userIP = getUsersIPAddress(); $db = Database::getDatabase(true); $row = $db->getRow('SELECT banType FROM banned_ips WHERE ipAddress = ' . $db->quote($userIP)); if (!is_array($row)) { return false; } return $row['banType']; }
public function checkAuth() { $params = $this->getPostParams(); $db = Database::getDatabase(); if ($db->select('device', "iddevice = {$params['iddevice']} and hash_key = '{$params['hash_key']}'")->fetch()) { return TRUE; } else { throw new RESTObjectException('This device has not permission'); } }
public function run() { $db = Database::getDatabase(); $rows = $db->getRows($this->query); $this->data = array(); foreach ($rows as $row) { $x = $row[$this->xColumnName]; $y = $row[$this->yColumnName]; $this->data[$x] = $y; } }
public static function refreshContent($url, $expires_in = 300) { $str = self::getURL($url); $data = self::decodeStrData($str); if ($data === false) { return false; } $db = Database::getDatabase(); $db->query("REPLACE INTO url_cache (url, dt_refreshed, dt_expires, data) VALUES (:url, :dt_refreshed, :dt_expires, :data)", array('url' => $url, 'dt_refreshed' => dater(), 'dt_expires' => dater(time() + $expires_in), 'data' => $str)); return $str; }
public function install() { // Create tables $sql = file_get_contents(DOC_ROOT . '/apps/' . $this->data['app']['name'] . '/db.sql'); // Do this to split up creations to one per query. $queries = explode('#', $sql); $db = Database::getDatabase(); foreach ($queries as $query) { $db->query($query); } redirect(WEB_ROOT . $this->app_name . '/'); }
public static function types() { $db = Database::getDatabase(); $db->query("SHOW COLUMNS FROM users LIKE 'level'"); $row = $db->getRow(); $type = $row['Type']; preg_match('/enum\\((.*)\\)$/', $type, $matches); $vals = explode(',', $matches[1]); if (is_array($vals)) { return str_replace("'", '', $vals); } else { return false; } }
function __construct() { $this->connection = Database::getDatabase(); /* Check if the table is created and if not create the table */ $query = "CREATE TABLE IF NOT EXISTS " . $this->TABLE_NAME . "(id INTEGER AUTO_INCREMENT,PRIMARY KEY(id),\n page varchar(200),\n ip VARCHAR(100),\n agent VARCHAR(50),\n city VARCHAR(200),\n region VARCHAR(200),\n country VARCHAR(200),\n description TEXT,\n extra TEXT,\n hit_date VARCHAR(25) )"; if ($result = mysql_query($query, $this->connection)) { } else { echo mysql_error($this->connection); $this->tableInit = false; } if ($this->tableInit) { $this->alterTable(); } }
public function POST() { (new SecureKeyAuth())->checkAuth(); $params = $this->getPOSTParams(); $db = Database::getDatabase(); $st = $db->prepare('UPDATE promocao SET escolhido = :escolhido WHERE sequencia = :sequencia'); $st->bindValue(':escolhido', $params['escolhido'], PDO::PARAM_BOOL); $st->bindValue(':sequencia', $params['sequencia'], PDO::PARAM_INT); if ($st->execute()) { $this->setResult(array('status' => 'OK', 'message' => 'Mensagem cadastrada com sucesso.')); } else { $this->setResult($db->errorInfo()); } }
static function createPasswordResetHash($userId) { $user = true; // make sure it doesn't already exist on an account while ($user != false) { // create hash $hash = MD5(microtime() . $userId); // lookup by hash $user = self::loadUserByPasswordResetHash($hash); } // update user with hash $db = Database::getDatabase(true); $db->query('UPDATE users SET passwordResetHash = :passwordResetHash WHERE id = :id', array('passwordResetHash' => $hash, 'id' => $userId)); return $hash; }
public function POST() { $sk = new SecureKeyAuth(); $sk->checkAuth(); $params = $this->getPostParams(); $db = Database::getDatabase(); $st = $db->prepare('INSERT INTO ' . 'promocao (idartista, nome, celular, texto)' . 'VALUES (:idartista, :nome, :celular, :texto)'); $st->bindValue(':idartista', $params['idartista'], PDO::PARAM_INT); $st->bindValue(':nome', $params['nome'], PDO::PARAM_STR); $st->bindValue(':celular', $params['celular'], PDO::PARAM_STR); $st->bindValue(':texto', $params['texto'], PDO::PARAM_STR); if ($st->execute()) { $this->setResult(array('status' => 'OK', 'message' => 'Mensagem cadastrada com sucesso.')); } else { $this->setResult($db->errorInfo()); } }
public function __construct($class_name, $sql = null, $extra_columns = array()) { $this->position = 0; $this->className = $class_name; $this->extraColumns = $extra_columns; // Make sure the class exists before we instantiate it... if (!class_exists($class_name)) { return; } $tmp_obj = new $class_name(); // Also, it needs to be a subclass of DBObject... if (!is_subclass_of($tmp_obj, 'DBObject')) { return; } if (is_null($sql)) { $sql = "SELECT * FROM `{$tmp_obj->tableName}`"; } $db = Database::getDatabase(); $this->result = $db->query($sql); }
public static function status($userId) { $db = Database::getDatabase(); $query = ' SELECT user, code, active FROM activation WHERE user='******'active'] == 1) { return true; } else { return false; } } }
public static function track($page_title = '') { $db = Database::getDatabase(); $dt = dater(); $referer = getenv('HTTP_REFERER'); $referer_is_local = self::refererIsLocal($referer); $url = full_url(); $search_terms = self::searchTerms(); $img_search = ''; $ip = self::getIP(); $info = self::browserInfo(); $browser_family = $info['browser']; $browser_version = $info['version']; $os = $info['platform']; $os_version = ''; $user_agent = $info['useragent']; $exec_time = defined('START_TIME') ? microtime(true) - START_TIME : 0; $num_queries = $db->numQueries(); $sql = "INSERT INTO stats (dt, referer, referer_is_local, url, page_title, search_terms, img_search, browser_family, browser_version, os, os_version, ip, user_agent, exec_time, num_queries)\n VALUES (:dt, :referer, :referer_is_local, :url, :page_title, :search_terms, :img_search, :browser_family, :browser_version, :os, :os_version, :ip, :user_agent, :exec_time, :num_queries)"; $vals = array('dt' => $dt, 'referer_is_local' => $referer_is_local, 'referer' => $referer, 'url' => $url, 'page_title' => $page_title, 'search_terms' => $search_terms, 'img_search' => $img_search, 'ip' => $ip, 'browser_family' => $browser_family, 'browser_version' => $browser_version, 'os_version' => $os_version, 'os' => $os, 'user_agent' => $user_agent, 'exec_time' => $exec_time, 'num_queries' => $num_queries); $db->query($sql, $vals); }
public function GET() { $flag_pode_votar = FALSE; $d1start = getConf()['dia1_inicio']; $d1end = getConf()['dia1_fim']; $d2start = getConf()['dia2_inicio']; $d2end = getConf()['dia2_fim']; $datetime = new DateTime(); $ctime = $datetime->getTimestamp(); $day = $d1start < $ctime and $ctime < $d1end ? 1 : $d2start < $ctime and $ctime < $d2end ? 2 : FALSE; if (isset($_GET['uuid'])) { $uuid = $_GET['uuid']; $resultSet = Database::getDatabase()->select('dispositivos', "uuid = '{$uuid}'")->fetch(PDO::FETCH_ASSOC); if ($resultSet) { $v1 = (bool) $resultSet['dia1']; $v2 = (bool) $resultSet['dia2']; $votou = $day == 1 ? $v1 : $day == 2 ? $v2 : FALSE; $podeVotar = $day != FALSE and $votou == FALSE; $result['cadastrado'] = TRUE; } elseif (isset($_GET['plataforma']) and isset($_GET['modelo'])) { if (Database::getDatabase()->insert('dispositivos', array('uuid', 'plataforma', 'modelo'), array($_GET['uuid'], $_GET['plataforma'], $_GET['modelo']), array(PDO::PARAM_STR, PDO::PARAM_STR, PDO::PARAM_STR))) { $result['cadastrado'] = TRUE; } else { $result['cadastrado'] = FALSE; } } } $result['status'] = 'OK'; $result['date_time'] = $datetime; $result['time'] = $ctime; if ($day) { $result['votacao'] = 'aberta'; $result['dia'] = $day; $result['pode_votar'] = $podeVotar; } else { $result['votacao'] = $d2end < $ctime ? 'encerrada' : 'fechada'; } $this->setResult($result); }
public function POST() { throw new RESTMethodNotImplementedException('Device', 'POST'); $fim = Application::getConf('votacao')->fim; $agora = time; if ($agora > $fim) { throw new RESTObjectException('Votações encerradas', $agora); } $sk = new SecureKeyAuth(); $sd = new SecureDeviceHash(); $sk->checkAuth(); $sd->checkAuth(); $params = $this->getPostParams(); $db = Database::getDatabase(); if ($db->select('device_votou_momo', "iddevice = {$params['iddevice']}")->fetch()) { throw new RESTObjectException('Você já votou para momo'); } try { $db->beginTransaction(); $flag = false; //inserir registro votado $flag = $db->exec("INSERT INTO device_votou_momo (iddevice) VALUES ({$params['iddevice']})") ? TRUE : FALSE; //inserir registro if ($flag) { $flag = $db->exec("INSERT INTO votos_momo (idmomo) VALUES ({$params['idmomo']})") ? TRUE : FALSE; } if ($flag) { $db->commit(); } else { $db->rollBack(); throw new RESTObjectException('Database insert fail'); } $this->GET(); } catch (PDOException $ex) { $db->rollBack(); throw new RESTObjectException('Database insert fail'); } }
/** * Constructor * Use $db->createResult( $parent, $name ) instead * * @param Database|DatabaseTable $parent * @param string $name * * @since 1.0.0 */ public function __construct($parent, $name) { if ($parent instanceof Database) { // basic result $this->db = $parent; $this->table = $this->db->schema()->getAlias($name); $this->query = DatabaseQuery::getInstance()->from($this->table); } else { // result referenced to parent $this->parent = $parent; $this->db = $parent->getDatabase(); $this->query = $parent->getDatabaseQuery(); // determine type of reference based on conventions and user hints $this->table = $this->db->schema()->isAlias($name) ? $this->db->schema()->getTable($name) : $name; if ($parent->getTable() == $this->table) { $this->key = $this->db->schema()->getPrimary($this->getTable()); $this->parentKey = $this->db->schema()->getReference($parent->getTable(), $name); } else { $this->key = $this->db->schema()->getBackReference($parent->getTable(), $name); $this->parentKey = $this->db->schema()->getPrimary($parent->getTable()); } } }
public function POST() { throw new RESTMethodNotImplementedException('Device', 'POST'); $sk = new SecureKeyAuth(); $sk->checkAuth(); //Verificando secure key $result = array(); $params = $this->getPostParams(); if ($params === FALSE) { throw new RESTMethodNotImplementedException('Device', 'POST'); } $flag_exists = false; $db = Database::getDatabase(); if (trim(strtolower($params['platform'])) == 'android') { //Verificando serial $st_result = $db->query("SELECT * FROM device WHERE serial = '{$params['serial']}'")->fetch(); $flag_exists = $st_result !== false; } else { $this->setResult(array('status' => 'ERROR', 'message' => 'Only Android devices are permited')); return; } if ($flag_exists) { $this->setResult(array('status' => 'ERROR', 'message' => 'Device is registered on database')); return; } $st = $db->prepare('INSERT INTO ' . 'device (uuid, serial, version, platform, model, hash_key)' . 'VALUES (:uuid, :serial, :version, :platform, :model, :hash_key)'); $params['hash_key'] = md5($params['uuid'] . $params['model'] . $params['serial']); foreach ($params as $field => $value) { $result[$field] = $value; $st->bindValue(':' . $field, $value); } if ($st->execute()) { $this->setResult(array('status' => 'OK', 'iddevice' => $db->lastInsertId(), 'hash_key' => $params['hash_key'])); } else { $this->setResult($db->errorInfo()); } }
function get_options($table, $val, $text, $default = null, $sql = '') { $db = Database::getDatabase(true); $out = ''; $table = $db->escape($table); $rows = $db->getRows("SELECT * FROM `{$table}` {$sql}"); foreach ($rows as $row) { $the_text = ''; if (!is_array($text)) { $text = array($text); } // Allows you to concat multiple fields for display foreach ($text as $t) { $the_text .= $row[$t] . ' '; } $the_text = htmlspecialchars(trim($the_text)); if (!is_null($default) && $row[$val] == $default) { $out .= '<option value="' . htmlspecialchars($row[$val], ENT_QUOTES) . '" selected="selected">' . $the_text . '</option>' . nl(); } elseif (is_array($default) && in_array($row[$val], $default)) { $out .= '<option value="' . htmlspecialchars($row[$val], ENT_QUOTES) . '" selected="selected">' . $the_text . '</option>' . nl(); } else { $out .= '<option value="' . htmlspecialchars($row[$val], ENT_QUOTES) . '">' . $the_text . '</option>' . nl(); } } return $out; }
<?php include "dbQueries.php"; //error_reporting(E_ALL); //ini_set('display_errors', 'On'); include_once 'classes/Authentication.php'; include_once 'classes/Database.php'; include_once 'includes/TestingCenter.php'; $db = Database::getDatabase(); Authentication::sec_session_start(); try { $dbh = new PDO("mysql:host=mysql2.cs.stonybrook.edu;dbname=sachin", "sachin", "108610059"); } catch (PDOException $e) { $message = "Couldnt connect to db."; echo "<script type='text/javascript'>alert('{$message}');</script>"; } $dbh->beginTransaction(); $todaysDate = date("Y-m-d"); $sql = "SELECT * FROM appointment WHERE netID='{$_POST['apptNetID']}' AND dateOfExam = '{$todaysDate}' AND checkedIn=0; "; $result = $dbh->prepare($sql); if (!$result) { $prepareFail = "Information NOT updated."; echo "<script type='text/javascript'>alert('{$prepareFail}');</script>"; $dbh->rollback(); $dbh = null; return; } //$conn->query($sql); $result->execute(); $var = $result->fetchAll(); ?>
private function attemptLogin($un, $pw) { $db = Database::getDatabase(); $Config = Config::getConfig(); // We SELECT * so we can load the full user record into the user DBObject later $row = $db->getRow('SELECT * FROM shine_users WHERE username = '******'password'] = $this->createHashedPassword($row['password']); } if ($pw != $row['password']) { return false; } $this->id = $row['id']; $this->username = $row['username']; $this->level = $row['level']; // Load any additional user info if DBObject and User are available if (class_exists('User') && is_subclass_of('User', 'DBObject')) { $this->user = new User(); $this->user->id = $row['id']; $this->user->load($row); } $this->storeSessionData($un, $pw); $this->loggedIn = true; return true; }
private function getOpenUntil($date) { $db = Database::getDatabase(); $handle = $db->getHandle(); $q_getopenuntil = "SELECT hours_openuntil from freyhalltestingcenterroom where daysFrom=?"; $handle->beginTransaction(); $result_openuntil = $handle->prepare($q_getopenuntil); if (!$result_openuntil) { echo "<script type='text/javascript'>alert('errUpdate');</script>"; } $center_openuntil = $result_openuntil->execute(array($date)); return $center_openuntil; }