Пример #1
0
function fcdb_connect($db, $un, $pw)
{
    global $fcdb_sel, $fcdb_conn;
    global $dbhost;
    $ok = true;
    set_error_handler("fcdb_error_handler");
    switch ($fcdb_sel) {
        case "PostgreSQL":
            $fcdb_conn = pg_Connect("dbname={$db} port=5432 user={$un}");
            if (!$fcdb_conn) {
                build_fcdb_error("I cannot make a connection to the database server.");
            }
            $ok = false;
            break;
        case "MySQL":
            $fcdb_conn = mysql_connect("java:comp/env/jdbc/freeciv_mysql");
            if (!$fcdb_conn) {
                build_fcdb_error("I cannot make a connection to the database server.");
                $ok = false;
            } else {
                $ok = mysql_select_db($db, $fcdb_conn);
                if (!$ok) {
                    build_fcdb_error("I cannot open the database." . $db . "  -- " . $fcdb_conn);
                }
            }
            break;
    }
    restore_error_handler();
    return $ok;
}
Пример #2
0
 function open($database, $host, $user, $password)
 {
     $connect_string = "";
     if (!$database) {
         return 0;
     }
     $host = split(":", $host);
     if ($host[0]) {
         $connect_string .= "host={$host['0']}";
     }
     if (isset($host[1])) {
         $connect_string .= " port={$host['1']}";
     }
     if ($user) {
         $connect_string .= " user={$user} ";
     }
     if ($password) {
         $connect_string .= " password={$password} ";
     }
     $connect_string .= " dbname={$database}";
     $this->connect_id = @pg_Connect($connect_string);
     if ($this->connect_id) {
         @pg_exec($this->connect_id, "SET DateStyle TO 'ISO'");
     }
     return $this->connect_id;
 }
Пример #3
0
function connect($host, $port, $options, $tty, $database)
{
    $connection = pg_Connect($host, $port, $options, $tty, $database);
    if (!$connection) {
        echo "Connection to database failed.";
        echo pg_ErrorMessage($connection);
        exit;
    }
    return $connection;
}
Пример #4
0
 /** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Nome da Função: msgErro
    Propósito: Dar a mensagem de erro do sistema para o usuário, inserir
               na tabela de log e notificar para o administrador
    Programador: Werner P. Moraes         Data de Criação: 14/05/2003
    Parâmetros: str Mensagem de erro
    Comentários Adicionais: Insere na tabela log_erro, manda email
                            * (não está pronta)
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 function msgErro($erro)
 {
     global $usuario;
     echo "<PRE>Transport Ltda. - " . date("d/m/Y - H:i:s") . "<HR>";
     echo $php_errormsg . "<HR>";
     echo $erro;
     echo "\n</PRE>";
     # exit();
     if (!$iBanco) {
         $iBanco = pg_Connect(strConexao);
     }
     $sSender = str_replace("'", "''", $_SERVER["REQUEST_URI"]);
     $sErro = str_replace("'", "''", $php_errormsg);
     $sError = str_replace("'", "''", $erro);
 }
Пример #5
0
/**
* Authenticate against a different PostgreSQL database which contains a usr table in
* the AWL format.
*
* @package   awl
*/
function auth_other_awl($username, $password)
{
    global $c;
    $authconn = pg_Connect($c->authenticate_hook['config']['connection']);
    if (!$authconn) {
        echo <<<EOERRMSG
  <html><head><title>Database Connection Failure</title></head><body>
  <h1>Database Error</h1>
  <h3>Could not connect to PostgreSQL database</h3>
  </body>
  </html>
EOERRMSG;
        exit(1);
    }
    if (isset($c->authenticate_hook['config']['columns'])) {
        $cols = $c->authenticate_hook['config']['columns'];
    } else {
        $cols = "*";
    }
    if (isset($c->authenticate_hook['config']['where'])) {
        $andwhere = " AND " . $c->authenticate_hook['config']['where'];
    } else {
        $andwhere = "";
    }
    $qry = new AwlQuery("SELECT {$cols} FROM usr WHERE lower(username) = ? {$andwhere}", strtolower($username));
    $qry->SetConnection($authconn);
    if ($qry->Exec('Login', __LINE, __FILE__) && $qry->rows() == 1) {
        $usr = $qry->Fetch();
        if (session_validate_password($password, $usr->password)) {
            $qry = new AwlQuery("SELECT * FROM usr WHERE user_no = {$usr->user_no};");
            if ($qry->Exec('Login', __LINE, __FILE__) && $qry->rows() == 1) {
                $type = "UPDATE";
            } else {
                $type = "INSERT";
            }
            $qry = new AwlQuery(sql_from_object($usr, $type, 'usr', "WHERE user_no={$usr->user_no}"));
            $qry->Exec('Login', __LINE, __FILE__);
            /**
             * We disallow login by inactive users _after_ we have updated the local copy
             */
            if (isset($usr->active) && $usr->active == 'f') {
                return false;
            }
            return $usr;
        }
    }
    return false;
}
Пример #6
0
/**
* Connect to the database defined in the $c->dbconn[] array
*/
function connect_configured_database()
{
    global $c, $dbconn;
    if (isset($dbconn)) {
        return;
    }
    /**
     * Attempt to connect to the configured connect strings
     */
    $dbconn = false;
    dbg_error_log('pgquery', 'Attempting to connect to database');
    if (isset($c->pg_connect) && is_array($c->pg_connect)) {
        foreach ($c->pg_connect as $k => $v) {
            if (!$dbconn) {
                if ($dbconn = isset($c->use_persistent) && $c->use_persistent ? pg_pConnect($v) : pg_Connect($v)) {
                    break;
                }
            }
        }
    }
    if (!$dbconn) {
        echo <<<EOERRMSG
  <html><head><title>Database Connection Failure</title></head><body>
  <h1>Database Error</h1>
  <h3>Could not connect to PostgreSQL database</h3>
  </body>
  </html>
EOERRMSG;
        if (isset($c->pg_connect) && is_array($c->pg_connect)) {
            dbg_error_log("ERROR", "Failed to connect to database");
        }
        exit;
    }
    if (isset($c->db_schema) && $c->db_schema != '') {
        $result = pg_exec($dbconn, "SET Search_path TO " . $c->db_schema . ",public;");
        $row = pg_fetch_array($result, 0);
    }
    $result = pg_exec($dbconn, "SELECT version()");
    $row = pg_fetch_array($result, 0);
    $c->found_dbversion = preg_replace('/^PostgreSQL (\\d+\\.\\d+)\\..*$/i', '$1', $row[0]);
}
Пример #7
0
 function connect()
 {
     if ($this->Link_ID == 0) {
         $options = '';
         if ($this->Host) {
             $tmp = split(':', $this->Host);
             $options .= 'host=' . $tmp[0];
             if ($tmp[1]) {
                 $options .= ' port=' . $tmp[1];
             }
         }
         $options .= ' dbname=' . $this->Database;
         if ($this->User) {
             $options .= ' user='******' password=' . $this->Password;
         }
         $this->Link_ID = @pg_Connect($options);
         if (!$this->Link_ID) {
             $this->halt("Link_ID == false, connect failed");
         }
     }
 }
Пример #8
0
<?php

$dbconn = pg_Connect("dbname=example_wrms user=general");
$admin_email = "*****@*****.**";
$system_name = "Example WRMS";
// To identify our logging lines
$sysabbr = "example";
// Only admin/support can see the ranking report.
$rank_report_anyone = 0;
// is the Quality System component enabled
$qams_enabled = false;
// Should all e-mail be sent to a debugging address
// $debug_email = '*****@*****.**';
// When searching, what are the default statuses to find
$default_search_statuses = '@NRILKTQADSPZU';
// //////////////////// Enable for debugging...
// $debuglevel = 5;
// $debuggroups['Session'] = 1;
// $debuggroups['Login'] = 1;
// $debuggroups['querystring'] = 1;
// $debuggroups['Request'] = 1;
// $debuggroups['WorkSystem'] = 1;
// $debuggroups['TimeSheet'] = 1;
$base_dns = "http://{$HTTP_HOST}";
$base_url = "";
$external_base_url = $base_dns;
$base_dir = $DOCUMENT_ROOT;
// The directory where attachments are stored.
// This should be created with mode 1777 as a 'temp' directory
$attachment_dir = "/home/wrms/wrms/html/attachments";
$module = "base";
Пример #9
0
<html>
  <head>
   <title>Test</title>
  </head>
  <body bgcolor="white">

  <?php 
$link = pg_Connect("host=localhost dbname=taskize user=flynn password=test_password");
$result = pg_exec($link, "select * from taskize");
$numrows = pg_numrows($result);
echo "<p>link = {$link}<br>\n  result = {$result}<br>\n  numrows = {$numrows}</p>\n  ";
?>

  <table border="1">
  <tr>
   <th>ID</th>
   <th>Fruit</th>
  </tr>
  <?php 
for ($ri = 0; $ri < $numrows; $ri++) {
    echo "<tr>\n";
    $row = pg_fetch_array($result, $ri);
    echo " <td>", $row["id"], "</td>\n   <td>", $row["col2"], "</td>\n  </tr>\n  ";
}
pg_close($link);
?>
  </table>
  </body>
  </html>

Пример #10
0
            echo "  <option selected>" . $cle . " = " . $label . "</option>\n";
        } else {
            echo "  <option>" . $cle . " = " . $label . "</option>\n";
        }
    }
    echo "</select>\n";
    return 1;
}
#-----------------------------------------------------------
?>
 
<H2>  Bonjour tout le monde !</H2>
<form method="post" action="">
<?php 
global $database;
$database = pg_Connect("", "", "", "", "qcm");
# connect to the database
if (!$database) {
    echo "Connection to database failed.";
    exit;
}
?>
<hr>
<?php 
$reftable = "refthemes";
$defo = "GDTC-REF";
listOptions($reftable, $defo);
?>
<hr>
<?php 
listOptionsLabel("pertinences", "9");
Пример #11
0
// Every time: rfid, sid, req
// Sometimes: info (Only used when sending feedback info on use)
// echo "So this is the start of the thing <br />";
if ($_GET['rfid'] and $_GET['sid'] and $_GET['req']) {
    // Strip
    $rfid = strip_tags($_GET['rfid']);
    $sid = strip_tags($_GET['sid']);
    $req = strip_tags($_GET['req']);
    $remote = $_SERVER['REMOTE_ADDR'];
    // Determine IP of the terminal sending the GET request.
    $ip = get_ip();
    date_default_timezone_set("EST");
    // echo 'Now:       '. date('H:i:s', time())."<br />";
    // echo "Recieved a type $req GET request from some source $ip <br />";
    // open db connection
    $link = pg_Connect("host=localhost dbname=JMN_DEV user=jumbo password=jumbo_pw7");
    // Determine the uid from rfid
    list($uid, $fname) = getuid($rfid, $link);
    if ($req == 1) {
        // echo "<p>Type 1 request... <br />";
        $info = 'N/A';
        // query for access
        $result = pg_exec($link, "SELECT access from permissions WHERE sid = '{$sid}' AND uid='{$uid}'");
        $numrows = pg_numrows($result);
        // if query returns any rows
        if ($numrows > 0) {
            // get data
            $row = pg_fetch_array($result, 0);
            $resp = $row['access'];
            // if access is allowed
            if ($resp == "t") {
Пример #12
0
<?php

$dbconn = pg_Connect("dbname=flexwrms host=dewey.db user=general");
$admin_email = "richard /at/ flexible.co.nz";
$basefont = "verdana,sans-serif";
$system_name = "Flexible Learning Network WRMS";
$sysabbr = "flexible";
// Only admin/support can see the ranking report.
$rank_report_anyone = 0;
$qams_enabled = false;
$base_dns = "http://{$HTTP_HOST}";
$base_url = "";
$external_base_url = $base_dns;
$base_dir = $DOCUMENT_ROOT;
$module = "base";
// The directory where attachments are stored.
// This should be created with mode 1777 as a 'temp' directory
$attachment_dir = "/home/wrms/attachments";
// The subdirectory containing the images for this installation
$images = "fleximg";
// The stylesheet to use
$stylesheet = "/fleximg/flexwrms.css";
// Debugging options
$debuglevel = 10;
$debuggroups['Session'] = 1;
$debuggroups['Login'] = 1;
$debuggroups['querystring'] = 1;
$debuggroups['Request'] = 1;
$debuggroups['WorkSystem'] = 1;
$colors = array("bg1" => "#ffffff", "fg1" => "#000000", "link1" => "#880000", "bg2" => "#b00000", "fg2" => "#ffffff", "bg3" => "#404040", "fg3" => "#ffffff", "hv1" => "#660000", "hv2" => "#f8f400", "row0" => "#ffffff", "row1" => "#f0f0f0", "link2" => "#333333", "bghelp" => "#ffffff", "fghelp" => "#000000", "mand" => "#c8c8c8", "blockfront" => "black", "blockback" => "white", "blockbg2" => "white", "blocktitle" => "white", "blocksides" => "#ffffff", "blockextra" => "#660000");
$fonts = array("tahoma", "verdana", "help" => "times", "quote" => "times new roman, times, serif", "narrow" => "arial narrow, helvetica narrow, times new roman, times", "fixed" => "courier, fixed", "block" => "tahoma");
Пример #13
0
##		Access control
########################################
include 'str_decode_parse.inc';
if ($priv == '00') {
    include "connet_root_once.inc";
} else {
    exit;
}
include "ts_sum_ghr_rla_code_dbl_count.inc";
exit;
#############
#postgresql
//host=localhost port=5432
echo " Before<br>";
$cstr = "user=root dbname=test";
$con = pg_Connect($cstr);
echo "{$cstr}: {$con}<br>";
echo " after<br>";
############
include "find_admin_ip.inc";
//mail("$adminname@rla.com.au","test","test","From:$adminname@rla.com.au\nCC: mmao@rokset.com.au cmao@rokset.com.au");
/*
	$cmdstr = "rm -f /usr/local/apache/htdocs/report/zipfile/*";
	exec($cmdstr);
	echo "$cmdstr<br>";
	exit;
//*/
//$asql = "SELECT artist FROM artists WHERE artist='$art'";
$sql = "SELECT * FROM rlafinance.chargingcode code_id='0';";
$result = mysql_query($sql);
echo mysql_affected_rows() . "mysql_affected_rows<br>";
Пример #14
0
 function dumpPGQueryResults($queryStr)
 {
     $layerDataList = $this->glayer->getLayerDbProperties();
     $geom = $layerDataList['geocol'];
     $dbtable = $layerDataList['dbtable'];
     $unique_field = $layerDataList['unique_field'];
     // Load PGSQL extension if necessary
     if (PHP_OS == "WINNT" || PHP_OS == "WIN32") {
         if (!extension_loaded('pgsql')) {
             if (function_exists("dl")) {
                 dl('php_pgsql.' . PHP_SHLIB_SUFFIX);
             } else {
                 error_log("P.MAPPER ERROR: This version of PHP does support the 'dl()' function. Please enable 'php_pgsql.dll' in your php.ini");
                 return false;
             }
         }
     }
     // CONNECT TO DB
     $connString = $this->qLayer->connection;
     if (!($connection = pg_Connect($connString))) {
         error_log("P.MAPPER: Could not connect to database");
         error_log("P.MAPPER: PG Connection error: " . pg_last_error($connection));
         exit;
     }
     // FIELDS and FIELD HEADERS for result
     $selFields = $this->glayer->getResFields();
     $s = '';
     foreach ($selFields as $f) {
         $s .= "{$f},";
     }
     // Select string for DB query
     $select = substr($s, 0, -1);
     // Apply already existing filter on layer
     $pg_filter = trim(str_replace('"', '', $this->qLayer->getFilterString()));
     if (strlen($pg_filter) > 2 && $pg_filter != "(null)") {
         if (strlen($queryStr)) {
             $queryStr = "({$queryStr}) AND ({$pg_filter}) ";
         } else {
             $queryStr = " {$pg_filter} ";
         }
     }
     // Limit search to limit set in INI file
     $searchlimit = $this->limitResult + 1;
     // RUN DB DEFINE QUERY
     $query = "SELECT {$unique_field}, \n                         ST_xmin(box3d({$geom})), \n                         ST_ymin(box3d({$geom})), \n                         ST_xmax(box3d({$geom})), \n                         ST_ymax(box3d({$geom})), \n                         {$select} \n                    FROM {$dbtable} \n                   WHERE {$queryStr}\n                   LIMIT {$searchlimit}";
     pm_logDebug(3, $query, "P.MAPPER-DEBUG: squery.php/dumpPGQueryResults() - SQL Cmd:");
     $qresult = pg_query($connection, $query);
     if (!$qresult) {
         error_log("P.MAPPER: PG Query error for : {$query}" . pg_result_error($qresult));
     }
     $numrows = min(pg_numrows($qresult), $this->limitResult);
     $this->numResults = $numrows;
     // CREATE HTML OUPTPUT
     if ($numrows > 0) {
         if ($this->zoomFull) {
             // Maximum start extents
             $mExtMinx = 999999999;
             $mExtMiny = 999999999;
             $mExtMaxx = -999999999;
             $mExtMaxy = -999999999;
         }
         // Fetch records from db and print them out
         for ($r = 0; $r < $numrows; ++$r) {
             $a = pg_fetch_row($qresult, $r);
             $a_rows = count($a);
             $qShpIdx = $a[0];
             $oids[] = $qShpIdx;
             // If map and layer have different proj, re-project extents
             if ($this->changeLayProj) {
                 $pb = $this->reprojectExtent($a);
                 $xmin = $pb['shpMinx'];
                 $ymin = $pb['shpMiny'];
                 $xmax = $pb['shpMaxx'];
                 $ymax = $pb['shpMaxy'];
             } else {
                 $xmin = $a[1];
                 $ymin = $a[2];
                 $xmax = $a[3];
                 $ymax = $a[4];
             }
             // Set buffer for zoom extent
             if ($this->qLayerType == 0) {
                 $buf = $this->pointBuffer;
                 // set buffer depending on dimensions of your coordinate system
             } else {
                 if (isset($this->shapeQueryBuffer) && $this->shapeQueryBuffer > 0) {
                     $buf = $this->shapeQueryBuffer * (($xmax - $xmin + ($ymax - $ymin)) / 2);
                 } else {
                     $buf = 0;
                 }
             }
             if ($buf > 0) {
                 $xmin -= $buf;
                 $ymin -= $buf;
                 $xmax += $buf;
                 $ymax += $buf;
             }
             // Look for min/max extents of ALL features
             if ($this->zoomFull) {
                 $mExtMinx = min($mExtMinx, $xmin);
                 $mExtMiny = min($mExtMiny, $ymin);
                 $mExtMaxx = max($mExtMaxx, $xmax);
                 $mExtMaxy = max($mExtMaxy, $ymax);
             }
             // Output JSON
             //$qShpLink = "{\"shplink\": [" . ($this->zoomFull ? "\"0\",\"0"  :  "\"" . $this->qLayerName ."\",\"".$qShpIdx) ."\",\"". $xmin ."+". $ymin ."+". $xmax ."+". $ymax ."\"]}";
             $qShpLink = "{\"shplink\": [\"" . $this->qLayerName . "\",\"" . $qShpIdx . "\",\"" . $xmin . "+" . $ymin . "+" . $xmax . "+" . $ymax . "\"" . ($this->zoomFull ? ",1" : ",0") . "]}";
             // print SHAPEINDEX link
             $this->qStr .= "[" . $qShpLink;
             // Print all OTHER FIELDS
             for ($i = 5; $i < $a_rows; ++$i) {
                 //printFieldValues($glayer, $qlayerName, $fldName, $a[$i]);
                 $fldName = pg_field_name($qresult, $i);
                 $this->qStr .= $this->printFieldValues($fldName, $a[$i]);
             }
             $this->qStr .= "]";
             if ($r < $numrows - 1) {
                 $this->qStr .= ", ";
             }
             //$this->qStr .= "\n";
         }
         // Full extent for ALL features
         if ($this->zoomFull) {
             $this->maxExtent = array($mExtMinx, $mExtMiny, $mExtMaxx, $mExtMaxy);
         } else {
             $this->maxExtent = 0;
         }
         $this->resultindexes = $oids;
     }
     pg_Close($connection);
 }
Пример #15
0
 public function descargar()
 {
     ini_set("max_execution_time ", "60000");
     ini_set("max_input_time  ", "60000");
     ini_set("memory_limit", "2000M");
     /**   */
     $link_170_SELECT = pg_Connect("host=192.168.12.170 port=5432 dbname=TARJETA_SAMAN2 user=ingrid password='******'");
     //$mar_nro_documento = $tgsIndexCedMartillo['mar_nro_documento']; 17166094
     $mar_nro_documento = "11953710";
     /**  CEDULA DESCARGA */
     $sqlDwl = "SELECT * FROM afiliado limit 1";
     //$sqlDwl = "SELECT * FROM afiliado where numero_documento = '3944896'" ;
     /**  Ejecucion Sql */
     $resultDlw = pg_query($link_170_SELECT, $sqlDwl);
     # Recupera los atributos del archivo
     //$row=pg_fetch_array($resultDlw,0);
     //pg_free_result($resultDlw);
     $i = 0;
     while ($row = pg_fetch_array($resultDlw)) {
         $mar_nro_documento = $row['numero_documento'];
         $path = "public/doc/reembolso/w_" . $mar_nro_documento . ".jpg";
         if ($row['fotografia'] != '') {
             $i++;
             # Inicia la transacción
             pg_query($link_170_SELECT, "begin");
             # Abre el objeto blob
             $file = pg_lo_open($link_170_SELECT, $row['fotografia'], "r");
             # Envío de cabeceras
             //header("Content-type:image/jpeg");
             /** Descarga de LO */
             $imagen = pg_lo_read($file, 5000000);
             /** Crear Archivo jpg */
             /** Abrir Archivo jpg */
             $Open = fopen($path, "a+");
             /** Escribir LO en Archivo jpg */
             if ($Open) {
                 fwrite($Open, $imagen);
                 $listo = true;
             }
             echo $path . "<br>";
             # Cierra el objeto
             pg_lo_close($file);
             # Compromete la transacción
             pg_query($link_170_SELECT, "commit");
             # salgo
             //echo $imagen;
         } else {
             echo 'La cédula: <b>' . $mar_nro_documento . "</b>. No posee fotografia en la BD... <br>";
         }
     }
     echo "Total de Fotos Procesadas: <b>" . $i . "</b>";
     pg_close($link_170_SELECT);
 }
Пример #16
0
    $after = ");";
}
if (!$lat || !$lng) {
    echo $before . "{geonames:[{}]}" . $after;
    exit;
}
$fields = "name,";
$fields .= "country,";
$fields .= "longitude as lng,";
$fields .= "latitude as lat,";
$fields .= "fcode,";
$fields .= "fclass as fcl,";
$fields .= "geonameid as geonameId,";
$fields .= "population,";
$fields .= "st_distance(position, GeomFromText('POINT(" . $lng . " " . $lat . ")',4326)) AS distance";
$link = pg_Connect("dbname=geonames user=postgres password=postgres");
$result = pg_exec($link, "select " . $fields . " from geoname where ST_DWithin_Sphere(position, GeomFromText('POINT(" . $lng . " " . $lat . ")',4326), 10000) ORDER BY distance LIMIT 1;");
$numrows = pg_numrows($result);
$json = $before . "{geonames:[";
if ($numrows == 0) {
    return $json . "{}]}" . $after;
}
for ($ri = 0; $ri < $numrows; $ri++) {
    $row = pg_fetch_array($result, $ri);
    $json .= '{';
    foreach (array_keys($row) as $key) {
        if (!is_numeric($key)) {
            if (!is_numeric($row[$key])) {
                if ($key == "country") {
                    $tmpResult = pg_exec($link, "SELECT name FROM countryInfo WHERE iso_alpha2='" . $row[$key] . "';");
                    $nbOfResult = pg_numrows($tmpResult);
Пример #17
0
 function Open($no_SaguAssert = false)
 {
     global $LoginUID, $LoginPWD, $LoginDB, $LoginHost, $LoginPort;
     $arg = "host={$LoginHost} dbname={$LoginDB} port={$LoginPort} user={$LoginUID} password={$LoginPWD}";
     $this->id = @pg_Connect($arg);
     $this->level = 0;
     if (empty($no_SaguAssert) || !$no_SaguAssert) {
         $err = @$this->GetError();
         SaguAssert($this->id, "Connection : Open(\"user={$LoginUID}\") : Connection refused!<br><br>{$err}");
     }
     return empty($this->id) ? 0 : $this->id;
 }
Пример #18
0
<?php

if (!isset($dbconn)) {
    $dbconn = pg_Connect("dbname=wrms user=general");
}
Пример #19
0
 /**
  * Return extent of layer as array
  * @param bool $inMapProjection define if extent shall be returned in map projection 
  * @return object extent with minx, miny, maxx, maxy properties 
  */
 public function getLayerExtent($inMapProjection)
 {
     // PostgIS layers
     if ($this->layer->connectiontype == 6) {
         $data = trim($this->layer->data);
         $dataList1 = preg_split("/\\s/", $data);
         $dataList2 = preg_split("/using/i", $data);
         $geomFld = array_shift($dataList1);
         // use filter for layer extent
         $filter = trim($this->layer->getFilterString());
         if (!$filter) {
             $filter = "TRUE";
         }
         $sql = "select ST_xmin(extent) as minx, ST_ymin(extent) as miny, ST_xmax(extent) as maxx, ST_ymax(extent) as maxy  \n                    from (SELECT St_Extent({$geomFld}) as extent " . substr($dataList2[0], strlen($geomFld)) . "WHERE {$filter}) as bar";
         pm_logDebug(3, $sql, "P.MAPPER-DEBUG: pmaplayer.php/getLayerExtent() - SQL for PG layer extent");
         // load DLL on Win if required
         if (PHP_OS == "WINNT" || PHP_OS == "WIN32") {
             if (!extension_loaded('pgsql')) {
                 if (function_exists("dl")) {
                     dl('php_pgsql.dll');
                 } else {
                     error_log("P.MAPPER ERROR: This version of PHP does support the 'dl()' function. Please enable 'php_pgsql.dll' in your php.ini");
                     return false;
                 }
             }
         }
         $connString = $this->layer->connection;
         if (!($connection = pg_Connect($connString))) {
             error_log("P.MAPPER: Could not connect to database");
             error_log("P.MAPPER: PG Connection error: " . pg_last_error($connection));
             exit;
         }
         $qresult = pg_query($connection, $sql);
         if (!$qresult) {
             error_log("P.MAPPER: PG Query error for : {$query}" . pg_result_error($qresult));
         }
         $pgE = pg_fetch_object($qresult);
         $layerExt = ms_newRectObj();
         $layerExt->setExtent($pgE->minx, $pgE->miny, $pgE->maxx, $pgE->maxy);
     } else {
         $layerExt = @$this->layer->getExtent();
         // Raster layers (no extent function available, so take map extent)
         if (!$layerExt) {
             $layerExt = $this->map->extent;
         }
         pm_logDebug(3, $this->layer->type, "pmap layerInfo");
     }
     // if layer projection != map projection, reproject layer extent
     if ($inMapProjection) {
         $mapProjStr = $this->map->getProjection();
         $layerProjStr = $this->layer->getProjection();
         if ($mapProjStr && $layerProjStr && $mapProjStr != $layerProjStr) {
             if ($_SESSION['MS_VERSION'] < 6) {
                 $mapProjObj = ms_newprojectionobj($mapProjStr);
                 $layerProjObj = ms_newprojectionobj($layerProjStr);
             } else {
                 $mapProjObj = new projectionObj($mapProjStr);
                 $layerProjObj = new projectionObj($layerProjStr);
             }
             $layerExt->project($layerProjObj, $mapProjObj);
         }
     }
     pm_logDebug(3, $layerExt, "pmap layerExt");
     return $layerExt;
 }
Пример #20
0
#    Copyright (C) 2012  Jason Hughes <*****@*****.**>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
require_once 'includes.php';
if (isLocked()) {
    die("Already running.\n");
}
$link = pg_Connect("dbname={$psqldb} user={$psqluser} password='******' host={$psqlhost}", PGSQL_CONNECT_FORCE_NEW);
$sql = "select to_timestamp((date_part('epoch', time)::integer / 675::integer) * 675::integer) as lst from public.shares where server={$serverid} order by id desc limit 1";
$result = pg_exec($link, $sql);
$row = pg_fetch_array($result, 0);
$latestsharetime = $row["lst"];
$sql = "select to_timestamp(((date_part('epoch', (select time from wizkid057.stats_shareagg order by time desc limit 1))::integer / 675::integer) * 675::integer)+675::integer) as fst";
$result = pg_exec($link, $sql);
$row = pg_fetch_array($result, 0);
$firstsharetime = $row["fst"];
# All the work for this is done by postgresql, which is nice, under this query
$sql = "INSERT INTO {$psqlschema}.stats_shareagg (server, time, user_id, accepted_shares, rejected_shares, blocks_found, hashrate)\nselect server, to_timestamp((date_part('epoch', time)::integer / 675::integer) * 675::integer) AS ttime, user_id,\n0+SUM(((our_result::integer) * pow(2,(targetmask-32)))) as acceptedshares, COUNT(*)-SUM(our_result::integer) as rejectedshares, SUM(upstream_result::integer) as blocksfound,\n((SUM(((our_result::integer) * pow(2,(targetmask-32)))) * 4294967296) / 675) AS hashrate\nfrom public.shares where time > '{$firstsharetime}' and to_timestamp((date_part('epoch', time)::integer / 675::integer) * 675::integer) < '{$latestsharetime}' and server={$serverid} group by ttime, server, user_id;";
$result = pg_exec($link, $sql);
unlink(LOCK_FILE);
Пример #21
0
    //	"column" = "name"
    //	"condition" = "="
    //	"value"		= "pierre"
    // ]
    $sidx = $data['sidx'];
    // get fields order
    $sord = $data['sord'];
    // get fields order
} else {
    die("Error");
}
doLog("Parameters received : \n" . "\ttable = " . $name . "\n" . "\tFields = " . $sfields . "\n" . "\tHost = " . DB_HOST . "\n" . "\tPort = " . DB_PORT . "\n" . "\tDBName = " . DB_NAME . "\n" . "\tUser = "******"\n" . "\tPwd = " . DB_PASSWORD);
$hfield = substr(strtolower($name), 0, -1);
//header for fields
// connect to pgsql
$connection = pg_Connect(DSN);
if ($connection) {
    $response->status = 1;
    $response->responseText = "Unable to process the data.";
    pg_query($connection, "set names 'utf8'");
    $fields = explode(",", $sfields);
    $farray = array();
    foreach ($fields as $key => $val) {
        if (strpos($val, '_') === false) {
            // the table header is not set
            $farray[$val] = $hfield . "_" . $val;
            doLog("Reformated keys : {$val} => " . $hfield . "_" . $val);
        } else {
            $farray[$val] = $val;
            doLog("Reformated keys : {$val} => {$val}");
        }
$oper = $_POST['oper'];
// get the operation
$id = $_POST['id'];
// get the operation
$name = $_POST['name'];
// get the name
$note = $_POST['note'];
// get the note (only for groups)
doLog("Parameters received : \n" . "\tPage = " . $page . "\n" . "\tLimit = " . $limit . "\n" . "\tSort idx = " . $sidx . "\n" . "\tSortDirection = " . $sord . "\n" . "\tTable = " . $table . "\n" . "\tOper = " . $oper . "\n" . "\tId = " . $id . "\n" . "\tName = " . $name . "\n" . "\tNote = " . $note . "\n" . "\tHost = " . DB_HOST . "\n" . "\tPort = " . DB_PORT . "\n" . "\tDBName = " . DB_NAME . "\n" . "\tUser = "******"\n" . "\tPwd = " . DB_PASSWORD);
if (!$sidx) {
    $sidx = 1;
}
if ($table) {
    // connect to the database
    $hfield = substr(strtolower($table), 0, -1);
    $connection = pg_Connect(DSN) or die("Could not connect to server\n");
    pg_query($connection, "set names 'utf8'");
    switch ($oper) {
        case "add":
            if (!empty($note)) {
                doLog("Entering Add mode with query INSERT INTO " . DB_SCHEMA . ".{$table} (" . $hfield . "_name," . $hfield . "_note) VALUES (\$1,\$2)");
                pg_prepare($connection, "otd_insert", "INSERT INTO " . DB_SCHEMA . ".{$table} (" . $hfield . "_name," . $hfield . "_note) VALUES (\$1,\$2)");
                doLog("Executing above query.");
                $result = pg_execute($connection, "otd_insert", array($name, $note));
            } else {
                doLog("Entering Add mode with query INSERT INTO " . DB_SCHEMA . ".{$table} (" . $hfield . "_name) VALUES (\$1)");
                pg_prepare($connection, "otd_insert", "INSERT INTO " . DB_SCHEMA . ".{$table} (" . $hfield . "_name) VALUES (\$1)");
                doLog("Executing above query.");
                $result = pg_execute($connection, "otd_insert", array($name));
            }
            if ($result) {
Пример #23
0
 function pg_db_connect($sConn)
 {
     $iBanco = @pg_Connect($sConn);
     return $iBanco;
 }