Example #1
1
 function insert()
 {
     $dbc = new DB();
     $dbc->connect();
     $sql = "insert into registered_users(FullName,Username,Password,Email,Mobile,RegNo) values('{$this->name}','{$this->username}','{$this->password}','{$this->email}','{$this->mobile}','{$this->regNo}')";
     $dbc->query($sql);
 }
Example #2
0
function makeDB()
{
    /* Connects to the database.
     * Configuration is taken from the config.php file.
     * Returns a database object uppon success,
     * die()'s on any kind of error.
     */
    // We need the DSN from the config file.
    global $DSN;
    // Create the database object.
    $database = DB::connect("{$DSN}");
    // Did we encounter an error?
    if (DB::isError($database)) {
        $dberror = $database->getMessage();
        // Print out the basic idea of an error, along with the raw PEAR::DB Error.
        print "There is a problem communicating with your database server: {$dberror}<br>";
        // Catch the most common mistake: Invalid credentials.
        if ($dberror == "DB Error: connect failed") {
            print "It seems you did not supply the correct mysql access information in the config.php.";
        }
        // Fall over, dead.
        die;
    }
    // Set database to associative fetching mode.
    $database->setFetchMode(DB_FETCHMODE_ASSOC);
    // and return the database object.
    return $database;
}
Example #3
0
 function run()
 {
     DB::connect();
     //determin controller
     switch ($_GET['ctrl']) {
         case 'page':
             $ctrl = new PageController();
             break;
         case 'wine':
             $ctrl = new WineController();
             break;
         case 'response':
             $ctrl = new ResponseController();
             break;
         case 'report':
             $ctrl = new ReportController();
             break;
         case 'dp':
             $ctrl = new DianPingController();
             break;
         default:
             $ctrl = new PageController();
     }
     return $ctrl->dispatch($_GET['action'] . "Action");
     DB::close();
 }
function log_err($file, $line, $message)
{
    global $error_level;
    // debug
    //print "<p>Error in: $file At line: $line</p>";
    //print "<p>Message: $message</p>";
    if ($error_level == 1) {
        $category = 0;
        $message = "{$message} ({$file}, {$line})";
        $dsn = array('phptype' => 'mysql', 'username' => 'cityg_8', 'password' => 'gBhpj4Xj', 'hostspec' => 'db72c.pair.com', 'database' => 'cityg_dev');
        $db =& DB::connect($dsn, $options);
        //$this->db = DB::connect($dsn);
        if (DB::isError($db)) {
            die($db->getMessage());
        }
        /**
         * /remark
         * Unix time has greater resolution than MySQL
         * datetime as far as I can tell.
         */
        $sql = "INSERT INTO event_log SET";
        $sql .= " timetamp=" . time();
        $sql .= " category=" . $db->quote($category);
        $sql .= ", message=" . $db->quote($message);
        $db->query($sql);
        if (DB::isError($db)) {
            die($db->getMessage());
        }
        //	print "<p>Error in: $file At line: $line</p>";
        //	print "<p>Message: $message</p>";
    }
}
 public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
 {
     if (!$this->testSessionEnvironment->isRunningTests()) {
         return;
     }
     $testState = $this->testSessionEnvironment->getState();
     // Date and time
     if (isset($testState->datetime)) {
         SS_Datetime::set_mock_now($testState->datetime);
     }
     // Register mailer
     if (isset($testState->mailer)) {
         $mailer = $testState->mailer;
         Email::set_mailer(new $mailer());
         Config::inst()->update("Email", "send_all_emails_to", null);
     }
     // Allows inclusion of a PHP file, usually with procedural commands
     // to set up required test state. The file can be generated
     // through {@link TestSessionStubCodeWriter}, and the session state
     // set through {@link TestSessionController->set()} and the
     // 'testsession.stubfile' state parameter.
     if (isset($testState->stubfile)) {
         $file = $testState->stubfile;
         if (!Director::isLive() && $file && file_exists($file)) {
             // Connect to the database so the included code can interact with it
             global $databaseConfig;
             if ($databaseConfig) {
                 DB::connect($databaseConfig);
             }
             include_once $file;
         }
     }
 }
 /**
  * Stuff we want to fire when we start.
  *
  */
 public static function init()
 {
     global $argv;
     DB::connect();
     self::mapinfo();
     self::parseArguments($argv);
 }
Example #7
0
 /**
  * Return the DB instance.
  *
  * @param string $type  Either 'read' or 'rw'.
  * @param string $app   The application.
  * @param mixed $dtype  The type. If this is an array, this is used as
  *                      the configuration array.
  *
  * @return DB  The singleton DB instance.
  * @throws Horde_Exception
  */
 public function create($type = 'rw', $app = 'horde', $dtype = null)
 {
     global $registry;
     $sig = hash('sha1', serialize($type . '|' . $app . '|' . $dtype));
     if (isset($this->_instances[$sig])) {
         return $this->_instances[$sig];
     }
     $pushed = $app == 'horde' ? false : $registry->pushApp($app);
     $config = is_array($dtype) ? $dtype : $this->getConfig($dtype);
     if ($type == 'read' && !empty($config['splitread'])) {
         $config = array_merge($config, $config['read']);
     }
     Horde::assertDriverConfig($config, 'sql', array('charset', 'phptype'));
     /* Connect to the SQL server using the supplied parameters. */
     $db = DB::connect($config, array('persistent' => !empty($config['persistent']), 'ssl' => !empty($config['ssl'])));
     if ($db instanceof PEAR_Error) {
         if ($pushed) {
             $registry->popApp();
         }
         throw new Horde_Exception($db);
     }
     // Set DB portability options.
     $db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS);
     if ($pushed) {
         $registry->popApp();
     }
     $this->_instances[$sig] = $db;
     return $db;
 }
function bayesspam_init()
{
    if (isset($_SESSION['username'])) {
        if ($GLOBALS['bayes_granularity'] == 'user') {
            $GLOBALS['bayes_username'] = addslashes(preg_replace('/' . $GLOBALS['bayes_domain_seperator'] . '/', '!', $_SESSION['username']));
        } elseif ($GLOBALS['bayes_granularity'] == 'domain') {
            $GLOBALS['bayes_username'] = addslashes(preg_replace('/^.+' . $GLOBALS['bayes_domain_seperator'] . '/', '', $_SESSION['username']));
        } else {
            $GLOBALS['bayes_username'] = '******';
        }
    }
    $GLOBALS['bayesdbhandle'] = DB::connect($GLOBALS['bayesdbtype'] . '://' . $GLOBALS['bayesdbuser'] . ':' . $GLOBALS['bayesdbpass'] . '@' . $GLOBALS['bayesdbhost'] . ':' . $GLOBALS['bayesdbport'] . '/' . $GLOBALS['bayesdbname'], 1);
    if (DB::isError($GLOBALS['bayesdbhandle'])) {
        if ($GLOBALS['bayes_show_db_error']) {
            bindtextdomain('bayesspam', SM_PATH . 'plugins/bayesspam/locale');
            textdomain('bayesspam');
            echo $GLOBALS['bayesdbhandle']->getDebugInfo() . "<BR>";
            echo _("BayesSpam improperly configured. Check DB Information.");
            bindtextdomain('squirrelmail', SM_PATH . 'locale');
            textdomain('squirrelmail');
        }
        $GLOBALS['bayesdbhandle'] = null;
    } else {
        $GLOBALS['bayesdbhandle']->setFetchMode(DB_FETCHMODE_ASSOC);
    }
    if ($GLOBALS['bayesdbhandle'] == null) {
        return;
    }
    if (!isset($_SESSION['bayesspam_corpus'])) {
        session_register('bayesspam_corpus');
    }
}
 public function setUp()
 {
     global $databaseConfig;
     if (!DB::isActive()) {
         DB::connect($databaseConfig);
     }
 }
Example #10
0
 public function user()
 {
     $db =& DB::connect('mysql://*****:*****@219.83.123.212/em');
     if (PEAR::isError($db)) {
         die($db->getDebugInfo());
     }
     $db->setFetchMode(DB_FETCHMODE_ASSOC);
     $res = $db->query('SELECT id, name, joint, level, pwd, clear_pwd, last FROM user LEFT JOIN user_pwd ON id=user_id WHERE id!="admin" ORDER BY id');
     if (PEAR::isError($res)) {
         die($res->getDebugInfo());
     }
     while ($row = $res->fetchRow()) {
         $row['id'] = trim($row['id']);
         if (!$row['id'] || preg_match('/[^0-9a-zA-Z-_@.]/', $row['id'])) {
             echo "<p>Exclude '{$row['id']}'</p>";
             continue;
         }
         $res2 = self::$dbh->query('INSERT INTO user (uid, name, mail, level, since) VALUES (?, ?, ?, ?, ?)', array($row['id'], $row['name'], $row['mail'], $row['level'], $row['joint']));
         if (PEAR::isError($res2)) {
             printf('%s<br/>', $res2->getDebugInfo());
         }
         $user_id = self::$dbh->getOne('SELECT id FROM user WHERE uid=?', array($row['id']));
         $res3 = self::$dbh->query('INSERT INTO user_pwd (user_id, pwd, clear) VALUES (?, ?, ?)', array($user_id, $row['pwd'], str_rot13($row['clear_pwd'])));
         if (PEAR::isError($res3)) {
             printf('%s<br/>', $res3->getDebugInfo());
         }
         ++$count;
     }
     printf("<p>{$count} Processed</p>");
 }
Example #11
0
 public static function init()
 {
     if (!self::$config) {
         self::$config = (include BASE_PATH . 'config.php');
     }
     // Incluir la base de datos
     include BASE_PATH . 'app/DB.php';
     include BASE_PATH . 'app/DBObject.php';
     include BASE_PATH . 'app/Query.php';
     // Conectamos con la base de datos
     DB::config(self::get('database'));
     DB::connect();
     // Definimos algunas constantes importantes
     foreach (array('cache', 'includes', 'models', 'controllers', 'views', 'assets') as $path) {
         self::$config['path'][$path . '_orig'] = self::$config['path'][$path];
         self::$config['path'][$path] = BASE_PATH . self::get('path.' . $path) . '/';
     }
     // Cargar los modelos automáticamente
     foreach (glob(self::get('path.models') . '*.php', GLOB_NOSORT) as $file) {
         include $file;
     }
     // Configurar el cargado automático de clases
     spl_autoload_register(function ($name) {
         require Config::get('path.includes') . $name . '.php';
     });
     Cache::configure(array('cache_path' => self::get('path.cache'), 'expires' => self::get('cache.expires')));
 }
Example #12
0
function getAllSQL($querytxt, $database)
{
    $db = DB::connect('mysql://*****:*****@localhost/' . $database);
    $db->setFetchMode(DB_FETCHMODE_ASSOC);
    $query = $db->getAll($querytxt);
    return $query;
}
Example #13
0
 public static function get_stats()
 {
     //this should really be properly cached at some point.
     $return = false;
     //is the data already in the session?
     if (isset($_SESSION['stats'])) {
         $return = $_SESSION['stats'];
     } else {
         $db = DB::connect(DB_CONNECTION_STRING);
         $alert_count = 0;
         $authority_count = 0;
         //Count of applications
         $alert_sql = "select value from stats where `key` = 'applications_sent'";
         $results = $db->getAll($alert_sql);
         if (sizeof($results) > 0) {
             $alert_count = $results[0][0];
         }
         //Count of authorities
         $authority_sql = "select count(authority_id) from authority where disabled = 0 or disabled is null";
         $results = $db->getAll($authority_sql);
         if (sizeof($results) > 0) {
             $authority_count = $results[0][0];
         }
         //save to session
         $return = array('alert_count' => $alert_count, 'authority_count' => $authority_count);
         $_SESSION['stats'] = $return;
     }
     return $return;
 }
 function TranslationEngine($lang = "english")
 {
     global $GlobalDatabase;
     _filter_var($lang);
     if (is_language_supported($lang)) {
         $this->Language = $lang;
         $this->LanguageTable = "lang_{$this->Language}";
     } else {
         $this->Language = "english";
         $this->LanguageTable = "";
     }
     /**
      * no need to create database connection for English
      * because it won't be used...
      */
     if ($this->Language != 'english') {
         if (!isset($GlobalDatabase)) {
             include 'configs/globals.php';
             $dsn = array('phptype' => $db_type, 'username' => $db_username, 'password' => $db_password, 'hostspec' => $db_host, 'database' => $db_name);
             $options = array('debug' => 2, 'portability' => DB_PORTABILITY_ALL);
             $this->Database =& DB::connect($dsn, $options);
             if (PEAR::isError($this->Database)) {
                 die($this->Database->getMessage());
             }
             $q =& $this->Database->query("SET NAMES utf8;");
             if (PEAR::isError($q)) {
                 die($q->getMessage());
             }
         } else {
             $this->Database = $GlobalDatabase;
         }
     }
 }
 function checkConnection()
 {
     if (!isset($this->db)) {
         $this->db =& DB::connect(PROXY_SERV_CONN_DSN);
         return $this->db;
     }
 }
    public static function get_connection()
    {
        if (!Dal::$_connection) {
            global $peepagg_dsn;
            Dal::$_connection = DB::connect($peepagg_dsn, array("autofree" => true));
            if (Dal::$_connection instanceof PEAR_Error) {
                $msg = Dal::$_connection->getMessage();
                if (strpos($msg, "no such database") != -1) {
                    ?>

<h1>Database not found</h1>

<p>Please check your <code>AppConfig.xml</code> file and ensure that the <code>$peepagg_dsn</code> variable is set and points to a valid database.</p>

<p>Currently, either the database doesn't exist, the user doesn't exist, or the password in <code>$peepagg_dsn</code> is incorrect.</p>

   <?php 
                    exit;
                }
                // otherwise we throw an exception
                throw new PAException(DB_CONNECTION_FAILED, "Database connection failed");
            }
            // connection succeeded - turn off automatic committing
            Dal::$_connection->autoCommit(FALSE);
        }
        return Dal::$_connection;
    }
Example #17
0
 public function getFieldSQL($tabla, $campo, $sql)
 {
     $query_user = DB::connect()->prepare("SELECT " . $campo . " FROM " . $tabla . " " . $sql . " ");
     $query_user->execute();
     $result_row = $query_user->fetchAll();
     return $result_row;
 }
 function PageTable($dsn = "", $class = "")
 {
     $this->PEAR();
     $this->url = $_SERVER['PHP_SELF'];
     $this->db = DB::connect($dsn);
     $this->table = new HTML_Table($class ? "class=" . $class : "");
 }
Example #19
0
	function log($priority, $message, $file = null, $line = null, $e = null) {
		$schema = "DEFAULT";
		$table = "logs";
		$trace = "";
		if (!empty($e)) {
			$trace = $e->getTraceAsString();
		}
		if (is_object($message)) {
			$message = JSON::encode($message);
		}
		$now = new Date();
		$log = array();
		$log["priority"] = $priority;
		$log["message"] = $message;
		$log["trace"] = $trace;
		$log["file"] = $file;
		$log["line"] = $line;
		$log["createdBy"] = "SYS";
		$log["createdTime"] = $now;
		$log["updatedBy"] = "SYS";
		$log["updatedTime"] = $now;

		$driver = $GLOBALS["CFG_DB"]->CON[$schema]->DRIVER;
		$insert = new Insert($table, $log, $schema);
		$link = DB::connect();
		$success = mysql_query($insert->sql(), $link);
		if (!$success) {
			$result = Bean::invoke(String::camelize('_'.$driver.'_driver'), "error", array($schema));
			throw new Exception("Cannot persist object. ".$result);
		}
	}
Example #20
0
 public function __construct(array $config)
 {
     $dsn = array('phptype' => $config['driver'], 'hostspec' => $config['hostname'], 'database' => $config['database'], 'username' => $config['username'], 'password' => $config['password']);
     // DBTYPE specific dsn settings
     switch ($dsn['phptype']) {
         case 'mysql':
         case 'mysqli':
             // if we are using some non-standard mysql port, pass that value in the dsn
             if ($config['port'] != 3306) {
                 $dsn['port'] = $config['port'];
             }
             break;
         default:
             if ($config['port']) {
                 $dsn['port'] = $config['port'];
             }
             break;
     }
     $db = DB::connect($dsn);
     $this->assertError($db, 1);
     // DBTYPE specific session setup commands
     switch ($dsn['phptype']) {
         case 'mysql':
         case 'mysqli':
             $db->query("SET SQL_MODE = ''");
             if (Language::isUTF8()) {
                 $db->query('SET NAMES utf8');
             }
             break;
         default:
             break;
     }
     $this->db = $db;
     $this->tablePrefix = $config['table_prefix'];
 }
Example #21
0
 /**
  * The constructor of the generic module
  * class, ModulePage (Page.Module.class.php)
  * <br>
  * Takes global variables like TrEng and GlobalDatabase
  * and sets the variables that will be used throughout
  * the class
  * @access public
  * @param string $group
  * @param string $modulecode
  * @return ModulePage
  */
 function ModulePage($modulecode)
 {
     global $GlobalDatabase;
     global $treng;
     _filter_var($group);
     if (isset($GlobalDatabase)) {
         $this->Database = $GlobalDatabase;
     } else {
         include 'configs/globals.php';
         $dsn = array('phptype' => $db_type, 'username' => $db_username, 'password' => $db_password, 'hostspec' => $db_host, 'database' => $db_name);
         $options = array('debug' => 2, 'portability' => DB_PORTABILITY_ALL);
         $this->Database =& DB::connect($dsn, $options);
         if (PEAR::isError($this->Database)) {
             die($this->Database->getMessage());
         }
         $q =& $this->Database->query("SET NAMES utf8;");
         if (PEAR::isError($q)) {
             die($q->getMessage());
         }
     }
     if (isset($treng)) {
         $this->TrEng = $treng;
     } else {
         $this->TrEng = new TranslationEngine();
     }
     $this->ModuleCode = $modulecode;
 }
Example #22
0
function dba_connect($username, $password, $dbname, $hostname, $port = "", $persistant = "true")
{
    global $core_config;
    $access = $username;
    if ($password) {
        $access = "{$username}:{$password}";
    }
    $host = $hostname;
    if ($port) {
        $host = "{$hostname}:{$port}";
    }
    if (_DB_DSN_) {
        $dsn = _DB_DSN_;
    } else {
        $dsn = _DB_TYPE_ . "://{$access}@{$host}/{$dbname}";
    }
    if (_DB_OPT_) {
        $options = _DB_OPT_;
    } else {
        $options = $persistant;
    }
    $dba_object = DB::connect($dsn, $options);
    if (DB::isError($dba_object)) {
        // $error_msg = "DB Name: $dbname<br>DB Host: $host";
        ob_end_clean();
        die("<p align=left>" . $dba_object->getMessage() . "<br>" . $error_msg . "<br>");
        return false;
    }
    return $dba_object;
}
Example #23
0
 /**
  * Constructor
  *
  * @access protected
  * @param  array  full liveuser configuration array
  * @return void
  * @see    LiveUser::factory()
  */
 function LiveUser_Admin_Perm_Container_DB_Simple(&$connectOptions)
 {
     if (is_array($connectOptions)) {
         foreach ($connectOptions as $key => $value) {
             if (isset($this->{$key})) {
                 $this->{$key} = $value;
             }
         }
         if (isset($connectOptions['connection']) && DB::isConnection($connectOptions['connection'])) {
             $this->dbc =& $connectOptions['connection'];
             $this->init_ok = true;
         } elseif (isset($connectOptions['dsn'])) {
             $this->dsn = $connectOptions['dsn'];
             $options = null;
             if (isset($connectOptions['options'])) {
                 $options = $connectOptions['options'];
             }
             $options['portability'] = DB_PORTABILITY_ALL;
             $this->dbc =& DB::connect($connectOptions['dsn'], $options);
             if (!DB::isError($this->dbc)) {
                 $this->init_ok = true;
             }
         }
     }
 }
Example #24
0
 function SC_DbConn($dsn = "", $err_disp = true, $new = false)
 {
     global $objDbConn;
     // Debugモード指定
     $options['debug'] = PEAR_DB_DEBUG;
     // 持続的接続オプション
     $options['persistent'] = PEAR_DB_PERSISTENT;
     // 既に接続されていないか、新規接続要望の場合は接続する。
     if (!isset($objDbConn->connection) || $new) {
         if ($dsn != "") {
             $objDbConn = DB::connect($dsn, $options);
             $this->dsn = $dsn;
         } else {
             if (defined('DEFAULT_DSN')) {
                 $objDbConn = DB::connect(DEFAULT_DSN, $options);
                 $this->dsn = DEFAULT_DSN;
             } else {
                 return;
             }
         }
     }
     $this->conn = $objDbConn;
     $this->error_mail_to = DB_ERROR_MAIL_TO;
     $this->error_mail_title = DB_ERROR_MAIL_SUBJECT;
     $this->err_disp = $err_disp;
     $this->dbFactory = SC_DB_DBFactory_Ex::getInstance();
 }
Example #25
0
function login()
{
    $controller = new UserTools();
    $db = new DB();
    $db->connect();
    if (!isset($_POST['apikey'])) {
        echo "bad api key";
        return NULL;
    }
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $user = $_POST['username'];
        $pass = $_POST['password'];
        $result = $controller->login($user, $pass);
        echo $result;
        /*
        $query = $db->select('users', 'username=$user,pass_hash=$pass');
        if(mysql_num_rows($query) == 1){
        	//success
        	$_SESSION['logged_in'] = $query['id'];
        } else {
        	//fail
        	echo "invalid username or password";
        }
        */
    }
}
 private function checkAndConnectDB()
 {
     global $databaseConfig;
     if (!DB::getConn() && $databaseConfig) {
         DB::connect($databaseConfig);
     }
 }
Example #27
0
 /**
  * Executes the CronJob.
  *
  * @return null
  */
 public function execute()
 {
     $callback = unserialize($this->callback);
     $result = call_user_func($callback);
     $q = "UPDATE crontab SET" . " result = {$result}," . " last_run = NOW()," . " next_run = ADDTIME(FROM_UNIXTIME({$this->now}), FROM_UNIXTIME(increment))" . " WHERE id = {$this->id}";
     DB::connect()->exec($q);
 }
Example #28
0
 function insert()
 {
     $db = new DB();
     $db->connect();
     $sql = "insert into contact(Username,Comments) values('{$this->username}','{$this->comments}')";
     $db->query($sql);
 }
/**
 * Execute a MySQL query
 *
 * @param	array		$dsn
 * @param	string	$query
 * @return	void	FALSE / array
 */
function myQuery($dsn, $query)
{
    require_once 'DB.php';
    $db =& DB::connect($dsn['DB_dsn'], $dsn['DB_options']);
    //	if (PEAR::isError($db)) {
    if (DB::isError($db)) {
        myLog($db->getMessage() . $db->getUserInfo());
        return false;
    }
    $db->setFetchMode(DB_FETCHMODE_ASSOC);
    // always set utf8
    $result = $db->query('SET NAMES utf8;');
    if (DB::isError($result)) {
        myLog('Query error:' . $result->getMessage());
        return false;
    }
    //	$result = $db->query($query);
    $result = $db->getAll($query);
    if (DB::isError($result)) {
        myLog('Query error: "' . $query . '" -> ' . $result->getMessage());
        return false;
    }
    $db->disconnect();
    return $result;
}
Example #30
0
 /**
  * Make a sql query to the database.
  *
  * @param string $sql
  * @return integer
  */
 public static function query($sql)
 {
     DB::connect();
     $res = mysqli_query(DB::$connection, $sql);
     DB::close();
     return $res;
 }