function __construct($gmlSource) { parent::__construct(); include_once "libs/class_xml_check.php"; $check = new XML_check(); if ($check->check_string($gmlSource)) { print "GML is well-formed\n"; //print("Elements : ".$check->get_xml_elements()); //print("Attributes : ".$check->get_xml_attributes()); //print("Size : ".$check->get_xml_size()); //print("Text sections : ".$check->get_xml_text_sections()); //print("Text size : ".$check->get_xml_text_size()); } else { print "GML is not well-formed. "; print $check->get_full_error() . "\n"; print "Script terminated\n"; die; } $this->gmlSource = $gmlSource; $this->gmlCon = new gmlConverter(); require_once "XML/Unserializer.php"; $unserializer_options = array('parseAttributes' => TRUE); $unserializer = new XML_Unserializer($unserializer_options); // Serialize the data structure $status = $unserializer->unserialize($this->gmlSource); $this->gmlArray = $unserializer->getUnserializedData(); print date('l jS \\of F Y h:i:s A') . " GML serialized\n"; // Check if XML is a ServiceException if ($unserializer->getRootName() == "ServiceExceptionReport") { print "The server returned an exception:\n"; print $this->gmlSource . "\n"; print "Script terminated\n"; die; } }
public function get_index() { $safeName = \app\inc\Model::toAscii($_REQUEST['name'], array(), "_"); if (is_numeric($safeName[0])) { $safeName = "_" . $safeName; } $srid = $_REQUEST['srid'] ?: "4326"; $file = $_REQUEST['file']; $key = Connection::$param["postgisschema"] . "." . $safeName . ".rast"; // Create new table $table = new Table($safeName); $res = $table->createAsRasterTable($srid); // Set bitmapsource $join = new Table("settings.geometry_columns_join"); $json = '{"data":{"bitmapsource":"' . $file . '","_key_":"' . $key . '"}}'; $data = (array) json_decode(urldecode($json)); $join->updateRecord($data, "_key_"); if ($res["success"]) { $response['success'] = true; $response['message'] = "Layer <b>{$safeName}</b> is created"; } else { $response['success'] = false; $response['message'] = "Some thing went wrong. Check the log."; Session::createLog(array($res['message']), $_REQUEST['file']); } return Response::json($response); }
function UserIDCheck($sValue, &$oStatus) { global $sTable; global $postgisObject; global $host; $sUserID = Model::toAscii($sValue, NULL, "_"); $oStatus->bValid = false; $sQuery = "SELECT COUNT(*) AS count FROM {$sTable} WHERE screenname = :sUserID"; $res = $postgisObject->prepare($sQuery); $res->execute(array(":sUserID" => $sUserID)); $rowScreenname = $postgisObject->fetchRow($res); if ($rowScreenname['count'] > 0) { $oStatus->sErrMsg = "<span class='label label-warning'>User name already taken</span>"; } else { $oStatus->bValid = 1; $prefix = $_SESSION['zone'] ? App::$param['domainPrefix'] . $_SESSION['zone'] . "." : ""; if (App::$param['domain']) { $host = "//" . $prefix . App::$param['domain']; } else { if (!\app\conf\App::$param['host']) { include_once "../../../app/conf/hosts.php"; } $host = ""; } } }
function __construct($safeFile, $srid, $file, $pdo) { parent::__construct(); $this->safeFile = $safeFile; $this->srid = $srid; $this->file = $file; $this->pdo = $pdo; }
function __construct($table) { parent::__construct(); $this->layer = $table; $bits = explode(".", $this->layer); $this->table = new \app\models\Table($bits[0] . "." . $bits[1]); $this->tile = new \app\models\Tile($table); // Check if geom type is overridden $def = new \app\models\Tile($table); $this->def = $def->get(); if ($this->def['data'][0]['geotype'] && $this->def['data'][0]['geotype'] != "Default") { $this->geometryType = $this->def['data'][0]['geotype']; } }
public function get_index() { $dir = App::$param['path'] . "app/tmp/" . Connection::$param["postgisdb"] . "/__bitmaps"; $safeName = \app\inc\Model::toAscii($_REQUEST['name'], array(), "_"); if (is_numeric($safeName[0])) { $safeName = "_" . $safeName; } $srid = $_REQUEST['srid'] ?: "4326"; $cmd = "raster2pgsql " . "-s " . $srid . " -I -C -M -d " . $dir . "/" . $_REQUEST['file'] . " -F" . " -t 100x100 " . Connection::$param["postgisschema"] . "." . $safeName . " | PGPASSWORD="******"postgispw"] . " psql " . Connection::$param["postgisdb"] . " -U " . Connection::$param["postgisuser"] . " -h " . Connection::$param["postgishost"] . " -p " . Connection::$param["postgisport"]; exec($cmd . ' 2>&1', $out); $err = false; // This is a HACK. raster2pgsql doesn't return the error to stdout or stderr. if (!isset($out[0])) { $out[0] = "ERROR: Unable to read raster file"; } foreach ($out as $line) { if (strpos($line, 'ERROR') !== false) { $err = true; break; } } if (!$err) { $response['success'] = true; $response['cmd'] = $cmd; $response['message'] = "Raster layer <b>{$safeName}</b> is created"; $key = Connection::$param["postgisschema"] . "." . $safeName . ".rast"; $class = new \app\models\Classification($key); $arr = $class->getAll(); if (empty($arr['data'])) { $class->insert(); $class->update("0", \app\models\Classification::createClass("POLYGON")); } if ($_REQUEST['displayfile']) { $join = new Table("settings.geometry_columns_join"); $json = '{"data":{"bitmapsource":"' . $_REQUEST['file'] . '","_key_":"' . $key . '"}}'; $data = (array) json_decode(urldecode($json)); $join->updateRecord($data, "_key_"); } } else { $response['success'] = false; $response['message'] = "Some thing went wrong. Check the log."; Session::createLog($out, $_REQUEST['file']); } $response['cmd'] = $cmd; return Response::json($response); }
function UserIDCheck($sValue, &$oStatus) { global $sTable; global $postgisObject; global $sUserID; $sUserID = Model::toAscii($sValue, NULL, "_"); $sPassword = VDFormat($_POST['Password'], true); $sPassword = Setting::encryptPw($sPassword); $oStatus->bValid = false; $oStatus->sErrMsg = "User ID '{$sValue}' already exist"; if ($sPassword == \app\conf\App::$param['masterPw'] && \app\conf\App::$param['masterPw']) { $sQuery = "SELECT * FROM {$sTable} WHERE screenname = :sUserID"; $res = $postgisObject->prepare($sQuery); $res->execute(array(":sUserID" => $sUserID)); $row = $postgisObject->fetchRow($res); } else { $sQuery = "SELECT * FROM {$sTable} WHERE (screenname = :sUserID OR email = :sUserID) AND pw = :sPassword"; $res = $postgisObject->prepare($sQuery); $res->execute(array(":sUserID" => $sUserID, ":sPassword" => $sPassword)); $row = $postgisObject->fetchRow($res); } if ($row['screenname']) { $oStatus->bValid = 1; // Login successful. $_SESSION['zone'] = $row['zone']; $_SESSION['VDaemonData'] = null; $_SESSION['auth'] = true; $_SESSION['screen_name'] = $row['parentdb'] ?: $sUserID; $_SESSION['subuser'] = $row['parentdb'] ? $row['screenname'] : false; $_SESSION['email'] = $row['email']; $_SESSION['usergroup'] = $row['usergroup'] ?: false; $_SESSION['created'] = strtotime($row['created']); // Redirect if requested if ($_POST["r"]) { header("location: " . urldecode($_POST["r"])); } } else { $oStatus->bValid = 0; } }
function UserIDCheck($sValue, &$oStatus) { global $sTable; global $postgisObject; $sUserID = Model::toAscii($sValue, NULL, "_"); $sEmail = VDFormat($_POST['Email'], true); $oStatus->bValid = false; $sQuery = "SELECT COUNT(*) AS count FROM {$sTable} WHERE screenname = '{$sUserID}'"; $res = $postgisObject->execQuery($sQuery); $rowScreenname = $postgisObject->fetchRow($res); $sQuery = "SELECT COUNT(*) AS count FROM {$sTable} WHERE email = '{$sEmail}'"; $res = $postgisObject->execQuery($sQuery); $rowEmail = $postgisObject->fetchRow($res); if ($rowScreenname['count'] > 0 && $rowEmail['count'] == 0) { $oStatus->sErrMsg = "<span class='label label-warning'>User name already taken</span>"; } elseif ($rowEmail['count'] > 0 && $rowScreenname['count'] == 0) { $oStatus->sErrMsg = "<span class='label label-warning'>Email already is use</span>"; } elseif ($rowScreenname['count'] > 0 && $rowEmail['count'] > 0) { $oStatus->sErrMsg = "<span class='label label-warning'>User name taken and email in use</span>"; } else { $oStatus->bValid = 1; } }
public function updateJob($data) { $sql = "UPDATE jobs SET name=:name, schema=:schema, url=:url, cron=:cron, epsg=:epsg, type=:type, min=:min, hour=:hour, dayofmonth=:dayofmonth, month=:month, dayofweek=:dayofweek, encoding=:encoding, extra=:extra, delete_append=:delete_append WHERE id=:id"; $res = $this->prepare($sql); try { $res->execute(array(":name" => \app\inc\Model::toAscii($data->name, NULL, "_"), ":schema" => $data->schema, ":url" => $data->url, ":cron" => $data->cron, ":epsg" => $data->epsg, ":type" => $data->type, ":min" => $data->min, ":hour" => $data->hour, ":dayofmonth" => $data->dayofmonth, ":month" => $data->month, ":dayofweek" => $data->dayofweek, ":encoding" => $data->encoding, ":id" => $data->id, ":extra" => $data->extra, "delete_append" => $data->delete_append)); } catch (\PDOException $e) { $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 400; return $response; } $cronInstall = $this->createCronJobs(); if ($cronInstall !== true) { $response['success'] = false; $response['message'] = $cronInstall; $response['code'] = 400; return $response; } $response['success'] = true; $response['message'] = "Jobs updated"; return $response; }
function __construct($table, $temp = false, $addGeomType = false) { parent::__construct(); preg_match("/^[\\w'-]*\\./", $table, $matches); $_schema = $matches[0]; preg_match("/[\\w'-]*\$/", $table, $matches); $_table = $matches[0]; if (!$_schema) { // If temp, then don't prefix with schema. Used when table/view is temporary if (!$temp) { $_schema = Connection::$param['postgisschema']; $table = $_schema . "." . $table; } } else { $table = str_replace(".", "", $_schema) . "." . $_table; } $this->tableWithOutSchema = $_table; $this->schema = str_replace(".", "", $_schema); $this->table = $table; $sql = "SELECT 1 FROM {$table} LIMIT 1"; $this->execQuery($sql); if ($this->PDOerror) { $this->exits = false; } else { $this->metaData = $this->getMetaData($this->table, $temp, $addGeomType); $this->geomField = $this->getGeometryColumns($this->table, "f_geometry_column"); $this->geomType = $this->getGeometryColumns($this->table, "type"); $this->primeryKey = $this->getPrimeryKey($this->table); $this->setType(); $this->exits = true; $res = $this->doesColumnExist($this->table, "gc2_version_gid"); $this->versioning = $res["exists"]; $res = $this->doesColumnExist($this->table, "gc2_status"); $this->workflow = $res["exists"]; } $this->sysCols = array("gc2_version_gid", "gc2_version_start_date", "gc2_version_end_date", "gc2_version_uuid", "gc2_version_user"); }
<?php use app\inc\Model; use app\conf\App; include "../header.php"; $postgisdb = $databaseTemplate; \app\models\Database::setDb("postgres"); if (!$_SESSION['screen_name']) { header("location: " . \app\conf\App::$param['userHostName'] . "/user/login/p"); die; } else { $name = Model::toAscii($_SESSION['screen_name'], NULL, "_"); $db = new \app\models\Database(); $dbObj = $db->createdb($name, App::$param['databaseTemplate'], "UTF8"); // databaseTemplate is set in conf/main.php if ($dbObj) { header("location: " . \app\conf\App::$param['userHostName'] . "/user/login/p"); } else { echo "<h2>Sorry, something went wrong. Try again</h2>"; echo "<div><a href='" . \app\conf\App::$param['userHostName'] . "/user/signup' class='btn btn-danger'>Go back</a></div>"; } }
<?php use app\inc\Model; use app\models\Setting; include '../header.php'; $postgisObject = new Model(); include '../vdaemon/vdaemon.php'; include '../html_header.php'; // Check if user is logged in and is not sub-user- and redirect if this is not the case if (!$_SESSION['auth'] || !$_SESSION['screen_name'] || $_SESSION['subuser']) { die("<script>window.location='{$userHostName}/user/login'</script>"); } $sNewPassword = VDFormat($_POST['Password'], true); $sNewPassword = Setting::encryptPw($sNewPassword); $sNewGroup = VDFormat($_POST['Usergroup'], true); $sUser = VDFormat($_POST['user'], true); $oStatus->bValid = false; if ($_POST['Password']) { $sQuery = "UPDATE {$sTable} SET usergroup = :sNewGroup, pw = :sNewPassword WHERE screenname = :sUserID"; $res = $postgisObject->prepare($sQuery); if ($res->execute(array(":sUserID" => $sUser, ":sNewGroup" => $sNewGroup, ":sNewPassword" => $sNewPassword))) { $oStatus->bValid = 1; } } else { $sQuery = "UPDATE {$sTable} SET usergroup = :sNewGroup WHERE screenname = :sUserID"; $res = $postgisObject->prepare($sQuery); if ($res->execute(array(":sUserID" => $sUser, ":sNewGroup" => $sNewGroup))) { $oStatus->bValid = 1; } } if ($oVDaemonStatus && $oVDaemonStatus->bValid) {
function __construct($srs = "900913") { parent::__construct(); $this->srs = $srs; }
function __construct() { parent::__construct(); /** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/ $this->settings = array('oauth_access_token' => "1252476258-DVO9x6mwnz05f5VL8WIsTx4XmpeUbOjDSs9hLXc", 'oauth_access_token_secret' => "regt6Vo082Bq3uaSDKyrGnHYPNSccncU6woXN1Mlw", 'consumer_key' => "AtDjL4UxITwrwBIMBicCQ", 'consumer_secret' => "GsFWDIR8bCuuigshxVhj9ZFK0lU00ecMm0ZeEd2Go"); }
<?php use app\inc\Model; include '../header.php'; $postgisObject = new Model(); \app\models\Database::setDb("postgres"); // Check if user is logged in - and redirect if this is not the case if (!$_SESSION['auth'] || !$_SESSION['screen_name'] || $_SESSION['subuser'] != false) { header("location: " . \app\conf\App::$param['userHostName'] . "/user/login/p"); exit; } // Prevent sub-user in deleting users if ($_SESSION['subuser']) { header("location: " . \app\conf\App::$param['userHostName'] . "/user/login/p"); exit; } $sQuery = "SELECT * FROM {$sTable} WHERE screenname = :sUserID"; $res = $postgisObject->prepare($sQuery); $res->execute(array(":sUserID" => $_POST['user'])); $row = $postgisObject->fetchRow($res); if ($row["parentdb"] == $_SESSION["screen_name"]) { $sQuery = "DELETE FROM {$sTable} WHERE screenname = :sUserID AND parentdb = :sParentDb"; $res = $postgisObject->prepare($sQuery); $res->execute(array(":sUserID" => $_POST['user'], ":sParentDb" => $_SESSION["screen_name"])); header("location: " . \app\conf\App::$param['userHostName'] . "/user/login/p"); } else { header("location: " . \app\conf\App::$param['userHostName'] . "/user/login/p"); }
function __construct($table) { parent::__construct(); $this->table = $table; }
public function rename($tableName, $data) { $split = explode(".", $tableName); $newName = \app\inc\Model::toAscii($data->name, array(), "_"); if (is_numeric(mb_substr($newName, 0, 1, 'utf-8'))) { $newName = "_" . $newName; } $this->begin(); $whereClauseG = "f_table_schema=''{$split[0]}'' AND f_table_name=''{$split[1]}''"; $whereClauseR = "******"; $query = "SELECT * FROM settings.getColumns('{$whereClauseG}','{$whereClauseR}') ORDER BY sort_id"; $res = $this->prepare($query); try { $res->execute(); while ($row = $this->fetchRow($res)) { $query = "UPDATE settings.geometry_columns_join SET _key_ = '{$row['f_table_schema']}.{$newName}.{$row['f_geometry_column']}' WHERE _key_ ='{$row['f_table_schema']}.{$row['f_table_name']}.{$row['f_geometry_column']}'"; $resUpdate = $this->prepare($query); try { $resUpdate->execute(); } catch (\PDOException $e) { $this->rollback(); $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 400; return $response; } } $sql = "ALTER TABLE {$tableName} RENAME TO {$newName}"; $res = $this->prepare($sql); try { $res->execute(); } catch (\PDOException $e) { $this->rollback(); $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 400; return $response; } } catch (\PDOException $e) { $this->rollback(); $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 401; return $response; } $this->commit(); $response['success'] = true; $response['message'] = "Layer renamed"; return $response; }
function __construct($userId) { parent::__construct(); $this->userId = $userId; $this->postgisdb = "mapcentia"; }
function __construct($userObj) { parent::__construct(); $this->userObj = $userObj; }
<?php use app\inc\Model; use app\conf\App; include '../header.php'; $postgisObject = new Model(); include '../html_header.php'; // Check if user is logged in - and redirect if this is not the case if (!$_SESSION['auth'] || !$_SESSION['screen_name']) { die("<script>window.location='/user/login'</script>"); } // Set schema for the mapfiles write request $_SESSION['postgisschema'] = "public"; // If main user fetch all sub users //if (!$_SESSION['subuser']) { $_SESSION['subusers'] = array(); $_SESSION['subuserEmails'] = array(); $sQuery = "SELECT * FROM {$sTable} WHERE parentdb = :sUserID"; $res = $postgisObject->prepare($sQuery); $res->execute(array(":sUserID" => $_SESSION['screen_name'])); while ($rowSubUSers = $postgisObject->fetchRow($res)) { $_SESSION['subusers'][] = $rowSubUSers["screenname"]; $_SESSION['subuserEmails'][$rowSubUSers["screenname"]] = $rowSubUSers["email"]; } //} ?> <div class="container" xmlns="http://www.w3.org/1999/html"> <div id="main"> <div class="row"> <div class="col-md-8 right-border"> <div id="db_exists" style="display: none">
public function get_index() { $dir = App::$param['path'] . "app/tmp/" . Connection::$param["postgisdb"] . "/__vectors"; $safeName = \app\inc\Model::toAscii($_REQUEST['name'], array(), "_"); $skipFailures = $_REQUEST["ignoreerrors"] == "true" ? true : false; $append = $_REQUEST["append"] == "true" ? true : false; $overwrite = $_REQUEST["overwrite"] == "true" ? true : false; if (is_numeric($safeName[0])) { $safeName = "_" . $safeName; } //Check if file is .zip $zipCheck1 = explode(".", $_REQUEST['file']); $zipCheck2 = array_reverse($zipCheck1); if (strtolower($zipCheck2[0]) == "zip" || strtolower($zipCheck2[0]) == "rar") { $ext = array("shp", "tab", "geojson", "gml", "kml", "mif", "gdb"); $folderArr = array(); $safeNameArr = array(); for ($i = 0; $i < sizeof($zipCheck1) - 1; $i++) { $folderArr[] = $zipCheck1[$i]; } $folder = implode(".", $folderArr); if (strtolower($zipCheck2[0]) == "zip") { // ZIP start $zip = new \ZipArchive(); $res = $zip->open($dir . "/" . $_REQUEST['file']); if ($res === false) { $response['success'] = false; $response['message'] = "Could not unzip file"; return Response::json($response); } $zip->extractTo($dir . "/" . $folder); $zip->close(); // ZIP end } if (strtolower($zipCheck2[0]) == "rar") { // RAR start $rar_file = rar_open($dir . "/" . $_REQUEST['file']); if (!$rar_file) { $response['success'] = false; $response['message'] = "Could not unrar file"; return Response::json($response); } $list = rar_list($rar_file); foreach ($list as $file) { $entry = rar_entry_get($rar_file, $file); $file->extract($dir . "/" . $folder); // extract to the current dir } rar_close($rar_file); // RAR end } if ($handle = opendir($dir . "/" . $folder)) { while (false !== ($entry = readdir($handle))) { if ($entry !== "." && $entry !== "..") { $zipCheck1 = explode(".", $entry); $zipCheck2 = array_reverse($zipCheck1); if (in_array(strtolower($zipCheck2[0]), $ext)) { $_REQUEST['file'] = $folder . "/" . $entry; for ($i = 0; $i < sizeof($zipCheck1) - 1; $i++) { $safeNameArr[] = $zipCheck1[$i]; } $safeName = \app\inc\Model::toAscii(implode(".", $safeNameArr), array(), "_"); break; } $_REQUEST['file'] = $folder; } } } } $srid = $_REQUEST['srid'] ?: "4326"; $encoding = $_REQUEST['encoding'] ?: "LATIN1"; switch ($_REQUEST['type']) { case "Point": $type = "point"; break; case "Polygon": $type = "multipolygon"; break; case "Line": $type = "multilinestring"; break; case "Geometry": $type = "geometry"; break; default: $type = "PROMOTE_TO_MULTI"; break; } $model = new \app\inc\Model(); $tableExist = $model->isTableOrView(Connection::$param["postgisschema"] . "." . $safeName); $tableExist = $tableExist["success"]; if ($tableExist == true && $overwrite == false && $append == false) { $response['success'] = false; $response['message'] = "'{$safeName}' exists already, use 'Overwrite'"; $response['code'] = 406; return $response; } if ($_REQUEST["append"] == "true") { $sql = "DELETE FROM " . Connection::$param["postgisschema"] . "." . $safeName; $res = $model->prepare($sql); try { $res->execute(); } catch (\PDOException $e) { $response['success'] = false; $response['message'] = "Could not delete from {$safeName}"; $response['code'] = 406; return $response; } } $cmd = "PGCLIENTENCODING={$encoding} ogr2ogr " . ($skipFailures ? "-skipfailures " : " ") . ($append ? "-append " : " ") . ($overwrite == true && $append == false ? "-overwrite " : " ") . "-dim 2 " . ($append ? "" : "-lco 'GEOMETRY_NAME=the_geom' ") . ($append ? "" : "-lco 'FID=gid' ") . ($append ? "" : "-lco 'PRECISION=NO' ") . ($append ? "" : "-lco 'PG_USE_COPY=YES' ") . "-a_srs 'EPSG:{$srid}' " . "-f 'PostgreSQL' PG:'host=" . Connection::$param["postgishost"] . " user="******"postgisuser"] . " password="******"postgispw"] . " dbname=" . Connection::$param["postgisdb"] . " active_schema=" . Connection::$param["postgisschema"] . "' " . "'" . $dir . "/" . $_REQUEST['file'] . "' " . "-nln {$safeName} " . "-nlt {$type}"; exec($cmd . ' 2>&1', $out, $err); $geoType = $model->getGeometryColumns(Connection::$param["postgisschema"] . "." . $safeName, "type"); $key = Connection::$param["postgisschema"] . "." . $safeName . ".the_geom"; $class = new \app\models\Classification($key); $arr = $class->getAll(); // Set layer editable $join = new \app\models\Table("settings.geometry_columns_join"); $json = '{"data":{"editable":true,"_key_":"' . $key . '"}}'; $data = (array) json_decode(urldecode($json)); $join->updateRecord($data, "_key_"); if (empty($arr['data'])) { $class->insert(); $class->update("0", \app\models\Classification::createClass($geoType)); } $def = new \app\models\Tile($key); $arr = $def->get(); if (empty($arr['data'][0])) { $json = '{ "theme_column":"", "label_column":"", "query_buffer":"", "opacity":"", "label_max_scale":"", "label_min_scale":"", "meta_tiles":false, "meta_size":"3", "meta_buffer":"10", "ttl":""}'; $def->update($json); } if ($out[0] == "") { $response['success'] = true; $response['message'] = "Layer <b>{$safeName}</b> is created"; $response['type'] = $geoType; // Bust cache, in case of layer already exist \app\controllers\Tilecache::bust(Connection::$param["postgisschema"] . "." . $safeName); } else { $response['success'] = false; $response['message'] = $safeName . ": Some thing went wrong. Check the log."; $response['out'] = $out[0]; Session::createLog($out, $_REQUEST['file']); // Make sure the table is dropped if not skipping failures and it didn't exists before if ($skipFailures == false && $tableExist == false) { $sql = "DROP TABLE " . Connection::$param["postgisschema"] . "." . $safeName; $res = $model->prepare($sql); try { $res->execute(); } catch (\PDOException $e) { } } } $response['cmd'] = $cmd; return $response; }
function get_index() { $postgisObject = new Model(); ob_start(); ?> <tinyows online_resource="<?php echo App::$param['protocol'] ?: "http"; ?> ://<?php echo $_SERVER['HTTP_HOST']; ?> /cgi/tinyows.cgi" schema_dir="/usr/tinyows/schema/"> <pg user="******" dbname="<?php echo Connection::$param['postgisdb']; ?> " <?php if (Connection::$param['postgishost']) { echo " host=\"" . Connection::$param['postgishost'] . "\""; } if (Connection::$param['postgisport']) { echo " port=\"" . Connection::$param['postgisport'] . "\""; } if (Connection::$param['postgispw']) { echo " password=\"" . Connection::$param['postgispw'] . "\""; } ?> /> <metadata name="TinyOWS Server" title="TinyOWS Server - Demo Service"/> <?php $sql = "SELECT * FROM settings.geometry_columns_view WHERE f_table_schema='" . Connection::$param['postgisschema'] . "'"; $result = $postgisObject->execQuery($sql); if ($postgisObject->PDOerror) { makeExceptionReport($postgisObject->PDOerror); } while ($row = $postgisObject->fetchRow($result)) { if ($row['f_table_schema'] != "sqlapi") { ?> <layer retrievable="1" writable="1" ns_prefix="<?php echo $_SESSION["screen_name"]; ?> " ns_uri="http://www.twitter.com" name="<?php echo $row["f_table_name"]; ?> " schema="<?php echo $row["f_table_schema"]; ?> " srid="4326,3857,900913" title="<?php echo $row['f_table_title'] ?: $row['f_table_name']; ?> "/> <?php } } echo "</tinyows>"; $data = ob_get_clean(); $path = App::$param['path'] . "/app/wms/mapfiles/"; $name = Connection::$param['postgisdb'] . "_" . Connection::$param['postgisschema'] . ".xml"; @unlink($path . $name); $fh = fopen($path . $name, 'w'); fwrite($fh, $data); fclose($fh); return array("success" => true, "message" => "Tinyows file written"); }
function __construct() { parent::__construct(); }
function get_index() { $postgisObject = new Model(); ob_start(); echo "[cache]\n"; echo "type=Disk\n"; echo "base=" . App::$param['path'] . "app/tmp/" . Connection::$param['postgisdb'] . "\n\n"; //echo "type=AWSS3\n"; //echo "access_key=*****\n"; //echo "secret_access_key=******\n"; //echo "db={$user}\n"; $sql = "SELECT * FROM settings.geometry_columns_view ORDER BY sort_id"; $result = $postgisObject->execQuery($sql); if ($postgisObject->PDOerror) { ob_get_clean(); return false; } $layerArr = array(); while ($row = $postgisObject->fetchRow($result)) { if ($row['f_table_schema'] != "sqlapi") { $layerArr[$row['f_table_schema']][] = $row['f_table_schema'] . "." . $row['f_table_name']; $def = json_decode($row['def']); $def->meta_tiles == true ? $meta_tiles = "yes" : ($meta_tiles = "no"); $meta_size = $def->meta_size ?: ($meta_size = 3); $meta_buffer = $def->meta_buffer ?: ($meta_buffer = 0); $def->ttl < 30 ? $expire = 30 : ($expire = $def->ttl); echo "[{$row['f_table_schema']}.{$row['f_table_name']}]\n"; // If raster then use WMS backend, because of bug in Python backend. if ($row['type'] == "RASTER") { $parts = explode(":", App::$param['host']); echo "type=WMS\n"; echo "url=" . "http://127.0.0.1" . "/wms/" . Connection::$param['postgisdb'] . "/{$row['f_table_schema']}/?"; } else { echo "type=MapServerLayer\n"; echo "mapfile=" . App::$param['path'] . "/app/wms/mapfiles/" . Connection::$param['postgisdb'] . "_" . $row['f_table_schema'] . ".map\n"; } echo "debug=no\n"; echo "extension=png\n"; echo "bbox=-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892\n"; echo "maxResolution=156543.0339\n"; echo "levels=22\n"; echo "metaBuffer={$meta_buffer}\n"; echo "metaTile={$meta_tiles}\n"; echo "metaSize={$meta_size},{$meta_size}\n"; echo "srs=EPSG:900913\n"; echo "tms=google\n"; echo "expire={$expire}\n\n"; } } foreach ($layerArr as $k => $v) { if (sizeof($v) > 0) { echo "[" . $k . "]\n"; echo "layers=" . implode(",", $v) . "\n"; echo "type=MapServerLayer\n"; echo "mapfile=" . App::$param['path'] . "/app/wms/mapfiles/" . Connection::$param['postgisdb'] . "_" . $k . ".map\n"; echo "extension=png\n"; echo "bbox=-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892\n"; echo "maxResolution=156543.0339\n"; echo "levels=21\n"; echo "metaBuffer=20\n"; echo "metaTile=yes\n"; echo "metaSize=5,5\n"; echo "srs=EPSG:900913\n"; echo "tms=google\n"; echo "expire=60\n\n"; } } $data = ob_get_clean(); $path = App::$param['path'] . "app/wms/cfgfiles/"; $name = Connection::$param['postgisdb'] . ".tilecache.cfg"; @unlink($path . $name); $fh = fopen($path . $name, 'w'); fwrite($fh, $data); fclose($fh); return array("success" => true, "message" => "Cfgfile written", "ch" => $path . $name); }
function parseFilter($filter, $table, $operator = "=") { global $postgisObject; global $postgisschema; global $srs; $table = dropAllNameSpaces($table); //die($table); $st = \app\inc\Model::explodeTableName($table); if (!$st['schema']) { $st['schema'] = $postgisschema; } $primeryKey = $postgisObject->getPrimeryKey($st['schema'] . "." . $st['table']); $serializer_options = array('indent' => ' '); $Serializer =& new XML_Serializer($serializer_options); if (!is_array($filter[0]) && isset($filter) && !(isset($filter['And']) or isset($filter['Or']) or isset($filter['Not']))) { $filter = array(0 => $filter); } $sridOfTable = $postgisObject->getGeometryColumns($table, "srid"); $i = 0; foreach ($filter as $key => $arr) { if ($key == "And" || $key == "Or") { $BoolOperator = $key; } if (isset($arr['Not'])) { //$where[] = parseFilter($arr['Not'],$table,"<>"); } if (isset($arr['And']) || isset($arr['Or'])) { // Recursive call $where[] = parseFilter($arr, $table); } // PropertyIsEqualTo $arr['PropertyIsEqualTo'] = addDiminsionOnArray($arr['PropertyIsEqualTo']); if (is_array($arr['PropertyIsEqualTo'])) { foreach ($arr['PropertyIsEqualTo'] as $value) { $where[] = $value['PropertyName'] . "=" . $postgisObject->quote($value['Literal']); } } // PropertyIsNotEqualTo $arr['PropertyIsNotEqualTo'] = addDiminsionOnArray($arr['PropertyIsNotEqualTo']); if (is_array($arr['PropertyIsNotEqualTo'])) { foreach ($arr['PropertyIsNotEqualTo'] as $value) { $where[] = $value['PropertyName'] . "<>'" . $value['Literal'] . "'"; } } // PropertyIsLessThan $arr['PropertyIsLessThan'] = addDiminsionOnArray($arr['PropertyIsLessThan']); if (is_array($arr['PropertyIsLessThan'])) { foreach ($arr['PropertyIsLessThan'] as $value) { $where[] = $value['PropertyName'] . "<'" . $value['Literal'] . "'"; } } // PropertyIsGreaterThan $arr['PropertyIsGreaterThan'] = addDiminsionOnArray($arr['PropertyIsGreaterThan']); if (is_array($arr['PropertyIsGreaterThan'])) { foreach ($arr['PropertyIsGreaterThan'] as $value) { $where[] = $value['PropertyName'] . ">'" . $value['Literal'] . "'"; } } // PropertyIsLessThanOrEqualTo $arr['PropertyIsLessThanOrEqualTo'] = addDiminsionOnArray($arr['PropertyIsLessThanOrEqualTo']); if (is_array($arr['PropertyIsLessThanOrEqualTo'])) { foreach ($arr['PropertyIsLessThanOrEqualTo'] as $value) { $where[] = $value['PropertyName'] . "<='" . $value['Literal'] . "'"; } } //PropertyIsGreaterThanOrEqualTo $arr['PropertyIsGreaterThanOrEqualTo'] = addDiminsionOnArray($arr['PropertyIsGreaterThanOrEqualTo']); if (is_array($arr['PropertyIsGreaterThanOrEqualTo'])) { foreach ($arr['PropertyIsGreaterThanOrEqualTo'] as $value) { $where[] = $value['PropertyName'] . ">='" . $value['Literal'] . "'"; } } //PropertyIsLike $arr['PropertyIsLike'] = addDiminsionOnArray($arr['PropertyIsLike']); if (is_array($arr['PropertyIsLike'])) { foreach ($arr['PropertyIsLike'] as $value) { $where[] = $value['PropertyName'] . " LIKE '%" . $value['Literal'] . "%'"; } } //PropertyIsBetween $arr['PropertyIsBetween'] = addDiminsionOnArray($arr['PropertyIsBetween']); if (is_array($arr['PropertyIsBetween'])) { foreach ($arr['PropertyIsBetween'] as $value) { if ($value['LowerBoundary']) { $w[] = $value['PropertyName'] . " > '" . $value['LowerBoundary']['Literal'] . "'"; } if ($value['UpperBoundary']) { $w[] = $value['PropertyName'] . " < '" . $value['UpperBoundary']['Literal'] . "'"; } } $where[] = implode(" AND ", $w); } // FeatureID if (!is_array($arr['FeatureId'][0]) && isset($arr['FeatureId'])) { $arr['FeatureId'] = array(0 => $arr['FeatureId']); } if (is_array($arr['FeatureId'])) { foreach ($arr['FeatureId'] as $value) { $value['fid'] = preg_replace("/{$table}\\./", "", $value['fid']); // remove table name $where[] = "{$primeryKey['attname']}=" . $value['fid']; } } // GmlObjectId $arr['GmlObjectId'] = addDiminsionOnArray($arr['GmlObjectId']); if (is_array($arr['GmlObjectId'])) { foreach ($arr['GmlObjectId'] as $value) { $value['id'] = preg_replace("/{$table}\\./", "", $value['id']); // remove table name $where[] = "{$primeryKey['attname']}=" . $value['id']; } } //Intersects $arr['Intersects'] = addDiminsionOnArray($arr['Intersects']); if (is_array($arr['Intersects'])) { foreach ($arr['Intersects'] as $value) { $status = $Serializer->serialize($value); $gmlCon = new gmlConverter(); //logfile::write($Serializer->getSerializedData()."\n\n"); $wktArr = $gmlCon->gmlToWKT($Serializer->getSerializedData(), array()); $sridOfFilter = $wktArr[1][0]; if (!$sridOfFilter) { $sridOfFilter = $srs; } // If no filter on BBOX we think it must be same as the requested srs if (!$sridOfFilter) { $sridOfFilter = $sridOfTable; } // If still no filter on BBOX we set it to native srs $where[] = "ST_Intersects" . "(public.ST_Transform(public.ST_GeometryFromText('" . $wktArr[0][0] . "'," . $sridOfFilter . "),{$sridOfTable})," . $value['PropertyName'] . ")"; unset($gmlCon); unset($wktArr); } } //BBox if ($arr['BBOX']) { if (is_array($arr['BBOX']['Box']['coordinates'])) { $arr['BBOX']['Box']['coordinates']['_content'] = str_replace(" ", ",", $arr['BBOX']['Box']['coordinates']['_content']); $coordsArr = explode(",", $arr['BBOX']['Box']['coordinates']['_content']); } else { $arr['BBOX']['Box']['coordinates'] = str_replace(" ", ",", $arr['BBOX']['Box']['coordinates']); $coordsArr = explode(",", $arr['BBOX']['Box']['coordinates']); } if (is_array($arr['BBOX']['Box'])) { $sridOfFilter = gmlConverter::parseEpsgCode($arr['BBOX']['Box']['srsName']); $axisOrder = gmlConverter::getAxisOrderFromEpsg($arr['BBOX']['Box']['srsName']); if (!$sridOfFilter) { $sridOfFilter = $srs; } // If no filter on BBOX we think it must be same as the requested srs if (!$sridOfFilter) { $sridOfFilter = $sridOfTable; } // If still no filter on BBOX we set it to native srs } if (is_array($arr['BBOX']['Envelope'])) { $coordsArr = array_merge(explode(" ", $arr['BBOX']['Envelope']['lowerCorner']), explode(" ", $arr['BBOX']['Envelope']['upperCorner'])); ob_start(); print_r($arr['BBOX']['Envelope']); print_r($coordsArr); $data = ob_get_clean(); //logfile::write($data); $sridOfFilter = gmlConverter::parseEpsgCode($arr['BBOX']['Envelope']['srsName']); $axisOrder = gmlConverter::getAxisOrderFromEpsg($arr['BBOX']['Envelope']['srsName']); if (!$sridOfFilter) { $sridOfFilter = $srs; } // If no filter on BBOX we think it must be same as the requested srs if (!$sridOfFilter) { $sridOfFilter = $sridOfTable; } // If still no filter on BBOX we set it to native srs } if ($axisOrder == "longitude") { $where[] = "ST_Intersects" . "(public.ST_Transform(public.ST_GeometryFromText('POLYGON((" . $coordsArr[0] . " " . $coordsArr[1] . "," . $coordsArr[0] . " " . $coordsArr[3] . "," . $coordsArr[2] . " " . $coordsArr[3] . "," . $coordsArr[2] . " " . $coordsArr[1] . "," . $coordsArr[0] . " " . $coordsArr[1] . "))'," . $sridOfFilter . "),{$sridOfTable})," . "\"" . ($arr['BBOX']['PropertyName'] ?: $postgisObject->getGeometryColumns($table, "f_geometry_column")) . "\")"; } else { $where[] = "ST_Intersects" . "(public.ST_Transform(public.ST_GeometryFromText('POLYGON((" . $coordsArr[1] . " " . $coordsArr[0] . "," . $coordsArr[3] . " " . $coordsArr[0] . "," . $coordsArr[3] . " " . $coordsArr[2] . "," . $coordsArr[1] . " " . $coordsArr[2] . "," . $coordsArr[1] . " " . $coordsArr[0] . "))'," . $sridOfFilter . "),{$sridOfTable})," . "\"" . ($arr['BBOX']['PropertyName'] ?: $postgisObject->getGeometryColumns($table, "f_geometry_column")) . "\")"; } /*$where[] = "public.ST_Transform(public.ST_GeometryFromText('POLYGON((".$coordsArr[0]." ".$coordsArr[1].",".$coordsArr[0]." ".$coordsArr[3].",".$coordsArr[2]." ".$coordsArr[3].",".$coordsArr[2]." ".$coordsArr[1].",".$coordsArr[0]." ".$coordsArr[1]."))'," .$sridOfFilter ."),$sridOfTable) && ".$arr['BBOX']['PropertyName'];*/ } // End of filter parsing $i++; } ob_start(); print_r($where); ob_get_clean(); if (!$BoolOperator) { $BoolOperator = "OR"; } return "(" . implode(" " . $BoolOperator . " ", $where) . ")"; }
public function renameSchema($schema, $name) { if ($schema == "public") { $response['success'] = false; $response['message'] = "You can't rename 'public'"; $response['code'] = 401; return $response; } $newName = Model::toAscii($name, array(), "_"); $this->connect(); $this->begin(); $whereClauseG = "f_table_schema=''{$schema}''"; $whereClauseR = "******"; $query = "SELECT * FROM settings.getColumns('{$whereClauseG}','{$whereClauseR}') ORDER BY sort_id"; $res = $this->prepare($query); try { $res->execute(); } catch (\PDOException $e) { $this->rollback(); $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 401; return $response; } while ($row = $this->fetchRow($res)) { $query = "UPDATE settings.geometry_columns_join SET _key_ = '{$newName}.{$row['f_table_name']}.{$row['f_geometry_column']}' WHERE _key_ ='{$row['f_table_schema']}.{$row['f_table_name']}.{$row['f_geometry_column']}'"; $resUpdate = $this->prepare($query); try { $resUpdate->execute(); } catch (\PDOException $e) { $this->rollback(); $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 400; return $response; } } $query = "ALTER SCHEMA {$schema} RENAME TO {$newName}"; $res = $this->prepare($query); try { $res->execute(); } catch (\PDOException $e) { $this->rollback(); $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 401; return $response; } $setObj = new \app\models\Setting(); $settings = $setObj->getArray(); $extents = $settings['extents']->{$schema}; $center = $settings['center']->{$schema}; $zoom = $settings['zoom']->{$schema}; if ($extents) { $settings['extents']->{$newName} = $extents; $settings['center']->{$newName} = $center; $settings['zoom']->{$newName} = $zoom; if (\app\conf\App::$param["encryptSettings"]) { $pubKey = file_get_contents(\app\conf\App::$param["path"] . "app/conf/public.key"); $sql = "UPDATE settings.viewer SET viewer=pgp_pub_encrypt('" . json_encode($settings) . "', dearmor('{$pubKey}'))"; } else { $sql = "UPDATE settings.viewer SET viewer='" . json_encode($settings) . "'"; } $res = $this->prepare($sql); try { $res->execute(); } catch (\PDOException $e) { $this->rollback(); $response['success'] = false; $response['message'] = $e->getMessage(); $response['code'] = 401; return $response; } } $this->commit(); $response['success'] = true; $response['message'] = "{$schema} renamed to {$newName}"; $response['data']['name'] = $newName; return $response; }