Exemplo n.º 1
0
function makeTileCacheFile($user, $extentLayer = NULL)
{
    //return;
    global $basePath;
    global $postgisdb;
    global $postgishost;
    global $postgispw;
    global $hostName;
    global $postgisschema;
    $postgisdb = $user;
    $table = $extentLayer;
    $postgisObject = new postgis();
    $srs = "900913";
    $geomField = $postgisObject->getGeometryColumns($table, "f_geometry_column");
    if ($extentLayer) {
        $sql = "SELECT xmin(EXTENT(transform(" . $geomField . ",{$srs}))) AS TXMin,xmax(EXTENT(transform(" . $geomField . ",{$srs}))) AS TXMax, ymin(EXTENT(transform(" . $geomField . ",{$srs}))) AS TYMin,ymax(EXTENT(transform(" . $geomField . ",{$srs}))) AS TYMax  FROM " . $table;
        $result = $postgisObject->execQuery($sql);
        //print_r($postgisObject->PDOerror);
        $row = $postgisObject->fetchRow($result);
    }
    ob_start();
    echo "[cache]\n";
    echo "type=Disk\n";
    echo "base={$basePath}/tmp/{$user}\n\n";
    //echo "type=AWSS3\n";
    //echo "access_key=AKIAIZUYE3I462NPVANQ\n";
    //echo "secret_access_key=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\n";
    $sql = "SELECT * FROM settings.geometry_columns_view";
    //echo $sql;
    $result = $postgisObject->execQuery($sql);
    if ($postgisObject->PDOerror) {
        makeExceptionReport($postgisObject->PDOerror);
    }
    while ($row = $postgisObject->fetchRow($result)) {
        echo "[{$row['f_table_schema']}.{$row['f_table_name']}]\n";
        echo "type=WMS\n";
        echo "url=http://127.0.0.1/cgi-bin/mapserv?map={$basePath}/wms/mapfiles/{$user}_{$row['f_table_schema']}.map\n";
        echo "extension=png\n";
        echo "bbox=-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892\n";
        echo "maxResolution=156543.0339\n";
        echo "metaTile=yes\n";
        echo "metaSize=5,5\n";
        echo "srs=EPSG:900913\n\n";
    }
    $data = ob_get_clean();
    @unlink("{$basePath}wms/cfgfiles/{$user}.tilecache.cfg");
    $newFile = "{$basePath}wms/cfgfiles/{$user}.tilecache.cfg";
    $fh = fopen($newFile, 'w');
    fwrite($fh, $data);
    fclose($fh);
}
Exemplo n.º 2
0
        $tables[] = $row['f_table_name'];
    }
}
foreach ($tables as $table) {
    $tableObj = new \app\models\table($postgisschema . "." . $table);
    $primeryKey = $tableObj->primeryKey;
    foreach ($tableObj->metaData as $key => $value) {
        if ($key != $primeryKey['attname']) {
            $fieldsArr[$table][] = $key;
        }
    }
    $fields = implode(",", $fieldsArr[$table]);
    $sql = "SELECT '{$fields}' FROM " . $postgisschema . "." . $table . " LIMIT 1";
    $result = $postgisObject->execQuery($sql);
    if ($postgisObject->PDOerror) {
        makeExceptionReport($postgisObject->PDOerror);
    }
    $atts["name"] = $table . "_Type";
    writeTag("open", "xsd", "complexType", $atts, True, True);
    $atts = null;
    $depth++;
    writeTag("open", "xsd", "complexContent", Null, True, True);
    $depth++;
    $atts["base"] = "gml:AbstractFeatureType";
    writeTag("open", "xsd", "extension", $atts, True, True);
    $depth++;
    writeTag("open", "xsd", "sequence", NULL, True, True);
    $atts = null;
    $depth++;
    $sql = "SELECT * FROM settings.getColumns('geometry_columns.f_table_name=''{$table}'' AND geometry_columns.f_table_schema=''{$postgisschema}''',\n                    'raster_columns.r_table_name=''{$table}'' AND raster_columns.r_table_schema=''{$postgisschema}''')";
    $fieldConfRow = $postgisObject->fetchRow($postgisObject->execQuery($sql));
Exemplo n.º 3
0
function doParse($arr)
{
    global $postgisObject;
    global $user;
    global $version;
    global $postgisschema;
    global $parts;
    $serializer_options = array('indent' => '  ');
    $Serializer =& new XML_Serializer($serializer_options);
    foreach ($arr as $key => $featureMember) {
        if ($key == "Insert") {
            if (!is_array($featureMember[0]) && isset($featureMember)) {
                $featureMember = array(0 => $featureMember);
            }
            foreach ($featureMember as $hey) {
                foreach ($hey as $typeName => $feature) {
                    if (is_array($feature)) {
                        // Skip handles
                        foreach ($feature as $field => $value) {
                            $fields[] = $field;
                            if (is_array($value)) {
                                // Must be geom if array
                                // We serialize the geometry back to XML for parsing
                                $status = $Serializer->serialize($value);
                                logfile::write("GML " . $Serializer->getSerializedData() . "\n\n");
                                $gmlCon = new gmlConverter();
                                $wktArr = $gmlCon->gmlToWKT($Serializer->getSerializedData(), array());
                                $values[] = array("{$field}" => $wktArr[0][0], "srid" => $wktArr[1][0]);
                                unset($gmlCon);
                                unset($wktArr);
                                //logfile::write($Serializer->getSerializedData()."\n\n");
                            } else {
                                $values[] = pg_escape_string($value);
                            }
                        }
                        $forSql['tables'][] = $typeName;
                        $forSql['fields'][] = $fields;
                        $forSql['values'][] = $values;
                        $fields = array();
                        $values = array();
                        $field = "";
                        $value = "";
                        // Start HTTP basic authentication
                        //if(!$_SESSION["oauth_token"]) {
                        $auth = $postgisObject->getGeometryColumns($postgisschema . "." . $typeName, "authentication");
                        if ($auth == "Write" or $auth == "Read/write") {
                            include '../inc/http_basic_authen.php';
                        }
                        //	}
                        // End HTTP basic authentication
                    }
                }
            }
        }
        if ($key == "Update") {
            if (!is_array($featureMember[0]) && isset($featureMember)) {
                $featureMember = array(0 => $featureMember);
            }
            $fid = 0;
            foreach ($featureMember as $hey) {
                $the_geom = $postgisObject->getGeometryColumns($postgisschema . "." . $hey['typeName'], "f_geometry_column");
                if (!is_array($hey['Property'][0]) && isset($hey['Property'])) {
                    $hey['Property'] = array(0 => $hey['Property']);
                }
                foreach ($hey['Property'] as $pair) {
                    $fields[$fid][] = $pair['Name'];
                    if ($pair['Name'] == $the_geom) {
                        // We serialize the geometry back to XML for parsing
                        $status = $Serializer->serialize($pair['Value']);
                        logfile::write($Serializer->getSerializedData() . "\n\n");
                        $gmlCon = new gmlConverter();
                        $wktArr = $gmlCon->gmlToWKT($Serializer->getSerializedData(), array());
                        $values[$fid][] = array("{$pair['Name']}" => current($wktArr[0]), "srid" => current($wktArr[1]));
                        unset($gmlCon);
                        unset($wktArr);
                    } else {
                        $values[$fid][] = $pair['Value'];
                    }
                }
                $forSql2['tables'][$fid] = $hey['typeName'];
                $forSql2['fields'] = $fields;
                $forSql2['values'] = $values;
                $forSql2['wheres'][$fid] = parseFilter($hey['Filter'], $hey['typeName']);
                $fid++;
                // Start HTTP basic authentication
                //if(!$_SESSION["oauth_token"]) {
                $auth = $postgisObject->getGeometryColumns($postgisschema . "." . $hey['typeName'], "authentication");
                if ($auth == "Write" or $auth == "Read/write") {
                    include '../inc/http_basic_authen.php';
                }
                //	}
                // End HTTP basic authentication
            }
            $pair = array();
            $values = array();
            $fields = array();
        }
        if ($key == "Delete") {
            if (!is_array($featureMember[0]) && isset($featureMember)) {
                $featureMember = array(0 => $featureMember);
            }
            foreach ($featureMember as $hey) {
                $forSql3['tables'][] = $hey['typeName'];
                $forSql3['wheres'][] = parseFilter($hey['Filter'], $hey['typeName']);
                // Start HTTP basic authentication
                //if(!$_SESSION["oauth_token"]) {
                $auth = $postgisObject->getGeometryColumns($postgisschema . "." . $hey['typeName'], "authentication");
                if ($auth == "Write" or $auth == "Read/write") {
                    include '../inc/http_basic_authen.php';
                }
                //	}
                // End HTTP basic authentication
            }
        }
    }
    echo '<wfs:WFS_TransactionResponse
        version="1.0.0"
	service="WFS"
	xmlns:wfs="http://www.opengis.net/wfs"
	xmlns:ogc="http://www.opengis.net/ogc">';
    // First we loop through inserts
    if (sizeof($forSql['tables']) > 0) {
        for ($i = 0; $i < sizeof($forSql['tables']); $i++) {
            if ($postgisObject->getGeometryColumns($postgisschema . "." . $forSql['tables'][$i], "editable")) {
                $the_geom = $postgisObject->getGeometryColumns($postgisschema . "." . $forSql['tables'][$i], "f_geometry_column");
                $primeryKey = $postgisObject->getPrimeryKey($postgisschema . "." . $forSql['tables'][$i]);
                //$metaData = $postgisObject -> getMetaData($forSql['tables'][$i]);
                $sql = "INSERT into {$postgisschema}.{$forSql['tables'][$i]} (";
                foreach ($forSql['fields'][$i] as $field) {
                    $fields[] = "\"" . $field . "\"";
                }
                $sql .= implode(",", $fields);
                unset($fields);
                $sql .= ") VALUES(";
                foreach ($forSql['values'][$i] as $key => $value) {
                    if (is_array($value)) {
                        fb($forSql['fields'][$i][$key]);
                        $values[] = "public.ST_Transform(public.ST_GeometryFromText('" . current($value) . "'," . next($value) . ")," . $postgisObject->getGeometryColumns($postgisschema . "." . $forSql['tables'][$i], "srid") . ")";
                    } elseif (!$value) {
                        $values[] = "NULL";
                    } else {
                        $values[] = $postgisObject->quote($value);
                    }
                }
                $sql .= implode(",", $values);
                unset($values);
                $sql .= ") RETURNING {$primeryKey['attname']} as gid,public.ST_AsText(public.ST_Centroid({$the_geom})) as {$the_geom};";
                // The query will return the new key
                $sqls['insert'][] = $sql;
            } else {
                $notEditable[$forSql['tables'][0]] = true;
            }
        }
    }
    // Second we loop through updates
    if (sizeof($forSql2['tables']) > 0) {
        for ($i = 0; $i < sizeof($forSql2['tables']); $i++) {
            //$metaData = $postgisObject -> getMetaData($forSql2['tables'][$i]);
            if ($postgisObject->getGeometryColumns($postgisschema . "." . $forSql2['tables'][$i], "editable")) {
                $the_geom = $postgisObject->getGeometryColumns($postgisschema . "." . $forSql2['tables'][$i], "f_geometry_column");
                $primeryKey = $postgisObject->getPrimeryKey($postgisschema . "." . $forSql2['tables'][$i]);
                $sql = "UPDATE {$postgisschema}.{$forSql2['tables'][$i]} SET ";
                foreach ($forSql2['fields'][$i] as $key => $field) {
                    if (is_array($forSql2['values'][$i][$key])) {
                        // is geometry
                        fb($forSql2['fields'][$i][$key]);
                        $value = "public.ST_Transform(public.ST_GeometryFromText('" . current($forSql2['values'][$i][$key]) . "'," . next($forSql2['values'][$i][$key]) . ")," . $postgisObject->getGeometryColumns($postgisschema . "." . $forSql2['tables'][$i], "srid") . ")";
                    } elseif (!$forSql2['values'][$i][$key]) {
                        $value = "NULL";
                    } else {
                        $value = $postgisObject->quote($forSql2['values'][$i][$key]);
                        // We need to escape the string
                    }
                    if (!is_array($forSql2['values'][$i][$key])) {
                        // is not geometry. Adding "" around field names
                        $pairs[] = "\"" . $field . "\"=" . $value;
                    } else {
                        $pairs[] = $field . "=" . $value;
                    }
                }
                $sql .= implode(",", $pairs);
                $sql .= " WHERE {$forSql2['wheres'][$i]} RETURNING {$primeryKey['attname']} as gid,public.ST_AsText(public.ST_Centroid({$the_geom})) as {$the_geom};";
                unset($pairs);
                $sqls['update'][] = $sql;
            } else {
                $notEditable[$forSql2['tables'][0]] = true;
            }
        }
    }
    // Third we loop through deletes
    if (sizeof($forSql3['tables']) > 0) {
        for ($i = 0; $i < sizeof($forSql3['tables']); $i++) {
            if ($postgisObject->getGeometryColumns($postgisschema . "." . $forSql3['tables'][$i], "editable")) {
                $sqls['delete'][] = "DELETE FROM {$postgisschema}.{$forSql3['tables'][$i]} WHERE {$forSql3['wheres'][$i]};\n\n";
            } else {
                $notEditable[$forSql3['tables'][0]] = true;
            }
        }
    }
    // We start sql BEGIN block
    $postgisObject->connect("PDO");
    $postgisObject->begin();
    // We fire the sqls
    if (isset($sqls)) {
        foreach ($sqls as $operation => $sql) {
            foreach ($sql as $singleSql) {
                if ($operation == "insert" || $operation == "update") {
                    $results[$operation][] = $postgisObject->execQuery($singleSql, "PDO", "select");
                    // Returning PDOStatement object
                } else {
                    $results[$operation] += $postgisObject->execQuery($singleSql, "PDO", "transaction");
                    // Returning interger
                }
                logfile::write("Sqls fired\n");
                logfile::write("{$singleSql}\n");
            }
        }
    }
    // If a layer is not editable, PDOerror is set.
    if (sizeof($notEditable) > 0) {
        $postgisObject->PDOerror[0] = "Layer not editable";
    }
    // WFS message
    echo '<wfs:Message>';
    echo '</wfs:Message>';
    // TransactionResult
    if (sizeof($postgisObject->PDOerror) == 0) {
        echo '<wfs:TransactionResult><wfs:Status><wfs:SUCCESS/></wfs:Status></wfs:TransactionResult>';
        $postgisObject->commit();
    } else {
        echo '<wfs:TransactionResult><wfs:Status><wfs:FAILURE/></wfs:Status></wfs:TransactionResult>';
        logfile::write("Error in\n");
        foreach ($postgisObject->PDOerror as $str) {
            logfile::write("{$str}\n");
        }
        logfile::write("ROLLBACK\n");
        $postgisObject->rollback();
        $results['insert'] = NULL;
        // Was object
        $results['update'] = NULL;
        // Was object
        $results['delete'] = 0;
        makeExceptionReport($postgisObject->PDOerror);
        // This output a exception and kills the script
    }
    // InsertResult
    if (sizeof($results['insert']) > 0) {
        reset($forSql['tables']);
        echo '<wfs:InsertResults handle="mygeocloud-WFS-default-handle">';
        foreach ($results['insert'] as $res) {
            echo '<ogc:FeatureId fid="';
            echo current($forSql['tables']) . ".";
            $row = $postgisObject->fetchRow($res);
            echo $row['gid'];
            echo '"/>';
            //$version->set(current($forSql['tables']),"insert",$row[$postgisObject->getGeometryColumns(current($forSql['tables']), "f_geometry_column")]);
            next($forSql['tables']);
        }
        echo '</wfs:InsertResults>';
    }
    // UpdateResult
    if (sizeof($results['update']) > 0) {
        reset($forSql2['tables']);
        echo '<wfs:UpdateResult>';
        foreach ($results['update'] as $res) {
            echo '<ogc:FeatureId fid="';
            echo current($forSql2['tables']) . ".";
            $row = $postgisObject->fetchRow($res);
            echo $row['gid'];
            echo '" />';
            //$version->set(current($forSql2['tables']),"update",$row[$postgisObject->getGeometryColumns(current($forSql['tables']), "f_geometry_column")]);
            next($forSql2['tables']);
        }
        echo '</wfs:UpdateResult>';
    }
    // TransactionSummary
    echo '<wfs:TransactionSummary>';
    if (isset($results)) {
        foreach ($results as $operation => $result) {
            if ($operation == "insert") {
                echo "<wfs:totalInserted>" . sizeof($result) . "</wfs:totalInserted>";
            }
            if ($operation == "update") {
                echo "<wfs:totalUpdated>" . sizeof($result) . "</wfs:totalUpdated>";
            }
            if ($operation == "delete") {
                echo "<wfs:totalDeleted>" . $result . "</wfs:totalDeleted>";
            }
        }
    }
    echo '</wfs:TransactionSummary>';
    echo '</wfs:WFS_TransactionResponse>';
    $postgisObject->free($result);
}
Exemplo n.º 4
0
function doParse($arr)
{
    global $postgisObject;
    global $user;
    global $postgisschema;
    global $layerObj;
    global $parentUser;
    global $transaction;
    global $db;
    $serializer_options = array('indent' => '  ');
    // We start sql BEGIN block
    $postgisObject->connect("PDO");
    $postgisObject->begin();
    $Serializer = new XML_Serializer($serializer_options);
    $workflowData = array();
    foreach ($arr as $key => $featureMember) {
        if ($key == "Insert") {
            if (!is_array($featureMember[0]) && isset($featureMember)) {
                $featureMember = array(0 => $featureMember);
            }
            foreach ($featureMember as $hey) {
                foreach ($hey as $typeName => $feature) {
                    $typeName = dropAllNameSpaces($typeName);
                    if (is_array($feature)) {
                        // Skip handles
                        // Remove ns from properties
                        foreach ($feature as $field => $value) {
                            $split = explode(":", $field);
                            if ($split[1]) {
                                $feature[dropAllNameSpaces($field)] = $value;
                                unset($feature[$field]);
                            }
                        }
                        // Check if table is versioned or has workflow. Add fields when clients doesn't send unaltered fields.
                        $tableObj = new table($postgisschema . "." . $typeName);
                        if (!array_key_exists("gc2_version_user", $feature) && $tableObj->versioning) {
                            $feature["gc2_version_user"] = null;
                        }
                        if (!array_key_exists("gc2_status", $feature) && $tableObj->workflow) {
                            $feature["gc2_status"] = null;
                        }
                        if (!array_key_exists("gc2_workflow", $feature) && $tableObj->workflow) {
                            $feature["gc2_workflow"] = null;
                        }
                        foreach ($feature as $field => $value) {
                            $fields[] = $field;
                            $roleObj = $layerObj->getRole($postgisschema, $typeName, $user);
                            $role = $roleObj["data"][$user];
                            if ($tableObj->workflow && ($role == "none" && $parentUser == false)) {
                                makeExceptionReport("You don't have a role in the workflow of '{$typeName}'");
                            }
                            if (is_array($value)) {
                                // Must be geom if array
                                // We serialize the geometry back to XML for parsing
                                $Serializer->serialize($value);
                                $gmlCon = new gmlConverter();
                                $wktArr = $gmlCon->gmlToWKT($Serializer->getSerializedData(), array());
                                $values[] = array("{$field}" => $wktArr[0][0], "srid" => $wktArr[1][0]);
                                unset($gmlCon);
                                unset($wktArr);
                                //Log::write($Serializer->getSerializedData()."\n\n");
                            } elseif ($field == "gc2_version_user") {
                                $values[] = $user;
                            } elseif ($field == "gc2_status") {
                                switch ($role) {
                                    case "author":
                                        $values[] = 1;
                                        break;
                                    case "reviewer":
                                        $values[] = 2;
                                        break;
                                    case "publisher":
                                        $values[] = 3;
                                        break;
                                    default:
                                        $values[] = 3;
                                        break;
                                }
                            } elseif ($field == "gc2_workflow") {
                                switch ($role) {
                                    case "author":
                                        $values[] = "hstore('author', '{$user}')";
                                        break;
                                    case "reviewer":
                                        $values[] = "hstore('reviewer', '{$user}')";
                                        break;
                                    case "publisher":
                                        $values[] = "hstore('publisher', '{$user}')";
                                        break;
                                    default:
                                        $values[] = "''";
                                        break;
                                }
                            } else {
                                $values[] = pg_escape_string($value);
                            }
                        }
                        $forSql['tables'][] = $typeName;
                        $forSql['fields'][] = $fields;
                        $forSql['values'][] = $values;
                        $fields = array();
                        $values = array();
                        //TODO check
                        //$field = "";
                        //$value = "";
                        // Start HTTP basic authentication
                        $auth = $postgisObject->getGeometryColumns($postgisschema . "." . $typeName, "authentication");
                        if ($auth == "Write" or $auth == "Read/write") {
                            $HTTP_FORM_VARS["TYPENAME"] = $typeName;
                            include 'inc/http_basic_authen.php';
                        }
                        // End HTTP basic authentication
                    }
                }
            }
        }
        if ($key == "Update") {
            if (!is_array($featureMember[0]) && isset($featureMember)) {
                $featureMember = array(0 => $featureMember);
            }
            $fid = 0;
            foreach ($featureMember as $hey) {
                $hey["typeName"] = dropAllNameSpaces($hey["typeName"]);
                if (!is_array($hey['Property'][0]) && isset($hey['Property'])) {
                    $hey['Property'] = array(0 => $hey['Property']);
                }
                // Check if table is versioned or has workflow. Add fields when clients doesn't send unaltered fields.
                $tableObj = new table($postgisschema . "." . $hey["typeName"]);
                foreach ($hey["Property"] as $v) {
                    if ($v["Name"] == "gc2_version_user") {
                        $gc2_version_user_flag = true;
                    }
                    if ($v["Name"] == "gc2_version_start_date") {
                        $gc2_version_start_date_flag = true;
                    }
                    if ($v["Name"] == "gc2_status") {
                        $gc2_status_flag = true;
                    }
                    if ($v["Name"] == "gc2_workflow") {
                        $gc2_workflow_flag = true;
                    }
                }
                if (!$gc2_version_user_flag && $tableObj->versioning) {
                    $hey["Property"][] = array("Name" => "gc2_version_user", "Value" => null);
                }
                if (!$gc2_version_start_date_flag && $tableObj->versioning) {
                    $hey["Property"][] = array("Name" => "gc2_version_start_date", "Value" => null);
                }
                if (!$gc2_status_flag && $tableObj->workflow) {
                    $hey["Property"][] = array("Name" => "gc2_status", "Value" => null);
                }
                if (!$gc2_workflow_flag && $tableObj->workflow) {
                    $hey["Property"][] = array("Name" => "gc2_workflow", "Value" => null);
                }
                //makeExceptionReport(print_r($hey, true));
                foreach ($hey['Property'] as $pair) {
                    $fields[$fid][] = $pair['Name'];
                    $roleObj = $layerObj->getRole($postgisschema, $hey['typeName'], $user);
                    $role = $roleObj["data"][$user];
                    if ($tableObj->workflow && ($role == "none" && $parentUser == false)) {
                        makeExceptionReport("You don't have a role in the workflow of '{$hey['typeName']}'");
                    }
                    if (is_array($pair['Value'])) {
                        // Must be geom if array
                        // We serialize the geometry back to XML for parsing
                        $Serializer->serialize($pair['Value']);
                        Log::write($Serializer->getSerializedData() . "\n\n");
                        $gmlCon = new gmlConverter();
                        $wktArr = $gmlCon->gmlToWKT($Serializer->getSerializedData(), array());
                        $values[$fid][] = array("{$pair['Name']}" => current($wktArr[0]), "srid" => current($wktArr[1]));
                        unset($gmlCon);
                        unset($wktArr);
                    } else {
                        $values[$fid][] = $pair['Value'];
                    }
                }
                $forSql2['tables'][$fid] = $hey['typeName'];
                $forSql2['fields'] = $fields;
                $forSql2['values'] = $values;
                $forSql2['wheres'][$fid] = parseFilter($hey['Filter'], $hey['typeName']);
                $fid++;
                // Start HTTP basic authentication
                $auth = $postgisObject->getGeometryColumns($postgisschema . "." . $hey['typeName'], "authentication");
                if ($auth == "Write" or $auth == "Read/write") {
                    $HTTP_FORM_VARS["TYPENAME"] = $hey['typeName'];
                    include 'inc/http_basic_authen.php';
                }
                // End HTTP basic authentication
            }
            $pair = array();
            $values = array();
            $fields = array();
        }
        if ($key == "Delete") {
            if (!is_array($featureMember[0]) && isset($featureMember)) {
                $featureMember = array(0 => $featureMember);
            }
            foreach ($featureMember as $hey) {
                $hey['typeName'] = dropAllNameSpaces($hey['typeName']);
                $forSql3['tables'][] = $hey['typeName'];
                $forSql3['wheres'][] = parseFilter($hey['Filter'], $hey['typeName']);
                $roleObj = $layerObj->getRole($postgisschema, $hey['typeName'], $user);
                $role = $roleObj["data"][$user];
                $tableObj = new table($postgisschema . "." . $hey["typeName"]);
                if ($tableObj->workflow && ($role == "none" && $parentUser == false)) {
                    makeExceptionReport("You don't have a role in the workflow of '{$hey['typeName']}'");
                }
                // Start HTTP basic authentication
                $auth = $postgisObject->getGeometryColumns($postgisschema . "." . $hey['typeName'], "authentication");
                if ($auth == "Write" or $auth == "Read/write") {
                    $HTTP_FORM_VARS["TYPENAME"] = $hey['typeName'];
                    include 'inc/http_basic_authen.php';
                }
                // End HTTP basic authentication
            }
        }
    }
    echo '<wfs:WFS_TransactionResponse version="1.0.0" xmlns:wfs="http://www.opengis.net/wfs"
  xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd">';
    // First we loop through inserts
    if (sizeof($forSql['tables']) > 0) {
        for ($i = 0; $i < sizeof($forSql['tables']); $i++) {
            if ($postgisObject->getGeometryColumns($postgisschema . "." . $forSql['tables'][$i], "editable")) {
                \app\controllers\Tilecache::bust($postgisschema . "." . $forSql['tables'][$i]);
                $gc2_workflow_flag = false;
                $roleObj = $layerObj->getRole($postgisschema, $forSql['tables'][$i], $user);
                $primeryKey = $postgisObject->getPrimeryKey($postgisschema . "." . $forSql['tables'][$i]);
                $sql = "INSERT INTO {$postgisschema}.{$forSql['tables'][$i]} (";
                foreach ($forSql['fields'][$i] as $key => $field) {
                    if ($field != "gc2_version_uuid" && $field != "gc2_version_start_date" && $field != "gc2_version_gid") {
                        $fields[] = "\"" . $field . "\"";
                    }
                }
                $sql .= implode(",", $fields);
                unset($fields);
                $sql .= ") VALUES(";
                foreach ($forSql['values'][$i] as $key => $value) {
                    if ($forSql['fields'][$i][$key] != "gc2_version_uuid" && $forSql['fields'][$i][$key] != "gc2_version_start_date" && $forSql['fields'][$i][$key] != "gc2_version_gid") {
                        if (is_array($value)) {
                            $values[] = "public.ST_Transform(public.ST_GeometryFromText('" . current($value) . "'," . next($value) . ")," . $postgisObject->getGeometryColumns($postgisschema . "." . $forSql['tables'][$i], "srid") . ")";
                        } elseif (!$value) {
                            $values[] = "NULL";
                        } elseif ($forSql['fields'][$i][$key] == "gc2_workflow") {
                            // Don't quote a hstore
                            $values[] = $value;
                            $gc2_workflow_flag = true;
                        } else {
                            $values[] = $postgisObject->quote($value);
                        }
                    }
                }
                $sql .= implode(",", $values);
                unset($values);
                $sql .= ") RETURNING {$primeryKey['attname']} as gid";
                // The query will return the new key
                if ($gc2_workflow_flag) {
                    $sql .= ",gc2_version_gid,gc2_status,gc2_workflow," . \app\inc\PgHStore::toPg($roleObj["data"]) . " as roles";
                    $gc2_workflow_flag = false;
                }
                $sqls['insert'][] = $sql;
            } else {
                $notEditable[$forSql['tables'][0]] = true;
            }
        }
    }
    // Second we loop through updates
    if (sizeof($forSql2['tables']) > 0) {
        for ($i = 0; $i < sizeof($forSql2['tables']); $i++) {
            if ($postgisObject->getGeometryColumns($postgisschema . "." . $forSql2['tables'][$i], "editable")) {
                \app\controllers\Tilecache::bust($postgisschema . "." . $forSql2['tables'][$i]);
                $primeryKey = $postgisObject->getPrimeryKey($postgisschema . "." . $forSql2['tables'][$i]);
                $tableObj = new table($postgisschema . "." . $forSql2['tables'][$i]);
                if ($tableObj->versioning) {
                    // Get original feature
                    $query = "SELECT * FROM {$postgisschema}.{$forSql2['tables'][$i]} WHERE {$forSql2['wheres'][$i]}";
                    $res = $postgisObject->execQuery($query);
                    $originalFeature = $postgisObject->fetchRow($res);
                    // Check if feature is ended
                    if ($originalFeature["gc2_version_end_date"]) {
                        makeExceptionReport("You can't change the history!");
                    }
                    // Clone original feature for ended version
                    $intoArr = array();
                    $selectArr = array();
                    foreach ($originalFeature as $k => $v) {
                        if ($k != $primeryKey['attname']) {
                            if ($k == "gc2_version_end_date") {
                                $intoArr[] = $k;
                                $selectArr[] = "now()";
                            } else {
                                $intoArr[] = $selectArr[] = $k;
                            }
                        }
                    }
                    $sql = "INSERT INTO {$postgisschema}.{$forSql2['tables'][$i]}(";
                    $sql .= implode(",", $intoArr);
                    $sql .= ")";
                    $sql .= " SELECT ";
                    $sql .= implode(",", $selectArr);
                    $sql .= " FROM {$postgisschema}.{$forSql2['tables'][$i]}";
                    $sql .= " WHERE {$forSql2['wheres'][$i]}";
                    //makeExceptionReport($sql);
                    $postgisObject->execQuery($sql);
                }
                $sql = "UPDATE {$postgisschema}.{$forSql2['tables'][$i]} SET ";
                $roleObj = $layerObj->getRole($postgisschema, $forSql2['tables'][$i], $user);
                $role = $roleObj["data"][$user];
                foreach ($forSql2['fields'][$i] as $key => $field) {
                    if (is_array($forSql2['values'][$i][$key])) {
                        // is geometry
                        $value = "public.ST_Transform(public.ST_GeometryFromText('" . current($forSql2['values'][$i][$key]) . "'," . next($forSql2['values'][$i][$key]) . ")," . $postgisObject->getGeometryColumns($postgisschema . "." . $forSql2['tables'][$i], "srid") . ")";
                    } elseif ($field == "gc2_version_user") {
                        $value = $postgisObject->quote($user);
                    } elseif ($field == "gc2_status") {
                        switch ($role) {
                            case "author":
                                if ($originalFeature[$field] > 1) {
                                    makeExceptionReport("This feature has been " . ($originalFeature[$field] == 2 ? "reviewed" : "published") . ", so an author can't edit it.");
                                }
                                $value = 1;
                                break;
                            case "reviewer":
                                if ($originalFeature[$field] > 2) {
                                    makeExceptionReport("This feature has been published, so a reviewer can't edit it.");
                                }
                                $value = 2;
                                break;
                            case "publisher":
                                $value = 3;
                                break;
                            default:
                                $value = $originalFeature[$field];
                                break;
                        }
                    } elseif ($field == "gc2_workflow") {
                        switch ($role) {
                            case "author":
                                $value = "'{$originalFeature[$field]}'::hstore || hstore('author', '{$user}')";
                                break;
                            case "reviewer":
                                $value = "'{$originalFeature[$field]}'::hstore || hstore('reviewer', '{$user}')";
                                break;
                            case "publisher":
                                $value = "'{$originalFeature[$field]}'::hstore || hstore('publisher', '{$user}')";
                                break;
                            default:
                                $value = "'{$originalFeature[$field]}'::hstore";
                                break;
                        }
                    } elseif ($field == "gc2_version_start_date") {
                        $value = "now()";
                    } elseif (!$forSql2['values'][$i][$key]) {
                        $value = "NULL";
                    } else {
                        $value = $postgisObject->quote($forSql2['values'][$i][$key]);
                        // We need to escape the string
                    }
                    $pairs[] = "\"" . $field . "\" =" . $value;
                }
                $sql .= implode(",", $pairs);
                $sql .= " WHERE {$forSql2['wheres'][$i]} RETURNING {$primeryKey['attname']} as gid";
                if ($tableObj->workflow) {
                    $sql .= ",gc2_version_gid,gc2_status,gc2_workflow," . \app\inc\PgHStore::toPg($roleObj["data"]) . " as roles";
                }
                //makeExceptionReport($sql);
                unset($pairs);
                $sqls['update'][] = $sql;
            } else {
                $notEditable[$forSql2['tables'][0]] = true;
            }
        }
    }
    // Third we loop through deletes
    if (sizeof($forSql3['tables']) > 0) {
        for ($i = 0; $i < sizeof($forSql3['tables']); $i++) {
            if ($postgisObject->getGeometryColumns($postgisschema . "." . $forSql3['tables'][$i], "editable")) {
                \app\controllers\Tilecache::bust($postgisschema . "." . $forSql3['tables'][$i]);
                $primeryKey = $postgisObject->getPrimeryKey($postgisschema . "." . $forSql3['tables'][$i]);
                $tableObj = new table($postgisschema . "." . $forSql3['tables'][$i]);
                if ($tableObj->versioning) {
                    // Check if its history
                    $res = $postgisObject->execQuery("SELECT gc2_version_end_date FROM {$postgisschema}.{$forSql3['tables'][$i]} WHERE {$forSql3['wheres'][$i]}", "PDO", "select");
                    $checkRow = $postgisObject->fetchRow($res);
                    if ($checkRow["gc2_version_end_date"]) {
                        makeExceptionReport("You can't change the history!");
                    }
                    // Update old record start
                    $sql = "UPDATE {$postgisschema}.{$forSql3['tables'][$i]} SET gc2_version_end_date = now(), gc2_version_user='******'";
                    if ($tableObj->workflow) {
                        // get original feature from feature
                        $query = "SELECT * FROM {$postgisschema}.{$forSql3['tables'][$i]} WHERE {$forSql3['wheres'][$i]}";
                        $resStatus = $postgisObject->execQuery($query);
                        $originalFeature = $postgisObject->fetchRow($resStatus);
                        $status = $originalFeature["gc2_status"];
                        // Get role
                        $roleObj = $layerObj->getRole($postgisschema, $forSql3['tables'][$i], $user);
                        $role = $roleObj["data"][$user];
                        switch ($role) {
                            case "author":
                                if ($status > 1) {
                                    makeExceptionReport("This feature has been " . ($status == 2 ? "reviewed" : "published") . ", so an author can't delete it.");
                                }
                                $value = 1;
                                break;
                            case "reviewer":
                                if ($status > 2) {
                                    makeExceptionReport("This feature has been published so a reviewer can't delete it.");
                                }
                                $value = 2;
                                break;
                            case "publisher":
                                $value = 3;
                                break;
                            default:
                                $value = $status;
                                break;
                        }
                        $sql .= ", gc2_status = {$value}";
                    }
                    // Update workflow
                    if ($tableObj->workflow) {
                        $workflow = $originalFeature["gc2_workflow"];
                        switch ($role) {
                            case "author":
                                $value = "'{$workflow}'::hstore || hstore('author', '{$user}')";
                                break;
                            case "reviewer":
                                $value = "'{$workflow}'::hstore || hstore('reviewer', '{$user}')";
                                break;
                            case "publisher":
                                $value = "'{$workflow}'::hstore || hstore('publisher', '{$user}')";
                                break;
                            default:
                                $value = "'{$workflow}'::hstore";
                                break;
                        }
                        $sql .= ", gc2_workflow = {$value}";
                    }
                    $sql .= " WHERE {$forSql3['wheres'][$i]} RETURNING {$primeryKey['attname']} as gid";
                    if ($tableObj->workflow) {
                        $sql .= ",gc2_version_gid,gc2_status,gc2_workflow," . \app\inc\PgHStore::toPg($roleObj["data"]) . " as roles";
                    }
                    $sqls['delete'][] = $sql;
                    // Update old record end
                } else {
                    $sqls['delete'][] = "DELETE FROM {$postgisschema}.{$forSql3['tables'][$i]} WHERE {$forSql3['wheres'][$i]} RETURNING {$primeryKey['attname']} as gid";
                }
            } else {
                $notEditable[$forSql3['tables'][0]] = true;
            }
        }
    }
    // We fire the sqls
    if (isset($sqls)) {
        foreach ($sqls as $operation => $sql) {
            foreach ($sql as $singleSql) {
                $results[$operation][] = $postgisObject->execQuery($singleSql, "PDO", "select");
                // Returning PDOStatement object
                Log::write("Sqls fired\n");
                Log::write("{$singleSql}\n");
            }
        }
    }
    // If a layer is not editable, PDOerror is set.
    if (sizeof($notEditable) > 0) {
        $postgisObject->PDOerror[0] = "Layer not editable";
    }
    // WFS message
    echo '<wfs:Message>';
    echo '</wfs:Message>';
    // TransactionResult
    if (sizeof($postgisObject->PDOerror) == 0) {
        echo '<wfs:TransactionResult handle="mygeocloud-WFS-default-handle"><wfs:Status><wfs:SUCCESS/></wfs:Status></wfs:TransactionResult>';
    } else {
        echo '<wfs:TransactionResult handle="mygeocloud-WFS-default-handle"><wfs:Status><wfs:FAILURE/></wfs:Status></wfs:TransactionResult>';
        Log::write("Error in\n");
        foreach ($postgisObject->PDOerror as $str) {
            Log::write("{$str}\n");
        }
        Log::write("ROLLBACK\n");
        $postgisObject->rollback();
        $results['insert'] = NULL;
        // Was object
        $results['update'] = NULL;
        // Was object
        $results['delete'] = 0;
        makeExceptionReport($postgisObject->PDOerror);
        // This output a exception and kills the script
    }
    // InsertResult
    if (sizeof($results['insert']) > 0) {
        if (isset($forSql['tables'])) {
            reset($forSql['tables']);
        }
        echo '<wfs:InsertResult>';
        foreach ($results['insert'] as $res) {
            echo '<ogc:FeatureId fid="';
            if (isset($forSql['tables'])) {
                echo current($forSql['tables']) . ".";
            }
            $row = $postgisObject->fetchRow($res);
            echo $row['gid'];
            echo '"/>';
            if (isset($row["gc2_workflow"])) {
                $workflowData[] = array("schema" => $postgisschema, "table" => current($forSql['tables']), "gid" => $row['gid'], "user" => $user, "status" => $row['gc2_status'], "workflow" => $row['gc2_workflow'], "roles" => $row['roles'], "version_gid" => $row['gc2_version_gid'], "operation" => "insert");
            }
            if (isset($forSql['tables'])) {
                next($forSql['tables']);
            }
        }
        echo '</wfs:InsertResult>';
    }
    // UpdateResult
    if (sizeof($results['update']) > 0) {
        if (isset($forSql2['tables'])) {
            reset($forSql2['tables']);
        }
        echo '<wfs:UpdateResult>';
        foreach ($results['update'] as $res) {
            echo '<ogc:FeatureId fid="';
            if (isset($forSql2['tables'])) {
                echo current($forSql2['tables']) . ".";
            }
            $row = $postgisObject->fetchRow($res);
            echo $row['gid'];
            echo '" />';
            if (isset($row["gc2_workflow"])) {
                $workflowData[] = array("schema" => $postgisschema, "table" => current($forSql2['tables']), "gid" => $row['gid'], "user" => $user, "status" => $row['gc2_status'], "workflow" => $row['gc2_workflow'], "roles" => $row['roles'], "version_gid" => $row['gc2_version_gid'], "operation" => "update");
            }
            if (isset($forSql2['tables'])) {
                next($forSql2['tables']);
            }
        }
        echo '</wfs:UpdateResult>';
    }
    // deleteResult
    if (sizeof($results['delete']) > 0) {
        if (isset($forSql3['tables'])) {
            reset($forSql3['tables']);
        }
        foreach ($results['delete'] as $res) {
            $row = $postgisObject->fetchRow($res);
            if (isset($row["gc2_workflow"])) {
                $workflowData[] = array("schema" => $postgisschema, "table" => current($forSql3['tables']), "gid" => $row['gid'], "user" => $user, "status" => $row['gc2_status'], "workflow" => $row['gc2_workflow'], "roles" => $row['roles'], "version_gid" => $row['gc2_version_gid'], "operation" => "delete");
            }
            if (isset($forSql2['tables'])) {
                next($forSql2['tables']);
            }
        }
    }
    // TransactionSummary
    echo '<wfs:TransactionSummary>';
    if (isset($results)) {
        foreach ($results as $operation => $result) {
            if ($operation == "insert") {
                echo "<wfs:totalInserted>" . sizeof($result) . "</wfs:totalInserted>";
            }
            if ($operation == "update") {
                echo "<wfs:totalUpdated>" . sizeof($result) . "</wfs:totalUpdated>";
            }
            if ($operation == "delete") {
                echo "<wfs:totalDeleted>" . sizeof($result) . "</wfs:totalDeleted>";
            }
        }
    }
    echo '</wfs:TransactionSummary>';
    echo '</wfs:WFS_TransactionResponse>';
    if (sizeof($workflowData) > 0) {
        $sqls = array();
        foreach ($workflowData as $w) {
            $sql = "INSERT INTO settings.workflow (f_schema_name,f_table_name,gid,status,gc2_user,roles,workflow,version_gid,operation)";
            $sql .= " VALUES('{$w["schema"]}','{$w["table"]}',{$w["gid"]},{$w["status"]},'{$w["user"]}','{$w["roles"]}'::hstore,'{$w["workflow"]}'::hstore,{$w["version_gid"]},'{$w["operation"]}')";
            $sqls[] = $sql;
        }
        // We fire the sqls
        foreach ($sqls as $sql) {
            $postgisObject->execQuery($sql, "PDO", "transaction");
        }
        if (sizeof($postgisObject->PDOerror) > 0) {
            makeExceptionReport($postgisObject->PDOerror);
            // This output a exception and kills the script
        }
    }
    //makeExceptionReport(print_r($sqls, true));
    $postgisObject->commit();
    $postgisObject->free($result);
}
Exemplo n.º 5
0
 function wfs_server()
 {
     // Manually tested this piece of code in order to check the requests.
     // Code based on a similar idea but build in Java
     header('Content-Type:text/xml; charset=UTF-8', TRUE);
     header('Connection:close', TRUE);
     //$userFromUri = "mhoegh"; // for testing
     logfile::write($userFromUri . "\n\n");
     // We connect to the users db
     $postgisdb = $userFromUri;
     $srs = $srsFromUri;
     $postgisschema = $schemaFromUri;
     $postgisObject = new postgis();
     //$user = new users($userFromUri);
     //$version = new version($user);
     $geometryColumnsObj = new GeometryColumns();
     function microtime_float()
     {
         list($utime, $time) = explode(" ", microtime());
         return (double) $utime + (double) $time;
     }
     $startTime = microtime_float();
     //ini_set("display_errors", "On");
     $thePath = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REDIRECT_URL'];
     //$thePath= "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
     $server = "http://" . $_SERVER['SERVER_NAME'];
     $BBox = null;
     //end added
     $currentTable = null;
     $currentTag = null;
     $gen = array();
     $gen[0] = "";
     $level = 0;
     $depth = 0;
     $tables = array();
     $fields = array();
     $wheres = array();
     $limits = array();
     logfile::write("\nRequest\n\n");
     logfile::write($HTTP_RAW_POST_DATA . "\n\n");
     $unserializer_options = array('parseAttributes' => TRUE, 'typeHints' => FALSE);
     $unserializer = new XML_Unserializer($unserializer_options);
     /*$HTTP_RAW_POST_DATA = '<?xml version="1.0" encoding="utf-8"?><wfs:Transaction service="WFS" version="1.0.0" xmlns="http://www.opengis.net/wfs" xmlns:mrhg="http://twitter/mrhg" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><wfs:Insert idgen="GenerateNew"><mrhg:hej><the_geom><gml:MultiPolygon srsName="urn:x-ogc:def:crs:EPSG:6.9:4326"><gml:polygonMember><gml:Polygon><gml:exterior><gml:LinearRing><gml:coordinates>5.0657329559,-41.1107215881 8.4824724197,-39.3435783386 4.3241734505,-34.6001853943 5.0657329559,-41.1107215881 </gml:coordinates></gml:LinearRing></gml:exterior></gml:Polygon></gml:polygonMember></gml:MultiPolygon></the_geom></mrhg:hej></wfs:Insert></wfs:Transaction>';*/
     /*$HTTP_RAW_POST_DATA = '<?xml version="1.0"?><DescribeFeatureType  version="1.1.0"  service="WFS"  xmlns="http://www.opengis.net/wfs"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">    <TypeName>california_coastline</TypeName></DescribeFeatureType>';
      */
     // Post method is used
     if ($HTTP_RAW_POST_DATA) {
         //$forUseInSpatialFilter = $HTTP_RAW_POST_DATA; // We store a unaltered version of the raw request
         $HTTP_RAW_POST_DATA = dropNameSpace($HTTP_RAW_POST_DATA);
         logfile::write($HTTP_RAW_POST_DATA . "\n\n");
         $status = $unserializer->unserialize($HTTP_RAW_POST_DATA);
         $arr = $unserializer->getUnserializedData();
         $request = $unserializer->getRootName();
         //print_r($arr);
         switch ($request) {
             case "GetFeature":
                 if (!is_array($arr['Query'][0])) {
                     $arr['Query'] = array(0 => $arr['Query']);
                 }
                 for ($i = 0; $i < sizeof($arr['Query']); $i++) {
                     if (!is_array($arr['Query'][$i]['PropertyName'])) {
                         $arr['Query'][$i]['PropertyName'] = array(0 => $arr['Query'][$i]['PropertyName']);
                     }
                 }
                 $HTTP_FORM_VARS["REQUEST"] = "GetFeature";
                 foreach ($arr['Query'] as $queries) {
                     $HTTP_FORM_VARS["TYPENAME"] .= $queries['typeName'] . ",";
                     if ($queries['PropertyName'][0]) {
                         foreach ($queries['PropertyName'] as $PropertyNames) {
                             // We check if typeName is prefix and add it if its not
                             if (strpos($PropertyNames, ".")) {
                                 $HTTP_FORM_VARS["PROPERTYNAME"] .= $PropertyNames . ",";
                             } else {
                                 $HTTP_FORM_VARS["PROPERTYNAME"] .= $queries['typeName'] . "." . $PropertyNames . ",";
                             }
                         }
                     }
                     if (is_array($queries['Filter']) && $arr['version'] == "1.0.0") {
                         @($checkXml = simplexml_load_string($queries['Filter']));
                         if ($checkXml === FALSE) {
                             makeExceptionReport("Filter is not valid");
                         }
                         $wheres[$queries['typeName']] = parseFilter($queries['Filter'], $queries['typeName']);
                     }
                 }
                 $HTTP_FORM_VARS["TYPENAME"] = dropLastChrs($HTTP_FORM_VARS["TYPENAME"], 1);
                 $HTTP_FORM_VARS["PROPERTYNAME"] = dropLastChrs($HTTP_FORM_VARS["PROPERTYNAME"], 1);
                 break;
             case "DescribeFeatureType":
                 $HTTP_FORM_VARS["REQUEST"] = "DescribeFeatureType";
                 $HTTP_FORM_VARS["TYPENAME"] = $arr['TypeName'];
                 //if (!$HTTP_FORM_VARS["TYPENAME"]) $HTTP_FORM_VARS["TYPENAME"] = $arr['typeName'];
                 break;
             case "GetCapabilities":
                 $HTTP_FORM_VARS["REQUEST"] = "GetCapabilities";
                 break;
             case "Transaction":
                 $HTTP_FORM_VARS["REQUEST"] = "Transaction";
                 if (isset($arr["Insert"])) {
                     $transactionType = "Insert";
                 }
                 if ($arr["Update"]) {
                     $transactionType = "update";
                 }
                 if ($arr["Delete"]) {
                     $transactionType = "Delete";
                 }
                 break;
         }
     } else {
         if (sizeof($_GET) > 0) {
             logfile::write($_SERVER['QUERY_STRING'] . "\n\n");
             $HTTP_FORM_VARS = $_GET;
             $HTTP_FORM_VARS = array_change_key_case($HTTP_FORM_VARS, CASE_UPPER);
             // Make keys case insensative
             $HTTP_FORM_VARS["TYPENAME"] = dropNameSpace($HTTP_FORM_VARS["TYPENAME"]);
             // We remove name space, so $where will get key without it.
             if ($HTTP_FORM_VARS['FILTER']) {
                 @($checkXml = simplexml_load_string($HTTP_FORM_VARS['FILTER']));
                 if ($checkXml === FALSE) {
                     makeExceptionReport("Filter is not valid");
                 }
                 //$forUseInSpatialFilter = $HTTP_FORM_VARS['FILTER'];
                 $status = $unserializer->unserialize(dropNameSpace($HTTP_FORM_VARS['FILTER']));
                 $arr = $unserializer->getUnserializedData();
                 $wheres[$HTTP_FORM_VARS['TYPENAME']] = parseFilter($arr, $HTTP_FORM_VARS['TYPENAME']);
             }
         } else {
             $HTTP_FORM_VARS = array("");
         }
     }
     //HTTP_FORM_VARS is set in script if POST is used
     $HTTP_FORM_VARS = array_change_key_case($HTTP_FORM_VARS, CASE_UPPER);
     // Make keys case
     $HTTP_FORM_VARS["TYPENAME"] = dropNameSpace($HTTP_FORM_VARS["TYPENAME"]);
     $tables = explode(",", $HTTP_FORM_VARS["TYPENAME"]);
     $properties = explode(",", dropNameSpace($HTTP_FORM_VARS["PROPERTYNAME"]));
     $featureids = explode(",", $HTTP_FORM_VARS["FEATUREID"]);
     $bbox = explode(",", $HTTP_FORM_VARS["BBOX"]);
     // Start HTTP basic authentication
     //if(!$_SESSION["oauth_token"]) {
     $auth = $postgisObject->getGeometryColumns($postgisschema . "." . $HTTP_FORM_VARS["TYPENAME"], "authentication");
     //}
     // End HTTP basic authentication
     print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
     ob_start();
     if (!empty($properties[0])) {
         foreach ($properties as $property) {
             $__u = explode(".", $property);
             // Is it "/" for get method?
             // We first check if typeName is namespace
             if ($__u[1]) {
                 foreach ($tables as $table) {
                     if ($table == $__u[0]) {
                         $fields[$table] .= $__u[1] . ",";
                     }
                 }
             } else {
                 foreach ($tables as $table) {
                     $fields[$table] .= $property . ",";
                 }
             }
         }
     }
     if (!empty($featureids[0])) {
         foreach ($featureids as $featureid) {
             $__u = explode(".", $featureid);
             foreach ($tables as $table) {
                 $primeryKey = $postgisObject->getPrimeryKey($postgisschema . "." . $table);
                 if ($table == $__u[0]) {
                     $wheresArr[$table][] = "{$primeryKey['attname']}={$__u[1]}";
                 }
                 $wheres[$table] = implode(" OR ", $wheresArr[$table]);
             }
         }
     }
     //get the request
     switch (strtoupper($HTTP_FORM_VARS["REQUEST"])) {
         case "GETCAPABILITIES":
             getCapabilities($postgisObject);
             break;
         case "GETFEATURE":
             if (!$gmlFeatureCollection) {
                 $gmlFeatureCollection = "wfs:FeatureCollection";
             }
             print "<" . $gmlFeatureCollection . "\n";
             print "xmlns=\"http://www.opengis.net/wfs\"\n";
             print "xmlns:wfs=\"http://www.opengis.net/wfs\"\n";
             print "xmlns:gml=\"http://www.opengis.net/gml\"\n";
             print "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
             print "xmlns:{$gmlNameSpace}=\"{$gmlNameSpaceUri}\"\n";
             if ($gmlSchemaLocation) {
                 print "xsi:schemaLocation=\"{$gmlSchemaLocation}\"";
             } else {
                 //print "xsi:schemaLocation=\"{$gmlNameSpaceUri} {$thePath}?REQUEST=DescribeFeatureType&amp;TYPENAME=".$HTTP_FORM_VARS["TYPENAME"]." http://www.opengis.net/wfs ".str_replace("server.php","",$thePath)."schemas/wfs/1.0.0/WFS-basic.xsd\"";
                 print "xsi:schemaLocation=\"{$gmlNameSpaceUri} {$thePath}?REQUEST=DescribeFeatureType&amp;TYPENAME=" . $HTTP_FORM_VARS["TYPENAME"] . " http://www.opengis.net/wfs http://wfs.plansystem.dk:80/geoserver/schemas/wfs/1.0.0/WFS-basic.xsd\"";
             }
             print ">\n";
             doQuery("Select");
             print "</" . $gmlFeatureCollection . ">";
             break;
         case "DESCRIBEFEATURETYPE":
             getXSD($postgisObject);
             break;
         case "TRANSACTION":
             doParse($arr);
             break;
         default:
             makeExceptionReport("Don't know that request");
             break;
     }
 }
    $settings_viewer = new \app\models\Setting();
    $response = $settings_viewer->get();
    $userGroup = $response["data"]["userGroups"]->{$subUser};
    if ($dbSplit[0] != $postgisschema) {
        $sql = "SELECT * FROM settings.geometry_columns_view WHERE _key_ LIKE :schema";
        $res = $postgisObject->prepare($sql);
        try {
            $res->execute(array("schema" => $postgisschema . "." . $HTTP_FORM_VARS["TYPENAME"] . ".%"));
        } catch (\PDOException $e) {
            $response['success'] = false;
            $response['message'] = $e->getMessage();
            $response['code'] = 401;
            makeExceptionReport($response);
        }
        while ($row = $postgisObject->fetchRow($res, "assoc")) {
            $privileges = (array) json_decode($row["privileges"]);
            switch ($transaction) {
                case false:
                    if ($privileges[$userGroup ?: $subUser] == false || $privileges[$userGroup ?: $subUser] == "none") {
                        makeExceptionReport(array("You don't have privileges to see this layer. Please contact the database owner, which can grant you privileges."));
                    }
                    break;
                case true:
                    if ($privileges[$userGroup ?: $subUser] == false || $privileges[$userGroup ?: $subUser] == "none" || $privileges[$userGroup ?: $subUser] == "read") {
                        makeExceptionReport(array("You don't have privileges to edit this layer. Please contact the database owner, which can grant you privileges."));
                    }
                    break;
            }
        }
    }
}
Exemplo n.º 7
0
    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");
    }
Exemplo n.º 8
0
function makeTileCacheFile($user, $extentLayer = NULL)
{
    //return;
    global $basePath;
    global $postgisdb;
    global $postgishost;
    global $postgispw;
    global $hostName;
    global $postgisschema;
    $postgisdb = $user;
    $table = $extentLayer;
    $postgisObject = new postgis();
    $srs = "900913";
    $geomField = $postgisObject->getGeometryColumns($table, "f_geometry_column");
    if ($extentLayer) {
        $sql = "SELECT xmin(EXTENT(transform(" . $geomField . ",{$srs}))) AS TXMin,xmax(EXTENT(transform(" . $geomField . ",{$srs}))) AS TXMax, ymin(EXTENT(transform(" . $geomField . ",{$srs}))) AS TYMin,ymax(EXTENT(transform(" . $geomField . ",{$srs}))) AS TYMax  FROM " . $table;
        $result = $postgisObject->execQuery($sql);
        //print_r($postgisObject->PDOerror);
        $row = $postgisObject->fetchRow($result);
    }
    ob_start();
    echo "[cache]\n";
    echo "type=Disk\n";
    echo "base={$basePath}/tmp/{$user}\n\n";
    //echo "type=AWSS3\n";
    //echo "access_key=AKIAIZUYE3I462NPVANQ\n";
    //echo "secret_access_key=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\n";
    //echo "db={$user}\n";
    $sql = "SELECT * FROM settings.geometry_columns_view";
    $result = $postgisObject->execQuery($sql);
    if ($postgisObject->PDOerror) {
        makeExceptionReport($postgisObject->PDOerror);
    }
    while ($row = $postgisObject->fetchRow($result)) {
        $layerArr[] = $row['f_table_schema'] . "." . $row['f_table_name'];
        $def = json_decode($row['def']);
        $def->meta_tiles == true ? $meta_tiles = "yes" : ($meta_tiles = "no");
        $def->ttl < 120 ? $expire = 120 : ($expire = $def->ttl);
        echo "[{$row['f_table_schema']}.{$row['f_table_name']}]\n";
        echo "type=WMS\n";
        echo "url={$hostName}/wms/{$user}/{$row['f_table_schema']}/?";
        echo "extension=png\n";
        echo "bbox=-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892\n";
        echo "maxResolution=156543.0339\n";
        echo "metaBuffer=20\n";
        echo "metaTile={$meta_tiles}\n";
        echo "metaSize=3,3\n";
        echo "srs=EPSG:900913\n";
        echo "expire={$expire}\n\n";
    }
    echo "[{$postgisschema}]\n";
    echo "layers=" . implode(",", $layerArr) . "\n";
    echo "type=WMS\n";
    echo "url={$hostName}/wms/{$user}/{$postgisschema}/?TRANSPARENT=FALSE&";
    echo "extension=png\n";
    echo "bbox=-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892\n";
    echo "maxResolution=156543.0339\n";
    echo "metaBuffer=20\n";
    echo "metaTile={$meta_tiles}\n";
    echo "metaSize=3,3\n";
    echo "srs=EPSG:900913\n";
    echo "expire={$expire}\n\n";
    $data = ob_get_clean();
    @unlink("{$basePath}wms/cfgfiles/{$user}.tilecache.cfg");
    $newFile = "{$basePath}wms/cfgfiles/{$user}.tilecache.cfg";
    $fh = fopen($newFile, 'w');
    fwrite($fh, $data);
    fclose($fh);
}