/**
  * Connect to database by using the given DSN string
  *
  * @author  copied from PEAR::Auth, Martin Jansen, slightly modified
  * @access private
  * @param  string DSN string
  * @return mixed  Object on error, otherwise bool
  */
 function _connectDB($dsn)
 {
     // only include the db if one really wants to connect
     require_once 'DB.php';
     if (is_string($dsn) || is_array($dsn)) {
         // put the dsn parameters in an array
         // DB would be confused with an additional URL-queries, like ?table=...
         // so we do it before connecting to the DB
         if (is_string($dsn)) {
             $dsn = DB::parseDSN($dsn);
         }
         $this->dbh = DB::Connect($dsn);
     } else {
         if (get_parent_class($dsn) == "db_common") {
             $this->dbh = $dsn;
         } else {
             if (is_object($dsn) && DB::isError($dsn)) {
                 return new DB_Error($dsn->code, PEAR_ERROR_DIE);
             } else {
                 return new PEAR_Error("The given dsn was not valid in file " . __FILE__ . " at line " . __LINE__, 41, PEAR_ERROR_RETURN, null, null);
             }
         }
     }
     if (DB::isError($this->dbh)) {
         return new DB_Error($this->dbh->code, PEAR_ERROR_DIE);
     }
     return true;
 }
Example #2
0
 public function getData($glob_user)
 {
     include_once "classes/db.class.php";
     $db = new DB();
     $db->Connect();
     include_once "./functions.php";
     $nav_links = '<a href="index.php" class="align_left"><h1>Awesome</h1></a>
                     <ul class="align_left">
                         <li><a href="index.php?web=home">Home</a></li>
                         <li><a href="index.php?web=profile&email=all">Profile</a></li>
                     </ul> 
                     
                     <form class="align_right" method="POST" id="log_out_form">
                         <input type="hidden" name="logging_out" value="bar" />
                         <a href="index.php?web=login" class="align_right logout_link"
                             onclick="document.getElementById(\'log_out_form\').submit(); return false;"
                         ><span class="glyphicon glyphicon-log-out"></span> Log out</a>
                     </form>
                     ';
     $new_post_form = '<form method="POST" class="new_post_form" enctype="multipart/form-data" name="new_post_form" onsubmit="return validate_textarea_newpost()">
                         <textarea rows="4" cols="90" maxlength="1000" name="post_textarea" class="form-control" placeholder="Share your story..."></textarea> 
                         </br>
                         <div style="float:left;">
                             <!--<span class="glyphicon glyphicon-camera" style="font-size:2.5em;"></span>-->
                             <input type="file" name="new_post_file">
                         </div>
                         <div style="float:right;">
                             <input type="submit" value="Send" class="btn btn-primary">
                         </div>
                     </form>';
     /***************************************************************/
     $table = "users";
     $selected_column = "id, name , email, sex, age, address, info, rights, phone";
     $where_arr = array("email" => $glob_user);
     $user_data = $db->DBSelectOne($table, $selected_column, $where_arr);
     $user_avatar = $user_data["id"];
     $user_avatar = file_exists("images/ava/" . $user_avatar . ".png") ? $user_avatar : "unknown";
     $user_infos = '<img class="img-circle with_shadow with_border" src="images/ava/' . $user_avatar . '.png" height="200px" width="200px">
                     <h1>' . $user_data["name"] . '</h1>
                         ' . $user_data["info"];
     $user_sex = $user_data["sex"] == 1 ? "Male" : "Female";
     $user_info_arr = array("sex" => "glyphicon-heart-empty", "age" => "glyphicon-calendar", "phone" => "glyphicon-earphone", "address" => "glyphicon-map-marker", "follow" => "glyphicon-eye-open");
     $user_info_arr_suffix = array("sex" => "", "age" => " years", "phone" => "", "address" => "", "follow" => "followers");
     $more_infos = get_more_info($user_data);
     /******************************* USERS POSTS ***************************************/
     $order_by = array();
     $order_by[] = array("column" => "time", "sort" => "DESC");
     $all_posts_arr = $db->DBSelectAll("posts", "id, users_id, text, time", array(), "", $order_by);
     $all_posts = get_all_posts($db, $all_posts_arr, $db, $user_data);
     $you_may_know = get_may_know($user_data["id"], $db);
     $activities = '<ul>
                         <li><span class="glyphicon glyphicon-heart"></span> <strong>Tony Tran</strong> likes your posts <span class="badge">5</span></li>
                         <li><span class="glyphicon glyphicon-eye-open"></span> <strong>Tony Tran</strong> and <strong>3 people</strong> started to follow you <span class="badge">4</span></li>
                         <li><span class="glyphicon glyphicon-heart"></span> <strong>Kin Le</strong> likes your posts <span class="badge">1</span></li>
                         <li></li>
                     </ul>';
     $copy_right = '<p>Copyright &copy; 2015 Vnkid</p>';
     return array("nav_links" => $nav_links, "user_infos" => $user_infos, "more_infos" => $more_infos, "you_may_know" => $you_may_know, "activities" => $activities, "all_posts" => $all_posts, "copy_right" => $copy_right, "new_post" => $new_post_form);
 }
Example #3
0
 public static function getAdminInfo($id)
 {
     $db = DB::Connect();
     $query = "SELECT nom_admin as nom, prenom_admin as prenom FROM ADMINISTRATEUR WHERE id_admin = " . $id;
     $result = $db->query($query);
     $result->setFetchMode(PDO::FETCH_OBJ);
     $info = $result->fetch();
     return $info;
 }
Example #4
0
 function __construct()
 {
     global $db_driver, $db_user, $db_pass, $db_host, $db_name;
     $dsn = $db_driver . '://' . $db_user . ':' . $db_pass . '@' . $db_host . '/' . $db_name;
     $this->db =& DB::Connect($dsn);
     if (PEAR::isError($this->db)) {
         die($this->db->getMessage());
     }
     $this->db->setFetchMode(DB_FETCHMODE_ASSOC);
 }
Example #5
0
 public static function findAll()
 {
     $db = DB::Connect();
     $result = $db->query("SELECT " . self::ID_COL . " as " . self::ID_ALIAS . ", " . self::ID_RESP_COL . " as " . self::ID_RESP_ALIAS . ", " . self::ANNEE_COL . " as " . self::ANNEE_ALIAS . ", " . self::NOM_COL . " as " . self::NOM_ALIAS . " FROM " . self::TABLE . " ORDER BY " . self::ANNEE_COL . " DESC");
     $result->setFetchMode(PDO::FETCH_OBJ);
     $list = $result->fetchAll();
     $formations = array();
     foreach ($list as $f) {
         array_push($formations, new FormationsModel($f));
     }
     return $formations;
 }
Example #6
0
 function db_connect($cdata)
 {
     if ($cdata[2]) {
         $DB = DB::Connect($cdata[2]);
     } else {
         global ${$cdata[3]};
         $DB = ${$cdata[3]};
     }
     if (DB::isError($DB)) {
         die($DB->getMessage() . "\n" . $DB->getUserInfo() . "\n");
     }
     return $DB;
 }
function get_user_id($name)
{
    $dsn = 'mysql://root@localhost/mysql';
    $db =& DB::Connect($dsn, array());
    if (PEAR::isError($db)) {
        die($db->getMessage());
    }
    $res = $db->query('SELECT host FROM user WHERE user=?', array($name));
    $id = null;
    while ($res->fetchInto($row)) {
        $id = $row[0];
    }
    return $id;
}
Example #8
0
 private function getUserInfo()
 {
     $this->user_id = 1;
     global $_CONFIG;
     $this->config = $_CONFIG;
     $dbc = new DB();
     $dbc->Connect("{$_CONFIG['db']['host']}", "{$_CONFIG['db']['user']}", "{$_CONFIG['db']['password']}", "{$_CONFIG['db']['db_name']}");
     $this->dbc = $dbc;
     $this->dbc->Query("SELECT * FROM minishop_tcart WHERE cUserID=" . $this->user_id);
     $cart = $this->dbc->ResultToArray();
     $this->cart_id = $cart[0]['cID'];
     $this->dbc->Query("SELECT * FROM minishop_tusers WHERE cID=" . $this->user_id);
     $user = $this->dbc->ResultToArray();
     $this->user_cash = $user[0]['cCash'];
 }
Example #9
0
 public static function findById($id)
 {
     $db = DB::Connect();
     if (isset($db)) {
         $query = "SELECT id_enseignant as id, prenom_enseignant as prenom, nom_enseignant as nom, \n                        tel_enseignant as tel, email_enseignant as email, \n                        login_secu as login, motdepasse_secu as password  \n                    FROM ENSEIGNANTS\n                    NATURAL JOIN SECURITE\n                    WHERE id_enseignant = :id";
         $req = $db->prepare($query);
         $req->bindParam(":id", $id, PDO::PARAM_INT);
         $req->execute();
         $enseignant = $req->fetch(PDO::FETCH_OBJ);
         if (!empty($enseignant)) {
             return new EnseignantsModel($enseignant);
         }
         return false;
     }
 }
Example #10
0
 function __construct()
 {
     global $g;
     //mysql_connect($g['db_host'],$g['db_user'],$g['db_pass'],null);//,MYSQL_CLIENT_SSL);
     //mysql_select_db($g['db_name']);
     //mysql_query('SET NAMES "utf8"');
     //mysql_query("SET time_zone = '{$g['timezone']}'");
     // setting database connections
     $db_opts =& \PEAR::getStaticProperty('DB_DataObject', 'options');
     $db_opts = $g['DB_DataObject'];
     $this->name = substr($g['DB_DataObject']['database'], strrpos($g['DB_DataObject']['database'], '/') + 1);
     $this->_db =& \DB::Connect($g['DB_DataObject']['database'], array());
     if (\PEAR::isError($this->_db)) {
         die($this->_db->getMessage());
     }
     $this->_db->setFetchMode(DB_FETCHMODE_ASSOC);
 }
Example #11
0
File: DB.php Project: rhertzog/lcs
 /**
  * Connect to database by using the given DSN string
  *
  * @access private
  * @param  string DSN string
  * @return mixed  Object on error, otherwise bool
  */
 function _connect($dsn)
 {
     if (is_string($dsn) || is_array($dsn)) {
         $this->db = DB::Connect($dsn);
     } elseif (get_parent_class($dsn) == "db_common") {
         $this->db = $dsn;
     } elseif (DB::isError($dsn)) {
         return PEAR::raiseError($dsn->getMessage(), $dsn->getCode());
     } else {
         return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__, 41, PEAR_ERROR_RETURN, null, null);
     }
     if (DB::isError($this->db) || PEAR::isError($this->db)) {
         return PEAR::raiseError($this->db->getMessage(), $this->db->getCode());
     } else {
         return true;
     }
 }
Example #12
0
 /**
  * (内部関数) SQL文を実行する
  *
  * @param SQL文
  * @return クエリ結果リソース
  */
 static function _query($sql)
 {
     static $db;
     // DB接続
     if (!$db) {
         $db = DB::Connect(ACS_DSN);
         $db->setFetchMode(DB_FETCHMODE_ASSOC);
     }
     // 通常テーブル名を言語仕様テーブル名に変換
     $lang = ACSMsg::get_lang(FALSE);
     if ($lang != ACS_DEFAULT_LANG && $lang != "") {
         $tables_array = ACSMsg::get_lang_tables_array();
         foreach ($tables_array as $table) {
             $sql = mb_ereg_replace("([, \t\n\\(\\)\\*\\+\\-\\/]+)" . "(" . $table . ")" . "([., \t\n\\(\\)\\*\\+\\-\\/]+|\$)", "\\1" . $table . "_" . $lang . "\\3", $sql);
         }
     }
     if (ACS_DEBUG_MODE && isset($_GET['timer'])) {
         $timelimit = $_GET['timer'];
         if (empty($timelimit)) {
             $timelimit = 0;
             // デフォルト0秒
         }
         $time_array = explode(' ', microtime());
         $start_time = substr($time_array[1] . substr($time_array[0], 1), 0, 14);
         $res = $db->query($sql);
         $time_array = explode(' ', microtime());
         $end_time = substr($time_array[1] . substr($time_array[0], 1), 0, 14);
         $diff_time = substr($end_time - $start_time, 0, 5);
         if (floatval($diff_time) >= $timelimit) {
             _debug($sql);
             echo "<code>{$start_time} -&gt; {$end_time}  (<font color=red>{$diff_time}</font> sec)</code>";
         }
     } else {
         $res = $db->query($sql);
     }
     return $res;
 }
Example #13
0
function &GetLinksSearch(&$attrs)
{
    global $C;
    $DB = new DB($C['db_hostname'], $C['db_username'], $C['db_password'], $C['db_name']);
    $DB->Connect();
    $links = array('links' => array(), 'pagination' => FALSE);
    $per_page = isset($attrs['perpage']) ? $attrs['perpage'] : 20;
    $page = isset($_GET['p']) ? $_GET['p'] : 1;
    $order_clause = empty($attrs['order']) ? '' : "ORDER BY {$attrs['order']}";
    $query = "SELECT * FROM lx_links WHERE status='active' AND MATCH(title,description,keywords) AGAINST (? IN BOOLEAN MODE) {$order_clause}";
    $binds = array($_GET['s']);
    $links['pagination'] = $DB->QueryWithPagination($query, $binds, $page, $per_page);
    if ($links['pagination']['result']) {
        while ($link = $DB->NextRow($links['pagination']['result'])) {
            $user_fields = $DB->Row('SELECT * FROM lx_link_fields WHERE link_id=?', array($link['link_id']));
            $link = array_merge($link, $user_fields);
            $link['date_added'] = strtotime($link['date_added']);
            $links['links'][] = $link;
        }
        $DB->Free($links['pagination']['result']);
    }
    unset($links['pagination']['result']);
    return $links;
}
Example #14
0
 public static function findByIddevoir($iddevoir, $idetu, $groupe)
 {
     $db = DB::Connect();
     if ($groupe == 1) {
         $query = $db->prepare("select note_groupes.note_groupe as notegroupe,groupes.id_groupe as idgroupe,\n        devoirs.id_devoir as iddevoir,note_groupes.commentaire_enseignant_groupe as notecommentaire  \n        from note_groupes,groupes,devoirs,etudiants,appartenir,matieres \n        where note_groupes.DEVOIRS_idDevoir=devoirs.id_devoir\n        and note_groupes.GROUPES_id_groupe=groupes.id_groupe\n        and etudiants.id_etu=appartenir.id_etu\n        and groupes.id_groupe=appartenir.id_groupe\n        and etudiants.id_etu=:idetu\n        and devoirs.id_devoir=:iddevoir;");
         $query->bindParam(':iddevoir', $iddevoir, PDO::PARAM_INT);
         $query->bindParam(':idetu', $idetu, PDO::PARAM_INT);
         $query->execute();
         $result = $query->fetch(PDO::FETCH_OBJ);
         if (!empty($result)) {
             return new noteModel($result, 1);
         }
     } else {
         $query = $db->prepare("select note_etudiants.note_etudiant as noteetudiant,note_etudiants.id_etu as idetudiant\n            ,note_etudiants.id_devoir as iddevvoir,note_etudiants.commentaire_enseignant_etudiant as notecommentaire\n            from note_etudiants,etudiants,devoirs,appartenir \n            where devoirs.id_devoir=note_etudiants.id_devoir\n            and etudiants.id_etu=note_etudiants.id_etu \n            and note_etudiants.id_etu=:idetu and note_etudiants.id_devoir=:iddevoir;");
         $query->bindParam(':iddevoir', $iddevoir, PDO::PARAM_INT);
         $query->bindParam(':idetu', $idetu, PDO::PARAM_INT);
         $query->execute();
         $result2 = $query->fetch(PDO::FETCH_OBJ);
         if (!empty($result2)) {
             return new noteModel($result2, 0);
         }
     }
     return false;
 }
Example #15
0
 private function __construct() {
     $dsn = 'mysql://*****:*****@localhost/photos';
     $this->_handle = & DB::Connect($dsn, array());
 }
Example #16
0
 public function update_observer($type, $message, $errfile, $errline, $errcontext, $backtrace)
 {
     global $cron_funcs_prior;
     $backtrace = htmlspecialchars_decode(str_replace(array('<br />', '&nbsp;'), array("\n", ' '), $backtrace));
     $x = $cron_funcs_prior[$this->func_md5] . ":\ntype=" . $type . "\nmessage=" . $message . "\nerror file=" . $errfile . "\nerror line=" . $errline . "\n" . $backtrace;
     error_log($x . "\n", 3, DATA_DIR . '/cron.txt');
     DB::IgnoreErrors(array('adodb_error', null));
     //ignore adodb errors
     $query_args = array(time(), $this->func_md5);
     $query = DB::TypeControl('UPDATE cron SET last=%d,running=0 WHERE func=%s', $query_args);
     if (!DB::Execute($query, $query_args)) {
         //if not - probably server gone away - retry every 10 seconds for 1h
         for ($i = 0; $i < 360; $i++) {
             sleep(10);
             $connection = null;
             try {
                 $connection = DB::Connect();
                 //reconnect database as new connection
             } catch (Exception $e) {
                 continue;
                 //no connection - wait
             }
             if ($connection->Execute($query, $query_args)) {
                 //if ok then break and exit
                 $connection->Close();
                 break;
             }
             $connection->Close();
         }
     }
     return true;
 }
Example #17
0
function logsearch()
{
    global $DB, $C;
    if (!isset($DB)) {
        $DB = new DB($C['db_hostname'], $C['db_username'], $C['db_password'], $C['db_name']);
        $DB->Connect();
    }
    if (preg_match_all('~[\'"]([^\'"]+)[\'"]|(\\b\\w+\\b)~', $_GET['s'], $matches)) {
        $date = gmdate('Y-m-d H:i:s', _timewithtz());
        foreach ($matches[0] as $match) {
            $match = str_replace(array('"', '\''), '', $match);
            if ($DB->Update('UPDATE `tx_search_terms` SET `searches`=`searches`+1,`date_last_search`=? WHERE `term`=?', array($date, $match)) < 1) {
                $DB->Update('INSERT INTO `tx_search_terms` VALUES (?,?,?,?)', array(null, $match, 1, $date));
            }
        }
    }
}
Example #18
0
 /**
  * Connect to database by using the given DSN string
  *
  * @access private
  * @param  string DSN string
  * @return mixed  Object on error, otherwise bool
  */
 function _connect($dsn)
 {
     $this->log('Auth_Container_DB::_connect() called.', AUTH_LOG_DEBUG);
     if (is_string($dsn) || is_array($dsn)) {
         $this->db = DB::Connect($dsn, $this->options['db_options']);
     } elseif (is_subclass_of($dsn, 'db_common')) {
         $this->db = $dsn;
     } elseif (DB::isError($dsn)) {
         return PEAR::raiseError($dsn->getMessage(), $dsn->getCode());
     } else {
         return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__, 41, PEAR_ERROR_RETURN, null, null);
     }
     if (DB::isError($this->db) || PEAR::isError($this->db)) {
         return PEAR::raiseError($this->db->getMessage(), $this->db->getCode());
     } else {
         return true;
     }
 }
$DSN = "mysql://{$dbuser}:{$dbpass}@{$dbhost}/{$dbbase}";
// Identification de l'utilisateur
$options = array('table' => 'uti_utilisateur', 'usernamecol' => 'uti_login', 'passwordcol' => 'uti_password', 'dsn' => $DSN);
require_once PATH_INC_BACKEND . 'logon.php';
$openwebAuth = new Auth("DB", $options, 'ow_html_login_box', true);
$openwebAuth->start();
if (isset($_GET['logon']) && $openwebAuth->getAuth()) {
    $openwebAuth->logout();
    unset($_SESSION['utilisateur']);
    $openwebAuth->start();
}
if (!$openwebAuth->getAuth()) {
    exit;
}
// Connexion à la base de données
$db = DB::Connect($DSN);
$db->setFetchMode(DB_FETCHMODE_ASSOC);
// Récuperation des données de l'utilisateur
if (!isset($_SESSION['utilisateur'])) {
    require_once PATH_INC_BACKEND_SERVICE . 'UserManager.class.php';
    $um = new UserManager($db);
    if (($user = $um->getUserDatas($openwebAuth->username)) === null) {
        session_destroy();
        echo 'Problème de lecture de vos données personnelles';
        exit;
    }
    // Vérifie si l'utilisateur est autorisé à se connecter
    if (intval($user['uti_valide']) == 0) {
        echo 'Votre compte est désactivé';
        exit;
    }
Example #20
0
 /**
  * Fonction permettant de modifier une matiere dans la base de données
  * 
  * @param MatieresModel $m la matière à mettre à jour
  */
 public static function update(MatieresModel $m)
 {
     $db = DB::Connect();
     $query = $db->prepare("UPDATE " . self::TABLE . " SET " . self::NOM_COL . " = :nom " . " WHERE " . self::ID_COL . " = :id ");
     try {
         $query->bindValue(":nom", $m->getName(), PDO::PARAM_STR);
         $query->bindValue(":id", $m->getId(), PDO::PARAM_INT);
         $db->beginTransaction();
         $query->execute();
         $db->commit();
     } catch (PDOException $e) {
         $db->rollback();
         DB::setError($e->getMessage());
         return false;
     }
     return self::findById($m->getId());
 }
Example #21
0
 /**
  * Fonction permettant de mettre a jour les informations d'un fichier attendu
  * 
  * @param FichiersModel $f le fichier attendu a mettre a jour
  */
 public static function update(FichiersModel $f)
 {
     $db = DB::Connect();
     $query = $db->prepare("UPDATE " . self::TABLE_F_ATTENDU . " SET " . self::NOM_COL . " = :name," . self::DATE_COL . " = :date," . self::HEURE_COL . " = :heure," . self::RETARD_COL . " = :retard " . " WHERE " . self::ID_COL . " = :id");
     try {
         $query->bindValue(":id", $f->getId(), PDO::PARAM_INT);
         $query->bindValue(":name", $f->getName(), PDO::PARAM_STR);
         $query->bindValue(":date", $f->getDate(), PDO::PARAM_STR);
         $query->bindValue(":heure", $f->getHeure(), PDO::PARAM_STR);
         $query->bindValue(":retard", $f->acceptRetard(), PDO::PARAM_BOOL);
         $db->beginTransaction();
         $query->execute();
         $db->commit();
     } catch (PDOException $e) {
         $db->rollback();
         DB::setError($e->getMessage());
         return false;
     }
     return self::findById($f->getId());
 }
Example #22
0
<?php

@header('Content-type: text/html;charset=UTF-8');
require_once "config_global.php";
require_once "checkpostandget.php";
require_once "classes/key.class.php";
require_once "classes/mysql.class.php";
require_once "classes/page.php";
date_default_timezone_set('Asia/Shanghai');
set_time_limit(0);
@session_start();
$db = new DB();
$db->Connect(DBHOST, DBUSER, DBPW, DBNAME);
mysql_query("set names 'utf8'");
require_once "classes/lib.class.php";
Example #23
0
 function connect()
 {
     global $user;
     global $db_include_path;
     if ($this->pear_type == 'MDB2') {
         require_once $db_include_path . 'MDB2.php';
         $this->mode = 'MDB2';
         $this->fetch_mode = MDB2_FETCHMODE_ASSOC;
     } else {
         require_once $db_include_path . 'DB.php';
         $this->mode = 'DB';
         $this->fetch_mode = DB_FETCHMODE_ASSOC;
     }
     if ($this->db_split) {
         $this->debug[] = 'configuration: db_split is set to true, both read and write servers required';
     } else {
         $this->debug[] = 'configuration: db_split is set to false, only one server for read/write required';
     }
     if ($this->random_connect_read) {
         $this->debug[] = 'configuration: Read server order being randomized';
     } else {
         $this->debug[] = 'configuration: Maintaining read server order';
     }
     if ($this->random_connect_write) {
         $this->debug[] = 'configuration: Write server order being randomized';
     } else {
         $this->debug[] = 'configuration: Maintaining write server order';
     }
     if (empty($this->read_servers)) {
         $this->debug[] = 'connecting: No sql read servers defined';
     } else {
         if ($this->random_connect_read) {
             shuffle($this->read_servers);
         }
         foreach ($this->read_servers as $v) {
             $dsn = $this->db_type . '://' . $v[0] . ':' . $v[1] . '@' . $v[2] . '/' . $v[3];
             if ($this->pear_type == 'MDB2') {
                 $db_read =& MDB2::Connect($dsn, array('persistent' => $this->persistent));
             } else {
                 $db_read = DB::Connect($dsn, $this->persistent);
             }
             $this->db_read = $db_read;
             if (PEAR::isError($this->db_read) || !$this->db_read) {
                 $this->debug[] = 'connecting: UNABLE TO CONNECT to read DB: ' . $v[2] . ' (' . $this->db_type . ') as ' . $v[0] . ' using PEAR ' . $this->pear_type;
             } else {
                 $this->debug[] = 'connecting: Connected to read DB: ' . $v[2] . ' (' . $this->db_type . ') as ' . $v[0] . ' using PEAR ' . $this->pear_type;
                 $this->current_read = $v;
                 break;
             }
         }
         if (!$this->db_read || PEAR::isError($this->db_read)) {
             $this->debug[] = 'connecting: Could not connect to any configured read servers';
         } else {
             if ($this->db_split) {
                 if (empty($this->write_servers)) {
                     $this->debug[] = 'connecting: No sql write servers defined';
                 } else {
                     if ($this->random_connect_write) {
                         shuffle($this->write_servers);
                     }
                     foreach ($this->write_servers as $v) {
                         $dsn = $this->db_type . '://' . $v[0] . ':' . $v[1] . '@' . $v[2] . '/' . $v[3];
                         if ($this->pear_type == 'MDB2') {
                             $this->db_write =& MDB2::Connect($dsn, true);
                         } else {
                             $this->db_write =& DB::Connect($dsn, true);
                         }
                         if (PEAR::isError($this->db_write) || !$this->db_write) {
                             $this->debug[] = 'connecting: Unable to connect to write DB: ' . $v[2] . ' as ' . $v[0];
                         } else {
                             $this->debug[] = 'connecting: Connected to write DB: ' . $v[2] . ' (' . $this->db_type . ') as ' . $v[0] . ' using PEAR ' . $this->pear_type;
                             $this->current_write = $v;
                             break;
                         }
                     }
                     if (!$this->db_write || PEAR::isError($this->db_write)) {
                         $this->debug[] = 'connecting: Could not connect to any configured write servers';
                     }
                 }
             } else {
                 $this->db_write = $this->db_read;
                 $this->debug[] = 'connection: db_split is set to false, using current read server as read/write';
                 $this->debug[] = 'connecting: Successfully connnected to required sql servers';
                 return true;
             }
         }
     }
     $user->notices[] = 'Could not establish a connection to the database';
 }
Example #24
0
<?php

$GLOBALS["page_start"] = microtime(true);
require_once "config.inc";
#DB stuff
require_once "DB.php";
$db = DB::Connect($GLOBALS["cfg"]["dsn"]) or die("Sorry");
$db->setFetchMode(DB_FETCHMODE_ASSOC);
$mytz = "-4:00";
$in_dst = 1;
if ($_COOKIE["u"]) {
    $sql = 'select id, username, tz, use_dst from users where md5(concat("u:", username, password)) = ?';
    $user = $db->getRow($sql, array($_COOKIE["u"]));
    if ($user) {
        $my_username = $user["username"];
        $my_id = $user["id"];
        $mytz = $user["tz"];
        if ($in_dst) {
            if ($user["use_dst"]) {
                $mytz = sprintf("%d:00", $mytz + 1);
            }
        }
    }
    unset($user);
    //var_dump($user);
}
if ($_POST['api_user'] && $_POST['api_password']) {
    $_SERVER['PHP_AUTH_USER'] = $_POST['api_user'];
    $_SERVER['PHP_AUTH_PW'] = $_POST['api_password'];
}
if ($_SERVER['PHP_AUTH_USER'] && $_SERVER['PHP_AUTH_PW'] && !$my_id) {
Example #25
0
require_once "PHPUnit2/Framework/IncompleteTestError.php";
static $tmpdir;
// temporary directory
//  Create a temporary directory to receive generated files
//  @todo <b>FIXME:</b> Is this platform independent?
do {
    $tmpdir = '/tmp/traxtest' . mt_rand(0, 99999999);
} while (!mkdir($tmpdir, 0700));
define('TRAX_ROOT', $tmpdir);
define('TRAX_ENV', 'test');
// Set up information that normally comes from database.ini
Trax::$database_settings['test'] = array('phptype' => 'mysql', 'database' => 'test_development', 'hostspec' => 'localhost', 'username' => 'root', 'password' => '', 'persistent' => true);
//  Create a DB to test with
@ini_set('include_path', './mockDB:' . ini_get('include_path'));
require_once "DB.php";
$db =& DB::Connect(Trax::$database_settings[TRAX_ENV], array('persistent' => true));
if (PEAR::isError($db) || is_a($db, 'DB_Error')) {
    PHPUnit2_Framework_Assert::fail("Unable to create database");
}
$db->setFetchMode(DB_FETCHMODE_ASSOC);
Trax::$active_record_connections[TRAX_ENV] =& $db;
require_once "trax_generator.php";
require_once "action_view/helpers.php";
require_once "action_view/helpers/active_record_helper.php";
require_once "active_record.php";
require_once "trax_exceptions.php";
/**
 *  When a class is referenced, get it from app/models
 */
function __autoload($class_name)
{
Example #26
0
function CreateTables()
{
    global $t;
    $DB = new DB($_REQUEST['db_hostname'], $_REQUEST['db_username'], $_REQUEST['db_password'], $_REQUEST['db_name']);
    $DB->Connect();
    $tables = array();
    IniParse("{$GLOBALS['BASE_DIR']}/includes/tables.php", TRUE, $tables);
    foreach ($tables as $name => $create) {
        $DB->Update("CREATE TABLE IF NOT EXISTS {$name} ( {$create} ) TYPE=MyISAM");
    }
    $password = RandomPassword();
    $domain = preg_replace('~^www\\.~', '', $_SERVER['HTTP_HOST']);
    $t->assign('password', $password);
    $DB->Update('DELETE FROM lx_administrators WHERE username=?', array('administrator'));
    $DB->Update('INSERT INTO lx_administrators VALUES (?,?,?,?,?,?,?,?,?,?)', array('administrator', sha1($password), '', 0, 'Administrator', "webmaster@{$domain}", 'administrator', '', 0, 0));
    $DB->Disconnect();
}
Example #27
0
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
define('ToplistX', TRUE);
require_once '../includes/common.php';
require_once 'includes/functions.php';
require_once "{$GLOBALS['BASE_DIR']}/includes/mysql.class.php";
$DB = new DB($C['db_hostname'], $C['db_username'], $C['db_password'], $C['db_name']);
$DB->Connect();
// Check consistency of last_updates
$last_updates = unserialize(GetValue('last_updates'));
if ($DB->Count('SELECT COUNT(*) FROM `tlx_daily_stats` WHERE `date_stats`=?', array($last_updates['daily']))) {
    // Update the daily value
    $today = gmdate('Y-m-d', TIME_NOW);
    $last_updates['daily'] = $today;
    StoreValue('last_updates', serialize($last_updates));
}
// Load table data
IniParse("{$GLOBALS['BASE_DIR']}/includes/tables.php", TRUE, $table_defs);
// Load existing tables
$tables = $DB->GetTables();
// Create the tlx_account_ranks table
if (!isset($tables['tlx_account_ranks'])) {
    $DB->Update("CREATE TABLE IF NOT EXISTS `tlx_account_ranks` ( {$table_defs['tlx_account_ranks']} ) TYPE=MyISAM");
Example #28
0
function ConvertData()
{
    global $C, $DB, $from_shell;
    $errors = array();
    if (!is_dir($_REQUEST['directory'])) {
        $errors[] = "The directory " . htmlspecialchars($_REQUEST['directory']) . " does not exist on your server";
        return DisplayMain($errors);
    }
    if (!is_file("{$_REQUEST['directory']}/tgpr.pl")) {
        $errors[] = "The tgpr.pl file could not be found in the " . htmlspecialchars($_REQUEST['directory']) . " directory";
        return DisplayMain($errors);
    }
    if (!is_readable("{$_REQUEST['directory']}/tgpr.pl")) {
        $errors[] = "The tgpr.pl file in the " . htmlspecialchars($_REQUEST['directory']) . " directory could not be opened for reading";
        return DisplayMain($errors);
    }
    // Check version
    $version_file_contents = file_get_contents("{$_REQUEST['directory']}/tgpr.pl");
    if (preg_match('~\\$VERSION\\s+=\\s+\'(.*?)\'~', $version_file_contents, $matches)) {
        list($a, $b, $c) = explode('.', $matches[1]);
        if ($b < 2 || strpos($c, '-SS') === FALSE) {
            $errors[] = "Your TGP Rotator installation is outdated; please upgrade to the very latest snapshot release (1.2.1-SS)";
            return DisplayMain($errors);
        }
    } else {
        $errors[] = "Unable to extract version information from tgpr.pl; your version of TGP Rotator is likely too old";
        return DisplayMain($errors);
    }
    // Extract MySQL information
    $mysql_file_contents = file_get_contents("{$_REQUEST['directory']}/data/variables");
    if ($mysql_file_contents === FALSE) {
        $errors[] = "Unable to read contents of the variables file";
        return DisplayMain($errors);
    }
    $vars = array();
    if (preg_match_all('~^\\$([a-z0-9_]+)\\s+=\\s+\'(.*?)\';$~msi', $mysql_file_contents, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $match) {
            $vars[$match[1]] = $match[2];
        }
    }
    if (!isset($vars['USERNAME']) || !isset($vars['DATABASE']) || !isset($vars['HOSTNAME'])) {
        $errors[] = "Unable to extract MySQL database information from the variables file";
        return DisplayMain($errors);
    }
    if (!is_writable("{$GLOBALS['BASE_DIR']}/annotations")) {
        $errors[] = "Change the permissions on the TGPX annotations directory to 777";
        return DisplayMain($errors);
    }
    if ($C['preview_dir'] == $vars['THUMB_DIR']) {
        $errors[] = "The TGPX Thumbnail URL cannot be the same as the TGP Rotator Thumbnail URL";
        return DisplayMain($errors);
    }
    $CONVERTDB = new DB($vars['HOSTNAME'], $vars['USERNAME'], $vars['PASSWORD'], $vars['DATABASE']);
    $CONVERTDB->Connect();
    $CONVERTDB->Update('SET wait_timeout=86400');
    $columns = $CONVERTDB->GetColumns('tr_Galleries');
    if (!in_array('Thumbnail_URL', $columns)) {
        $errors[] = "Your TGP Rotator installation is outdated; please upgrade to the latest snapshot release";
        return DisplayMain($errors);
    }
    if (!$from_shell) {
        echo "<pre>";
    }
    // Copy annotations
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "Copying annotation font files and images...\n");
    echo "Copying annotation font files and images...\n";
    flush();
    $annotations =& DirRead($vars['ANNOTATION_DIR'], '^[^.]');
    foreach ($annotations as $annotation) {
        @copy("{$vars['ANNOTATION_DIR']}/{$annotation}", "{$GLOBALS['BASE_DIR']}/annotations/{$annotation}");
    }
    // Copy thumbnail previews
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "Copying thumbnail preview images...\n");
    echo "Copying thumbnail preview images...\n";
    flush();
    $thumbs =& DirRead($vars['THUMB_DIR'], '\\.jpg$');
    foreach ($thumbs as $thumb) {
        @copy("{$vars['THUMB_DIR']}/{$thumb}", "{$C['preview_dir']}/t_{$thumb}");
        @chmod("{$C['preview_dir']}/t_{$thumb}", 0666);
    }
    //
    // Dump annotations
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "Converting annotation settings...\n");
    echo "Converting annotation settings...\n";
    flush();
    $annotations = array();
    $DB->Update('DELETE FROM `tx_annotations`');
    $result = $CONVERTDB->Query('SELECT * FROM `tr_Annotations`');
    while ($annotation = $CONVERTDB->NextRow($result)) {
        $DB->Update('INSERT INTO `tx_annotations` VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', array(null, $annotation['Identifier'], strtolower($annotation['Type']), $annotation['String'], 0, $annotation['Font_File'], $annotation['Size'], $annotation['Color'], $annotation['Shadow'], $annotation['Image_File'], $annotation['Transparency'], $annotation['Location']));
        $annotations[$annotation['Unique_ID']] = $DB->InsertID();
    }
    $CONVERTDB->Free($result);
    //
    // Dump categories
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "Converting categories...\n");
    echo "Converting categories...\n";
    flush();
    $categories = array();
    $category_ids = array();
    $DB->Update('DELETE FROM `tx_categories`');
    $result = $CONVERTDB->Query('SELECT * FROM `tr_Categories`');
    while ($category = $CONVERTDB->NextRow($result)) {
        $tag = CreateCategoryTag($category['Name']);
        $categories[$category['Name']] = $tag;
        $DB->Update('INSERT INTO `tx_categories` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', array(null, $category['Name'], $tag, empty($category['Pictures']) ? 0 : 1, $category['Pictures'], 10, 30, 12288, "{$vars['THUMB_WIDTH']}x{$vars['THUMB_HEIGHT']}", 1, $annotations[$category['Ann_Pictures']], empty($category['Movies']) ? 0 : 1, $category['Movies'], 5, 30, 102400, "{$vars['THUMB_WIDTH']}x{$vars['THUMB_HEIGHT']}", 1, $annotations[$category['Ann_Movies']], -1, 0, null, null, null));
        $category_ids[$category['Name']] = $DB->InsertID();
    }
    $CONVERTDB->Free($result);
    //
    // Dump sponsors
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "Converting sponsors...\n");
    echo "Converting sponsors...\n";
    flush();
    $counter = 1;
    $sponsors = array();
    $DB->Update('DELETE FROM `tx_sponsors`');
    $result = $CONVERTDB->Query('SELECT DISTINCT `Sponsor` FROM `tr_Galleries` WHERE `Sponsor`!=?', array(''));
    while ($sponsor = $CONVERTDB->NextRow($result)) {
        $sponsors[$sponsor['Sponsor']] = $counter;
        $DB->Update("INSERT INTO `tx_sponsors` VALUES (?,?,?)", array($counter++, $sponsor['Sponsor'], null));
    }
    $CONVERTDB->Free($result);
    //
    // Dump gallery data
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "Converting gallery data...\n");
    echo "Converting gallery data...\n";
    flush();
    $DB->Update('DELETE FROM `tx_galleries`');
    $DB->Update('DELETE FROM `tx_gallery_fields`');
    $DB->Update('DELETE FROM `tx_gallery_icons`');
    $DB->Update('DELETE FROM `tx_gallery_previews`');
    $DB->Update('ALTER TABLE `tx_galleries` AUTO_INCREMENT=0');
    $DB->Update('ALTER TABLE `tx_gallery_previews` AUTO_INCREMENT=0');
    $result = $CONVERTDB->Query('SELECT * FROM `tr_Galleries` ORDER BY `Gallery_ID`');
    $preview_sizes = array();
    while ($gallery = $CONVERTDB->NextRow($result)) {
        $DB->Update("INSERT INTO `tx_galleries` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", array(null, $gallery['Gallery_URL'], $gallery['Description'], $gallery['Keywords'], $gallery['Thumbnails'], $C['from_email'], null, $gallery['Weight'], $gallery['Clicks'], $_SERVER['REMOTE_ADDR'], null, !empty($gallery['Sponsor']) ? $sponsors[$gallery['Sponsor']] : null, 'permanent', strtolower($gallery['Type']), $gallery['Status'] == 'Pending' ? 'approved' : strtolower($gallery['Status']), $gallery['Status'] == 'Disabled' ? 'approved' : null, date(DF_DATETIME, TimeWithTz($gallery['Added'])), date(DF_DATETIME, TimeWithTz($gallery['Added'])), date(DF_DATETIME, TimeWithTz($gallery['Added'])), empty($gallery['Scheduled_Date']) ? null : "{$gallery['Scheduled_Date']} 00:00:00", empty($gallery['Display_Date']) ? null : "{$gallery['Display_Date']} 12:00:00", null, null, 'TGPR Convert', '', null, 0, empty($gallery['Thumbnail_URL']) ? 0 : 1, $gallery['Allow_Scan'], $gallery['Allow_Thumb'], $gallery['Times_Selected'], $gallery['Used_Counter'], $gallery['Build_Counter'], null, MIXED_CATEGORY . " " . $categories[$gallery['Category']]));
        $gallery_id = $DB->InsertID();
        $gallery_info = array('gallery_id' => $gallery_id);
        $insert = CreateUserInsert('tx_gallery_fields', $gallery_info);
        $DB->Update('INSERT INTO `tx_gallery_fields` VALUES (' . $insert['bind_list'] . ')', $insert['binds']);
        foreach (explode(',', $gallery['Icons']) as $icon_id) {
            if (isset($icons[$icon_id])) {
                $DB->Update('INSERT INTO `tx_gallery_icons` VALUES (?,?)', array($gallery_id, $icons[$icon_id]));
            }
        }
        if (!empty($gallery['Thumbnail_URL'])) {
            $dimensions = '';
            if (!empty($gallery['Thumb_Width']) && !empty($gallery['Thumb_Height'])) {
                $dimensions = "{$gallery['Thumb_Width']}x{$gallery['Thumb_Height']}";
                $preview_sizes[$dimensions] = TRUE;
            }
            $DB->Update('INSERT INTO `tx_gallery_previews` VALUES (?,?,?,?)', array(null, $gallery_id, '', $dimensions));
            $preview_id = $DB->InsertID();
            if (preg_match('~^' . preg_quote($vars['THUMB_URL']) . '~i', $gallery['Thumbnail_URL'])) {
                $gallery['Thumbnail_URL'] = "{$C['preview_url']}/{$preview_id}.jpg";
                $DB->Update('UPDATE `tx_gallery_previews` SET `preview_url`=? WHERE `preview_id`=?', array($gallery['Thumbnail_URL'], $preview_id));
                @rename("{$C['preview_dir']}/t_{$gallery['Gallery_ID']}.jpg", "{$C['preview_dir']}/{$preview_id}.jpg");
            }
        }
    }
    $CONVERTDB->Free($result);
    // Update the stored thumbnail preview sizes
    $sizes = unserialize(GetValue('preview_sizes'));
    if (!is_array($sizes)) {
        $sizes = array();
    }
    $sizes = array_merge($sizes, array_keys($preview_sizes));
    StoreValue('preview_sizes', serialize(array_unique($sizes)));
    //
    // Dump TGP page data
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "Converting TGP pages...\n");
    echo "Converting TGP pages...\n";
    flush();
    $build_order = 1;
    $DB->Update('DELETE FROM `tx_pages`');
    $DB->Update('ALTER TABLE `tx_pages` AUTO_INCREMENT=0');
    $result = $CONVERTDB->Query('SELECT * FROM `tr_Pages` ORDER BY `Build_Order`');
    while ($page = $CONVERTDB->NextRow($result)) {
        $template = file_get_contents("{$_REQUEST['directory']}/data/pages/{$page['Page_ID']}");
        $template = ConvertTemplate($template);
        $compiled = '';
        $page['Directory'] = preg_replace('~/$~', '', $page['Directory']);
        $DB->Update('INSERT INTO `tx_pages` VALUES (?,?,?,?,?,?,?,?,?)', array(null, "{$page['Directory']}/{$page['Filename']}", $page['Page_URL'], $page['Category'] == 'Mixed' ? null : $category_ids[$page['Category']], $build_order++, 0, null, $template, $compiled));
    }
    $CONVERTDB->Free($result);
    FileAppend("{$GLOBALS['BASE_DIR']}/data/convert.log", "\nData conversion complete!");
    echo "\nData conversion complete!\n";
    if (!$from_shell) {
        echo "</pre>";
    }
}
Example #29
0
<?php

/* 
V4.80 8 Mar 2006  (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
  Released under both BSD license and Lesser GPL library license. 
  Whenever there is any discrepancy between the two licenses, 
  the BSD license will take precedence. 
  Set tabs to 4 for best viewing.
	
  Latest version is available at http://adodb.sourceforge.net
*/
error_reporting(E_ALL);
include_once '../adodb-pear.inc.php';
$username = '******';
$password = '';
$hostname = 'localhost';
$databasename = 'xphplens';
$driver = 'mysql';
$dsn = "{$driver}://{$username}:{$password}@{$hostname}/{$databasename}";
$db = DB::Connect($dsn);
$db->setFetchMode(ADODB_FETCH_ASSOC);
$rs = $db->Query('select firstname,lastname from adoxyz');
$cnt = 0;
while ($arr = $rs->FetchRow()) {
    print_r($arr);
    print "<br>";
    $cnt += 1;
}
if ($cnt != 50) {
    print "<b>Error in \$cnt = {$cnt}</b>";
}
Example #30
0
<?php

require_once 'PEAR.php';
require_once 'DB.php';
require_once 'DB/Table.php';
require_once 'Var_Dump.php';
class example extends DB_Table
{
    var $col = array('xvarchar' => array('type' => 'varchar', 'size' => 128, 'require' => false, 'qf_type' => 'radio', 'qf_radiosep' => '<br />', 'qf_vals' => array('another', 'other', 'that', 'this')), 'xbool' => array('type' => 'boolean'), 'xchar' => array('type' => 'char', 'size' => 10, 'require' => true), 'xclob' => array('type' => 'clob', 'require' => false), 'xsmint' => array('type' => 'smallint', 'require' => false, 'qf_client' => true), 'xint' => array('type' => 'integer', 'require' => true), 'xbigint' => array('type' => 'bigint', 'require' => false), 'xdecimal' => array('type' => 'decimal', 'size' => 5, 'scope' => 2, 'require' => false), 'xsingle' => array('type' => 'single', 'require' => false), 'xdouble' => array('type' => 'double', 'require' => false), 'xdate' => array('type' => 'date', 'default' => "'0001-01-01'", 'require' => false), 'xtime' => array('type' => 'time', 'default' => "'00:00:00'", 'require' => false), 'xtimestamp' => array('type' => 'timestamp'));
    var $idx = array('id' => array('type' => 'unique', 'cols' => array('xint')), 'multi' => array('type' => 'normal', 'cols' => array('xdate', 'xtime', 'xchar')));
    var $sql = array('list' => array('select' => '*', 'get' => 'row'));
}
$opts = parse_ini_file('setup.ini', true);
$db = DB::Connect($opts['dsn']);
$example =& new example($db, $opts['example']['table'], $opts['example']['create']);
if ($example->error) {
    Var_Dump::display($example->error);
    die;
}
if ($opts['example']['display']) {
    Var_Dump::display($example);
}
if ($opts['example']['fetch']) {
    $example->fetchmode = DB_FETCHMODE_ASSOC;
    $result = $example->select('list');
    Var_Dump::display($result);
}
$form =& $example->getForm(null, 'mydata', null);
$form->addElement('submit', 'op', 'Submit');
//Var_dump::display($form);
echo "<html><head><title>bogotest</title></head><body>\n";