Exemplo n.º 1
0
 private function get($url)
 {
     $curl = curl_init($url);
     curl_setopt($curl, CURLOPT_URL, $url);
     curl_setopt($curl, CURLOPT_HEADER, 0);
     curl_setopt($curl, CURLOPT_HEADER, 0);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($curl, CURLOPT_VERBOSE, 1);
     Utility::debug('executing url via cUrl . . .', 1);
     $response = curl_exec($curl);
     Utility::debug('cUrl complete', 1);
     Utility::debug('GooglePlaces called: response=' . $response, 5);
     if ($error = curl_error($curl)) {
         Utility::debug('cUrl exception:' . $error, 3);
         throw new \Exception('CURL Error: ' . $error);
     }
     curl_close($curl);
     return $response;
 }
Exemplo n.º 2
0
 public static function executeQuery($query)
 {
     // connect to database
     Utility::debug('executing query ' . $query, 5);
     Utility::debug('server=' . self::$server . 'user='******'Error connecting to database: ' . mysql_error(), 1);
         Utility::errorRedirect('Error connecting to database: ' . mysql_error());
     } else {
         Utility::debug('Connected.', 5);
     }
     Utility::debug('Executing query . . .', 5);
     $data = mysqli_query($con, $query);
     if (!$data) {
         Utility::debug('Error executing query:' . mysql_error(), 1);
         Utility::errorRedirect('Error connecting to database: ' . mysql_error());
     } else {
         Utility::debug('Query executed successfully', 5);
         return $data;
     }
 }
Exemplo n.º 3
0
 public static function getClass($classname, $userID, $tenantID)
 {
     $coretypes = array('tenant', 'tenantSetting', 'tenantProperty', 'category', 'menuItem', 'page', 'tenantContent', 'entityList');
     if (!in_array($classname, $coretypes, false) && !in_array($classname, Application::$knowntypes, false)) {
         throw new Exception('Unknown class name: ' . $classname);
     }
     $classpath = Config::$root_path . '/classes/';
     if (in_array($classname, $coretypes, false)) {
         // core types will be in core path as configured in config.php
         $classpath = Config::$core_path . '/classes/';
     }
     // include appropriate dataEntity class & then instantiate it
     $classfile = $classpath . $classname . '.php';
     if (!file_exists($classfile)) {
         Utility::debug('Unable to instantiate class for ' . $classname . ' Classfile does not exist. Looking for ' . $classfile, 9);
         throw new Exception('Unable to instantiate new : ' . classname);
     }
     include_once $classfile;
     $classname = ucfirst($classname);
     // class names start with uppercase
     $class = new $classname($userID, $tenantID);
     return $class;
 }
Exemplo n.º 4
0
 public static function executeQueriesInTransaction($queries)
 {
     Log::debug('Database::executeQueriesInTransaction() called. Server=' . Config::$server . ', user='******'Error connecting to database: ' . mysql_error(), 9);
         Utility::errorRedirect('Error connecting to database: ' . mysql_error());
     }
     Log::debug('Starting transaction.', 5);
     if (!mysqli_autocommit($con, FALSE)) {
         Log::debug('Unable to set autocommit off: ' . mysqli_error($con), 9);
         mysqli_rollback($con);
         throw new Exception(mysqli_error($con));
     }
     Log::debug('Transaction started.', 1);
     $success = true;
     Log::debug('Executing ' . count($queries) . ' queries . . .', 1);
     foreach ($queries as $query) {
         Log::debug($query, 1);
         Log::debug('executing query [' . $query . ']', 5);
         $data = mysqli_query($con, $query);
         if (!$data) {
             $success = false;
             Log::debug('Error executing query:' . mysqli_error($con), 9);
             break;
         }
     }
     if (!$success) {
         Log::debug('Rolling back transaction.', 9);
         $err = mysqli_error($con);
         mysqli_rollback($con);
         mysqli_close($con);
         throw new Exception($err);
     } else {
         Log::debug('Committing transaction.', 5);
         mysqli_commit($con);
     }
     mysqli_close($con);
 }
 /**       
     Delete request
     @access public
     @throws Exception object
         @param string $serviceUri | String with the service uri
         @param array $parameters | Array with the parameters
         @param string $authorization | String with the authorization hash string   
     @return object
 */
 public function delete($serviceUri, $parameters = null, $authorization = null, $debug = false)
 {
     try {
         self::check_headers();
         $curl = curl_init($this->Options["host"] . $serviceUri);
         curl_setopt($curl, CURLOPT_HTTPHEADER, self::build_header(Utility::build_http_query($parameters), $authorization));
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
         curl_setopt($curl, CURLOPT_POSTFIELDS, Utility::build_http_query($parameters));
         $curl_response = curl_exec($curl);
         $http_status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
         curl_close($curl);
         if ($curl_response === false) {
             throw new Exception('Error occured during curl exec. Additioanl info: ' . var_export(curl_getinfo($curl)));
         }
         $json = json_decode($curl_response);
         if (isset($json) && is_object($json)) {
             return (object) Utility::array_to_object(["payload" => json_decode($curl_response), "http_status" => ["http_method" => "POST", "code" => $http_status_code, "canonical_name" => HttpHandler::get_http_code_info($http_status_code)]]);
         } else {
             if ($debug) {
                 $data = (object) Utility::array_to_object(["webservice_return" => trim(strip_tags($curl_response)), "http_status" => ["http_method" => "POST", "code" => $http_status_code, "canonical_name" => HttpHandler::get_http_code_info($http_status_code)]]);
                 Utility::debug($data);
             }
         }
     } catch (Exception $e) {
         throw $e;
     }
 }
Exemplo n.º 6
0
    if (strlen($categories) > 0) {
        // may be a little overkill, but want to ensure nothing but integers get passed into category id list
        $idlist = explode("|", $categories, 10);
        $separator = "";
        foreach ($idlist as $id) {
            if (is_numeric($id)) {
                $filter .= $separator . $id;
                $separator = ",";
            }
        }
    }
    Utility::debug('filter is: ' . $filter, 2);
    if ($listId > 0) {
        // a list was requested here. Different handling than regular entity set
        $query = 'call getLocationsByEntityListIdEx(' . $listId . ',' . $tenantID . ',' . $start . ',' . $return . ',' . $userID . ')';
    } elseif (strlen($filter > 0)) {
        $query = "call getLocationsByLatLngAndCategoryIdList(" . $tenantID . "," . $userID . "," . $center_lat . "," . $center_long . "," . $return . "," . $start . "," . Database::queryString($filter) . ")";
    } else {
        $query = "call getLocationsByLatLng(" . $tenantID . "," . $userID . "," . $center_lat . "," . $center_long . "," . $return . "," . $start . ")";
    }
    Utility::debug('Executing query: ' . $query, 5);
    $data = mysqli_query($con, $query) or die(mysqli_error());
    $rows = array();
    while ($r = mysqli_fetch_assoc($data)) {
        $rows[] = Utility::addDisplayElements($r);
    }
    $set = "{\"locations\":" . json_encode($rows) . "}";
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');
    echo $set;
}
Exemplo n.º 7
0
        header('Location: ' . $successURL);
    } catch (Exception $e) {
        if ($e->getCode() == 1) {
            // Password has expired.
            $expired = true;
            $_SESSION['expiredUserID'] = $user->userid;
            $errorMessage = "Your password has expired. Please create a new password.";
        } elseif ($e->getCode() == 2) {
            // Password has been reset.
            $reset = true;
            $_SESSION['expiredUserID'] = $user->userid;
            $errorMessage = "Your password has been reset. Please create a new password.";
        } else {
            $errorMessage = $e->getMessage();
        }
        Utility::debug('Login failed: ' . $errorMessage, 9);
    }
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Food Finder: Login</title>
        <?php 
include "partials/includes.php";
?>
        <script type="text/javascript" src="js/login.js"></script>  
    </head>
    <body>
Exemplo n.º 8
0
 private function validatePassword($password, $username, $userid)
 {
     // returns true if password if correct for specified user
     $userDetails = User::getUserDetails($username);
     if ($password != "reset") {
         $saltedPassword = Utility::saltAndHash($password, $userDetails["password"]);
     } else {
         $saltedPassword = '******';
     }
     $query = 'call validateUser(' . Database::queryString($username);
     $query .= ',' . Database::queryString($saltedPassword);
     $query .= ',' . Database::queryNumber($this->tenantid) . ');';
     $result = Database::executeQuery($query);
     if (!$result) {
         Utility::debug('User ' . $name . ' failed password validation.', 9);
         return false;
     } else {
         $matchedid = 0;
         while ($o = mysqli_fetch_object($result)) {
             $matchedid = $o->userid;
         }
         Utility::debug($matchedid . '- ' . $userid, 9);
         return $userid == $matchedid;
     }
 }
Exemplo n.º 9
0
    die;
}
// Allow certain file formats
if ($fileExtension == "kml") {
    Utility::debug("Processing kml file.", 7);
    $xml = simplexml_load_file($workingFile) or die("Error: Cannot parse file.");
    // use name of file being imported. This will let client query for progress
    $batchname = $_FILES["importFile"]["name"];
    $itemcount = count($xml->Document[0]->Placemark);
    $batchid = Utility::startBatch($batchname, $itemcount, $tenantID);
    // copy temp file to target folder
    copy($workingFile, $target_file);
    // will use curl to aynch execute the batch job
    $ch = curl_init();
    $url = 'http://' . $_SERVER['SERVER_NAME'] . "/foodfinder/service/processKML.php";
    $url .= "?source=" . urlencode($target_file);
    $url .= "&batchid=" . $batchid;
    $url .= "&tenantid=" . $tenantID;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    Utility::debug("Calling curl for url " . $url, 7);
    curl_exec($ch);
    curl_close($ch);
}
header('Content-Type: application/json');
$response = '{"count":' . json_encode($itemcount);
$response .= ', "batchid":' . $batchid . '}';
echo $response;
Utility::debug('File import batch initiated for ' . $workingFile . '. BatchID=' . $batchid, 5);
Exemplo n.º 10
0
            }
            $response = '{"id":' . json_encode($newID) . "}";
            Utility::debug('Endorsement added: ID=' . $newID, 5);
            header('Content-Type: application/json');
            echo $response;
        }
    } else {
        // this is an existing record: update
        // to do: add data validations
        Utility::debug('Updating endorsement', 5);
        echo 'Unable to uodate endorsement: method is not yet implemented';
        header(' ', true, 500);
    }
} elseif ($_SERVER['REQUEST_METHOD'] == "DELETE") {
    $json = file_get_contents('php://input');
    $data = json_decode($json);
    // to do: got to figure out how to secure this sucker
    $id = $data->{'id'};
    if (!$id > 0) {
        echo 'Unable to delete endorsement: an ID is required';
        header(' ', true, 400);
        die;
    }
    Utility::debug('Deleting endorsement id=' . $id, 5);
    $query = "call deleteLocationEndorsement(" . Database::queryNumber($id);
    $query .= "," . Database::queryNumber($tenantID);
    $query .= ')';
    $result = Database::executeQuery($query);
} else {
    echo "Unsupported HTTP method.";
}
Exemplo n.º 11
0
 public function updateEntity($id, $data)
 {
     // this does a very basic update based upon common pattern
     // override to add custom save functionality
     // if simple is true, child entities are ignored
     Utility::debug('dataentity.updateEntity called', 5);
     $queries = array();
     $this->validateData($data);
     //$queries = array();
     $newID = 0;
     $query = "call update" . $this->getName() . "(" . $id;
     $followOnQueries = array();
     $fieldarray = $this->getFields();
     $separator = ",";
     foreach ($fieldarray as $field) {
         if (!property_exists($data, $field[0])) {
             // assume all required fields already validated, so do what?
             $data->{$field[0]} = null;
         }
         switch ($field[1]) {
             case "string":
                 $query .= $separator . Database::queryString($data->{$field[0]});
                 break;
             case "json":
                 $query .= $separator . Database::queryJSON($data->{$field[0]});
                 break;
             case "boolean":
                 $query .= $separator . Database::queryBoolean($data->{$field[0]});
                 break;
             case "number":
             case "decimal":
             case "hidden":
                 $query .= $separator . Database::queryNumber($data->{$field[0]});
                 break;
             case "date":
                 $query .= $separator . Database::queryDate($data->{$field[0]});
                 break;
             case "picklist":
                 $query .= $separator . Database::queryString($data->{$field[0]});
                 break;
             case "linkedentity":
                 $query .= $separator . Database::queryNumber($data->{$field[0]});
                 break;
             case "linkedentities":
             case "childentities":
                 // if childentity field is not specified, then don't mess with children; only if child array is specific (even if any)
                 $handle = is_array($data->{$field[0]});
                 if ($handle) {
                     // a little extra overhead here, but due to sort/sequence keys, etc., don't want to blow away and replace unless we have to
                     // first, determine whether linkedentities list is different
                     $peekquery = "call get" . ucfirst($field[0]) . "By" . $this->getName() . 'Id(' . Database::queryNumber($id) . ',' . Database::queryNumber($this->tenantid) . ',' . Database::queryNumber($this->userid) . ');';
                     $results = Database::executeQuery($peekquery);
                     $currentSet = array();
                     $debug = '';
                     while ($row = $results->fetch_assoc()) {
                         array_push($currentSet, intval($row["id"]));
                         $debug .= $row["id"] . '-';
                     }
                     $newSet = array();
                     $debug .= '|';
                     if (is_array($data->{$field[0]})) {
                         $children = $data->{$field[0]};
                         foreach ($children as $c) {
                             array_push($newSet, $c->id);
                             $debug .= $c->id . '-';
                         }
                     }
                     Log::debug('SETS: ' . $debug, 5);
                     // first, determine whether we need to remove children
                     for ($i = 0; $i < count($currentSet); $i++) {
                         if (!in_array($currentSet[$i], $newSet)) {
                             // one of the old children is not in new set; for now, we'll remove all
                             $procname = $this->getRemoveChildrenProcName($field[0]);
                             array_push($followOnQueries, 'call ' . $procname . '(' . $id . ',' . $this->tenantid . ');');
                             // blank current set so all children get re-added
                             $currentSet = array();
                             break;
                         }
                         if ($currentSet[$i] != $newSet[$i]) {
                             // the sequence of the members has changed; for now, we'll remove them all, too
                             // may want more nuanced handling of this in the future if these sets get big or complex
                             $procname = $this->getRemoveChildrenProcName($field[0]);
                             array_push($followOnQueries, 'call ' . $procname . '(' . $id . ',' . $this->tenantid . ');');
                             // blank current set so all children get re-added
                             $currentSet = array();
                             break;
                         }
                     }
                     // now, determine which children need to be added
                     if (is_array($data->{$field[0]})) {
                         $children = $data->{$field[0]};
                         foreach ($children as $c) {
                             if (!in_array($c->id, $currentSet)) {
                                 // this child isn't present. Will need to add
                                 $procname = $this->getAddChildProcName($field[2]);
                                 array_push($followOnQueries, 'call ' . $procname . '(' . $id . ',' . $c->id . ',' . $this->tenantid . ');');
                             }
                         }
                     }
                 }
                 break;
             case "propertybag":
                 $propertyBag = serialize($data->{$field[0]});
                 $query .= $separator . Database::queryString($propertyBag);
                 break;
             case "custom":
                 $query .= $separator . $this->getCustomValue($field[0], $data->{$field[0]}, 'update');
         }
         $separator = ", ";
     }
     // assume tenantid is always needed and is last parameter (or 2nd to last if user required)
     $query .= $separator . Database::queryNumber($this->tenantid);
     $separator = ", ";
     // add userid if object hasOwner
     if ($this->hasOwner()) {
         $query .= $separator . Database::queryNumber($this->userid);
     }
     $query .= ')';
     Log::debug('Pushing query ' . $query, 1);
     array_push($queries, $query);
     // handle user-defined properties
     if ($this->hasProperties()) {
         // remove all properties for object - if not specified in the data, assume it's not longer a valid property
         array_push($queries, $this->getDeletePropertiesSQL($id));
         // get array of properties allowed for this entity & tenant
         $keys = $this->getPropertyKeys();
         foreach ($keys as $key) {
             // determine whether data contains a value for this key - field will be prepended with PROP
             if (property_exists($data, 'PROP-' . $key[0])) {
                 // only save if not empty - that's the MO for now
                 $val = $data->{'PROP-' . $key[0]};
                 if (strlen($val) > 0) {
                     array_push($queries, $this->getSavePropertySQL($id, $key[0], $data->{'PROP-' . $key[0]}));
                 }
             }
         }
     }
     // add follow-one queries for child entities
     foreach ($followOnQueries as $q) {
         array_push($queries, $q);
     }
     Database::executeQueriesInTransaction($queries);
     return true;
 }
Exemplo n.º 12
0
 public static function getList($listID, $tenantID, $userID)
 {
     // putting this into the Utility class as a future wrapper
     // currently, some lists are hard-coded (like states—-things unlikely to change much)
     // others are retrieved from database
     // in future, need to add caching here since many of these lists will be slowly-changing at best
     // also, this is now very application specific and needs to get moved out of Utility to some sort
     // of list server object
     $return = array();
     switch ($listID) {
         case "states":
             $states = array("", "AK", "AL", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "ID", "IA", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MO", "MS", "NC", "ND", "NE", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WY");
             // for states, we want to use the abbreviation as both display and data value, so create multi
             foreach ($states as $state) {
                 $return[] = array($state, $state);
             }
             break;
         case "addressType":
             $query = "select id,type from addressType where tenantID=" . Database::queryNumber($tenantID);
             $result = Database::executeQuery($query);
             while ($r = mysqli_fetch_array($result, MYSQLI_NUM)) {
                 $return[] = $r;
             }
             break;
         case "tenants":
             if ($userID == 1) {
                 $query = "select id,name from tenant";
             } else {
                 $query = "select * from tenant T\n                            inner join tenantUser TU on TU.tenantid=T.id\n                            inner join tenantUserRole TUR on TUR.tenantuserid=TU.id\n                            inner join role R on R.id=TUR.roleid\n                            where R.name='admin'\n                                and TU.userid=" . Database::queryNumber($userID) . ";";
             }
             $result = Database::executeQuery($query);
             while ($r = mysqli_fetch_array($result, MYSQLI_NUM)) {
                 $return[] = $r;
             }
             break;
         case "roles":
             $query = "select name from role;";
             $result = Database::executeQuery($query);
             while ($r = mysqli_fetch_array($result, MYSQLI_NUM)) {
                 $return[] = $r[0];
             }
             break;
         case "categories":
             $query = "call getCategories(" . $tenantID . ")";
             $result = Database::executeQuery($query);
             while ($r = mysqli_fetch_assoc($result)) {
                 $return[] = $r;
             }
             break;
         case "units":
             $units = array("gallon", "liter", "milliliter", "ounces", "pint", "quart");
             foreach ($units as $unit) {
                 $return[] = array($unit, $unit);
             }
             break;
         case "distilleries":
             Utility::debug('retrieving distilleries list: ' . $tenantID, 5);
             $query = "call getDistilleries(" . $tenantID . ");";
             $distilleries = Database::executeQuery($query);
             while ($r = mysqli_fetch_array($distilleries, MYSQLI_NUM)) {
                 $return[] = $r;
             }
             break;
         case "spirit_categories":
             Utility::debug('retrieving spirit categories . . .', 5);
             $query = "select C.id,C.name from category C inner join categoryType CT on C.categorytypeid=CT.id where CT.name='spirit' and C.tenantID=" . $tenantID . " order by C.name;";
             $categories = Database::executeQuery($query);
             while ($r = mysqli_fetch_array($categories, MYSQLI_NUM)) {
                 $return[] = $r;
             }
             break;
         case "categorytypes":
             Utility::debug('retrieving categorytypes . . .', 5);
             $query = "select id,name from categoryType";
             $types = Database::executeQuery($query);
             while ($r = mysqli_fetch_array($types, MYSQLI_NUM)) {
                 $return[] = $r;
             }
             break;
         case "locationStatus":
             // Pending: will be displayed only to certain roles (for now, admins), as they are locations waiting visits and write-ups
             $status_values = array("Active", "Closed", "Temporarily Closed", "Unknown", "Pending", "Coming Soon");
             foreach ($status_values as $unit) {
                 $return[] = array($unit, $unit);
             }
             break;
         case "locationProperty":
             // will need to be more dynamic in future to allow for tenant-specific lists and admin capability for adding
             // but for now we'll use a hardcoded list
             $values = array("Date Founded", "Cooking Method");
             foreach ($values as $unit) {
                 $return[] = array($unit, $unit);
             }
             break;
         case "entities":
             // list of system entities that can be managed/expanded with categories, entity lists, etc.
             $values = array("location", "product");
             foreach ($values as $entity) {
                 $return[] = array($entity, $entity);
             }
             break;
         case "entityListTypes":
             // types of entity lists support; currently only "static" (i.e. defined by set members in a table); in future should
             // support "dynamic" (i.e. list defined by a query)
             $values = array("static");
             foreach ($values as $entity) {
                 $return[] = array($entity, $entity);
             }
             break;
         case "collectionTypes":
             $types = array("product");
             foreach ($types as $type) {
                 $return[] = array($type, $type);
             }
             break;
         case "featureStatus":
             // list of system entities that can be managed/expanded with categories, entity lists, etc.
             $values = array("Draft", "Awaiting Review", "Published");
             foreach ($values as $entity) {
                 $return[] = array($entity, $entity);
             }
             break;
         case "assignmentStatus":
             // list of system entities that can be managed/expanded with categories, entity lists, etc.
             $values = array("Unassigned", "Assigned", "Complete");
             foreach ($values as $entity) {
                 $return[] = array($entity, $entity);
             }
             break;
         case "assignmentType":
             // list of system entities that can be managed/expanded with categories, entity lists, etc.
             $values = array("Feature", "Other");
             foreach ($values as $entity) {
                 $return[] = array($entity, $entity);
             }
             break;
         case "authorList":
             Utility::debug('retrieving author list . . .', 5);
             $query = "call getAuthorListByTenant(" . Database::queryNumber($tenantID) . ")";
             $types = Database::executeQuery($query);
             $return[] = array(null, "-- none --", null, null);
             while ($r = mysqli_fetch_array($types, MYSQLI_NUM)) {
                 $return[] = $r;
             }
             break;
         default:
             Log::debug("Utility:getList() called with unknown list type:" . $listID, 10);
             return false;
     }
     return $return;
 }
Exemplo n.º 13
0
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, True);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
    curl_setopt($ch, CURLOPT_VERBOSE, True);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: token ' . Config::$github_token));
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_USERAGENT, 'Food Finder');
    Utility::debug('Posting issue via cUrl (url=' . $url . ')', 1);
    $response = curl_exec($ch);
    $error = '';
    if ($error = curl_error($ch)) {
        Utility::debug('cUrl exception:' . $error, 9);
    }
    curl_close($ch);
    if ($error) {
        Service::returnError('Unable to post issue to GitHub: ' . $error, 500);
    } else {
        Utility::debug('Issue service call completed successfully.', 5);
        $returnData = json_decode($response);
        if (array_key_exists('number', $returnData)) {
            $response = json_encode(array("id" => $returnData->{"number"}));
        } else {
            Service::returnError('Unable to log issue. Response from repositor: ' . $response);
        }
        //http_response_code(200);
        Service::returnJSON($response);
    }
} else {
    Service::returnError('Unsupported method.', 400, 'issue');
}
Exemplo n.º 14
0
            }
            $response = '{"id":' . json_encode($newID) . "}";
            Utility::debug('Endorsement added: ID=' . $newID, 5);
            header('Content-Type: application/json');
            echo $response;
        }
    } else {
        // this is an existing record: update
        // to do: add data validations
        Utility::debug('Updating link', 5);
        echo 'Unable to uodate link: method is not yet implemented';
        header(' ', true, 500);
    }
} elseif ($_SERVER['REQUEST_METHOD'] == "DELETE") {
    $json = file_get_contents('php://input');
    $data = json_decode($json);
    // to do: got to figure out how to secure this sucker
    $id = $data->{'id'};
    if (!$id > 0) {
        echo 'Unable to delete link: an ID is required';
        header(' ', true, 400);
        die;
    }
    Utility::debug('Deleting link id=' . $id, 5);
    $query = "call deleteLocationLink(" . Database::queryNumber($id);
    $query .= "," . Database::queryNumber($tenantID);
    $query .= ')';
    $result = Database::executeQuery($query);
} else {
    echo "Unsupported HTTP method.";
}
Exemplo n.º 15
0
            } else {
                // this is an existing record: update
                Utility::debug('Saving ' . $type . ' record with id=' . $id, 5);
                $result = false;
                try {
                    $result = $class->updateEntity($id, $data, $tenantID);
                } catch (Exception $ex) {
                    header(' ', true, 500);
                    echo 'Unable to save ' . $type . ':' . $ex->getMessage();
                    die;
                }
                if (!$result) {
                    header(' ', true, 500);
                    echo 'Unable to save ' . $type;
                } else {
                    Utility::debug($type . ' updated.', 5);
                    $response = '{"id":' . json_encode($id) . "}";
                    header('Content-Type: application/json');
                    echo $response;
                }
            }
            break;
        default:
            Service::returnError('Invalid action: ' . $action);
    }
} elseif ($_SERVER['REQUEST_METHOD'] == "PUT") {
    $reset = $_GET["reset"];
    $id = $_GET["id"];
    $class = new User($id, $tenantID);
    if (!$user->userCanEdit($id, $class)) {
        Service::returnError('Access denied.', 403);
Exemplo n.º 16
0
        $query .= "," . Database::queryString($data->{'googleReference'});
        $query .= "," . Database::queryString($data->{'googlePlacesId'});
        $query .= "," . Database::queryNumber($data->{'tenantid'});
        $query .= ')';
        try {
            $result = Database::executeQuery($query);
        } catch (Exception $e) {
            $result = false;
            if ($debug > 0) {
                // don't reveal errors unless in debug mode
                $errMessage = $e->getMessage();
            } else {
                $errMessage = 'Unknown error.';
            }
        }
        if (!$result) {
            header(' ', true, 500);
            echo 'Unable to save location. ' . $errMessage;
        } else {
            Utility::debug('Location updated.', 5);
            $newID = $data->{'id'};
            $response = '{"id":' . json_encode($newID) . "}";
            header('Content-Type: application/json');
            echo $response;
        }
    }
    //echo $json["name"];
    //header(' ', true, 400);
} else {
    echo "Unsupported HTTP method.";
}
Exemplo n.º 17
0
Utility::debug('Form service invoked for type:' . $type . ', method=' . $_SERVER['REQUEST_METHOD'], 5);
$coretypes = array('tenant', 'tenantSetting', 'tenantProperty', 'category', 'menuItem', 'page', 'content', 'tenantContent', 'entityList');
if (!in_array($type, $coretypes, false) && !in_array($type, Application::$knowntypes, false)) {
    // unrecognized type requested can't do much from here.
    Service::returnError('Unknown type: ' . $type, 400, 'entityService?type=' . $type);
}
$classpath = Config::$root_path . '/classes/';
if (in_array($type, $coretypes, false)) {
    // core types will be in core path as configured in config.php
    $classpath = Config::$core_path . '/classes/';
}
// include appropriate dataEntity class & then instantiate it
$classfile = $classpath . $type . '.php';
if (!file_exists($classfile)) {
    header(' ', true, 500);
    Utility::debug('Unable to instantiate class for ' . $type . ' Classfile does not exist. Looking for: ' . $classfile, 9);
    echo 'Internal error. Unable to process entity.';
    die;
}
include_once $classfile;
$classname = ucfirst($type);
// class names start with uppercase
$class = new $classname($userID, $tenantID);
$id = 0;
if (isset($_GET["id"])) {
    $id = $_GET["id"];
}
$parentid = Utility::getRequestVariable('parentid', 0);
$entity = '';
if ($id > 0) {
    try {
Exemplo n.º 18
0
    $query = "call getLocationById(" . $id . "," . $tenantID . "," . $userID . ")";
    $data = Database::executeQuery($query);
    if (!$data) {
        $id = 0;
    } else {
        while ($o = mysqli_fetch_object($data)) {
            $location = $o;
            Utility::debug('Retrieved data for ' . $location->name, 5);
        }
    }
}
if ($id == 0 && $mode != 'edit') {
    Utility::debug('Location.php called with no id and non-edit mode', 1);
    Utility::errorRedirect("Unable to load location: no location specified in request.");
} else {
    Utility::debug('Rendering location.php for location ID=' . $id, 5);
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
	
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Location</title>
        <?php 
include "partials/includes.php";
?>
		<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
		<script type="text/javascript" src="js/validator.js"></script>
		<script src="js/location.js"></script>		
Exemplo n.º 19
0
    echo "<h1>Client example</h1>";
    echo "<p>The following calls are some example of how can you use the restful webservice!</p>";
    //Example of auth method - This method returns the token
    echo "<h2 style='color:green;'>[POST] Service route: /user/auth</h2>";
    $auth = $serviceRequest->post("/user/auth", ["email" => "*****@*****.**", "password" => "123456"], null, false);
    Utility::debug($auth);
    //Set the token for authenticated methods
    $userToken = $auth->payload->data->token;
    //Example of get request to an unauthenticated route to list user
    echo "<h2 style='color:green;'>[GET] Service route: /user/list_user [TOKEN: {$userToken}]</h2>";
    $listUser = $serviceRequest->get("/user/list_user", null, null, false);
    Utility::debug($listUser);
    //Example of get request to an unauthenticated route to read single user
    echo "<h2 style='color:green;'>[GET] Service route: /user/read_user [TOKEN: {$userToken}]</h2>";
    $readUser = $serviceRequest->get("/user/read_user", ["id" => 1], null, false);
    Utility::debug($readUser);
    //Example of post request to an authenticated route to create an user
    echo "<h2 style='color:green;'>[POST] Service: /user/create [TOKEN: {$userToken}]</h2>";
    $create = $serviceRequest->post("/user/create", ["name" => "Darth Vader", "email" => "*****@*****.**", "password" => "123456"], $userToken, false);
    Utility::debug($create);
    //Example of put request to an authenticated route to update an user
    echo "<h2 style='color:green;'>[PUT] Service route: /user/update [TOKEN: {$userToken}]</h2>";
    $update = $serviceRequest->put("/user/update", ["id" => 1, "name" => "Luke Skywalker"], $userToken, false);
    Utility::debug($update);
    //Example of delete request to an authenticated route to delete an user
    echo "<h2 style='color:green;'>[DELETE] Service route: /user/delete [TOKEN: {$userToken}]</h2>";
    $delete = $serviceRequest->delete("/user/delete", ["id" => 2], $userToken, false);
    Utility::debug($delete);
} catch (Exception $e) {
    throw $e;
}
Exemplo n.º 20
0
    header(' ', true, 400);
    die;
}
if ($action == 'cancel') {
    Utility::debug('Canceling batch ' . $batchId . '...', 5);
    $result = Utility::cancelBatch($batchId, $tenantID, $userID);
    if (!$result) {
        echo 'Unable to cancel batch.';
        header(' ', true, 404);
    } else {
        $response = '{"status": "canceled"}';
        header('Content-Type: application/json');
        echo $response;
    }
} else {
    Utility::debug('Checking batch status for batch ' . $batchId, 9);
    $result = Utility::getBatchStatus($batchId, $tenantID, $userID);
    if (!$result) {
        echo 'Batch status not found.';
        header(' ', true, 404);
    } else {
        if ($r = mysqli_fetch_array($result)) {
            $status = $r[2];
            $items = $r[5];
            $processed = $r[6];
            $response = '{"status":' . json_encode($status) . ", ";
            $response .= ' "items":' . json_encode($items) . ",";
            $response .= ' "processed":' . json_encode($processed) . "}";
            header('Content-Type: application/json');
            echo $response;
        } else {
Exemplo n.º 21
0
if (!isset($_SESSION['userID'])) {
    // set ID to 0 to indicate unauthenticated user
    $_SESSION['userID'] = 0;
    $userID = 0;
} else {
    $userID = $_SESSION['userID'];
}
Log::debug('instantiating new user for userID=' . $userID, 1);
$user = new User($userID, $tenantID);
Context::$currentUser = $user;
if ($newsession) {
    Log::startSession(session_id(), $tenantID, $userID);
}
if ($userID > 0 && !$user->canAccessTenant($tenantID)) {
    Log::debug('Unauthorized user attempted to access tenant page. (user='******', tenant=' . $tenantID . ')', 9);
    header('HTTP/1.0 403 Forbidden');
    echo '<p>You are not allowed to access this resource.</p>';
    exit;
} elseif ($userID == 0) {
    // TO DO: check whether tenant allows anonymous access
    // for now, assume that they all do
    $allowAnon = Utility::getTenantProperty($applicationID, $tenantID, $userID, 'allowAnonAccess');
    if (!$allowAnon && strtolower(basename($_SERVER['PHP_SELF'])) != 'login.php') {
        //echo strtolower(basename($_SERVER['PHP_SELF']));
        Log::debug('Unauthenticated user attempted to access tenant page. Redirecting to login. (tenant=' . $tenantID . ')', 9);
        header('Location: Login.php?context=loginRequired');
        die;
    }
}
Utility::debug('pageCheck complete.  (user='******', tenant=' . $tenantID . ')', 1);
Exemplo n.º 22
0
            $result = Database::executeQuery($query);
        } catch (Exception $e) {
            if ($debug > 0) {
                // don't reveal errors unless in debug mode
                $errMessage = $e->getMessage();
            }
        }
        if (!$result) {
            Utility::debug("Unable to save location/place #: " . $count . ". " . $errMessage, 5);
            $exceptions[] = $errMessage;
            $exceptionCount++;
        } else {
            $newID = 0;
            while ($r = mysqli_fetch_array($result)) {
                $newID = $r[0];
            }
            $response = '{"id":' . json_encode($newID) . "}";
            Utility::debug('Location added: ID=' . $newID, 5);
        }
    }
    if (!Utility::updateBatch($batchid, $count, $tenantid)) {
        Utility::debug('Unable to update batch status. Assuming canceled batch and halting processing.', 3);
        $canceled = true;
        break;
    }
}
if (!$canceled) {
    Utility::finshBatch($batchid, $itemscomplete, $tenantid);
}
Utility::debug('Batch process complete.', 5);