Esempio n. 1
0
function secret($dbs, $cryptKey, $id, $data = NULL)
{
    global $db;
    $maxLen = strlen('9223372036854775807') - 1;
    // keep it shorter than biggest usable unsigned "big int" in MySQL
    $table = 'offsite';
    extract((array) $dbs[$db_name = key($dbs)], EXTR_PREFIX_ALL, 'db');
    $db = new PDO("{$db_driver}:host={$db_host};port={$db_port};dbname={$db_name}", $db_user, $db_pass);
    if (!isset($data)) {
        return offlog(35, $result = lookup('data', $table, $id)) == '' ? '' : base64_encode(ezdecrypt($result, $cryptKey));
    }
    // retrieval is easy
    $data = ezencrypt(base64_decode($data), $cryptKey);
    if ($id) {
        return offlog(38, query("UPDATE {$table} SET data=? WHERE id=?", array($data, $id)) ? $id : FALSE);
    }
    // replacing old data with new value
    while (TRUE) {
        // new data, find an unused id
        $id = randomInt($maxLen);
        if (!lookup(1, $table, $id)) {
            break;
        }
    }
    return offlog(44, query("INSERT INTO {$table} (id, data) VALUES (?, ?)", array($id, $data)) ? $id : FALSE);
}
Esempio n. 2
0
function createWikiTable($header, $filelist, $filespecs, $languages)
{
    global $linkprefix;
    global $version;
    global $subversion;
    //Get the DBpedia Version Number for Preview File
    preg_match('~/([0-9]+\\.[0-9]+)/~', $linkprefix, $matches);
    echo "===" . $header . "===\n";
    echo "**NOTE: You can find DBpedia dumps in 97 languages at our ((http://downloads.dbpedia.org/" . $version . "." . $subversion . "/ DBpedia download server)).**\n\n";
    echo "//Click on the dataset names to obtain additional information.//\n";
    echo "#||\n||**Dataset**|**" . implode('**|**', $languages) . "**||\n";
    if ($header == "Core Datasets") {
        echo "||((#dbpediaontology DBpedia Ontology)) ++(<# <a href=\"http://downloads.dbpedia.org/preview.php?file=" . $version . "." . $subversion . "_sl_dbpedia_" . $version . "." . $subversion . ".owl.bz2\">preview</a> #>)++|++<# <a href=\"http://downloads.dbpedia.org/" . $version . "." . $subversion . "/dbpedia_" . $version . "." . $subversion . ".owl.bz2\" title=\"Triples: unknown; Filesize(download): unknown; Filesize(unpacked): unknown\">owl</a> #>++|++--++|++--++|++--++|++--++|++--++|++--++|++--++|++--++|++--++|++--++|++--++||";
    }
    foreach ($filelist as $name) {
        foreach ($languages as $index => $lang) {
            if ($index === 0) {
                echo '||((#' . str_replace(" ", "", strtolower($name['title'])) . ' ' . $name['title'] . ')) ++(<# <a href="http://downloads.dbpedia.org/preview.php?file=' . $matches[1] . '_sl_' . $lang . '_sl_' . $name['file'] . $lang . '.nt.bz2">preview</a> #>)++|';
            }
            echo '++' . lookup($name['file'], $lang, $filespecs) . '++|';
        }
        echo "|\n";
    }
    echo "||# \n";
}
Esempio n. 3
0
function lookup($user, $operation, $acl, $type)
{
    $id = (string) $user->id;
    if (isset($acl->users->{$id}) and ($acl->users->{$id}->{$type} === '*' or in_array($operation, $acl->users->{$id}->{$type}))) {
        return true;
    } elseif ($groups = intersect($acl->groups, $user->groups)) {
        foreach ($groups as $group) {
            if (isset($group->{$type}) and ($group->{$type} === '*' or in_array($operation, $group->{$type}))) {
                return true;
            }
        }
    }
    if (isset($acl->parent)) {
        return lookup($user, $operation, $acl->parent, $type);
    } else {
        return false;
    }
}
Esempio n. 4
0
    render("sell_form.php", ["positions" => $positions]);
    // else if user has sold a position (stored in $_POST)
} else {
    // access variables
    $id = $_SESSION["id"];
    $id_int = intval($id);
    $symbol = $_POST["symbol"];
    $symbol_str = strval($symbol);
    $positions = $_SESSION["positions"];
    // get revenue of sold stock
    // get number of shares
    foreach ($positions as $position) {
        if ($position["symbol"] == $symbol_str) {
            $total = $position["total"];
            $shares = $position["shares"];
        }
    }
    // get price of stock
    $stock = lookup("{$symbol}");
    $price = $stock["price"];
    //add revenue of sold stock to cash
    query("UPDATE `users` SET cash = cash + {$total} WHERE id = {$id}");
    // delete position from porfolio
    query("DELETE FROM `portfolios` WHERE id = ? AND symbol = ?", $id_int, $symbol_str);
    // store transaction in transactions table
    $rows = query("SELECT NOW()");
    $datetime = $rows[0]["NOW()"];
    query("INSERT INTO `transactions` (id, transaction, datetime, symbol, shares, price)" . " VALUES (?, ?, ?, ?, ?, ?)", $id, "SELL", $datetime, $symbol, $shares, $price);
    //redirect to index.php
    redirect("index.php");
}
Esempio n. 5
0
<?php

// Configuration
require "../includes/config.php";
// Get the user's id number, provided to $_SESSION upon login
$id = $_SESSION["id"];
// Declare a table to load in the data we want from lookup() and query()
$userport = [];
// Get every row from the stocks table where the id matches the session
$portquery = query("SELECT * FROM stocks WHERE id  = ?", $id);
// Query all the user's information to attain cash reserves
$userquery = query("SELECT * FROM users WHERE id  = ?", $id);
$username = $userquery[0]["username"];
// Loop through each row of the portquery
foreach ($portquery as $row) {
    // Perform a lookup on the symbol found in the current row
    $stock = lookup($row["symbol"]);
    // If there was no lookup error, i.e. $stock is not false
    if ($stock !== false) {
        // Load up the userport table with appropriate key-val pairs
        $userport[] = ["name" => $stock["name"], "symbol" => $row["symbol"], "shares" => $row["shares"], "price" => $stock["price"], "totval" => $row["shares"] * $stock["price"], "cash" => $userquery[0]["cash"]];
    }
}
?>
    
<?php 
// render portfolio
render("portfolio.php", ["title" => "Portfolio", "userport" => $userport, "username" => $username]);
Esempio n. 6
0
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    render("buy_form.php", ["title" => "Buy"]);
} else {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // ensure that a whole number > 0 was entered, no fractions of shares allowed
        $shares = $_POST["shares"];
        if (preg_match("/^\\d+\$/", $shares) == false) {
            apologize("You must enter a whole number!");
        } elseif ($shares <= 0) {
            apologize("Enter a number greater than zero!");
        }
        $symbol = strtoupper($_POST["symbol"]);
        $id = $_SESSION["id"];
        $action = "BUY";
        // get a quote for the requested share
        $quote = lookup($symbol);
        if (!$quote) {
            apologize("Symbol not found!");
        }
        // users are unique so select the first row [0]
        $user = cs50::query("SELECT * FROM users WHERE id = ?", $id)[0];
        $value = $shares * $quote["price"];
        $cash_available = $user["cash"];
        if ($value > $cash_available) {
            apologize("You don't have enough cash!");
        }
        // add purchase to user's portfolio
        cs50::query("INSERT INTO portfolios (user_id, symbol, shares) VALUES (?, ?, ?)\n            ON DUPLICATE KEY UPDATE shares = shares + ?", $id, $symbol, $shares, $shares);
        // set user's cash to reflect purchase
        cs50::query("UPDATE users SET cash = cash - ? WHERE id = ?", $value, $id);
        // add purchase information into history
    $string = str_replace(" ", "+", urlencode($string));
    $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $string . "&sensor=false";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $details_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);
    // If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
    if ($response['status'] != 'OK') {
        return null;
    }
    $geometry = $response['results'][0]['geometry'];
    $array = array('latitude' => $geometry['location']['lat'], 'longitude' => $geometry['location']['lng']);
    return $array;
}
$result = mysqli_query($conn, "Select id,Address,City,Zip,State,Latitude,Longitude from tbl_name;");
if (!$result) {
    die('Invalid query: ' . mysql_error());
} else {
    if (mysqli_num_rows($result) == 0) {
        die("No rows found.");
    }
    while ($row = mysqli_fetch_assoc($result)) {
        if ($row["Latitude"] != 0 || $row["Longitude"] != 0) {
            continue;
        }
        $latlon = lookup($row['Address'] . " " . $row['City'] . " " . $row['Zip'] . " " . $row['State']);
        mysqli_query($conn, "Update tbl_name set Latitude ='" . $latlon["latitude"] . "', Longitude = '" . $latlon["longitude"] . "' where id=" . $row["id"] . ";");
        echo $row['Address'] . " " . $latlon["latitude"] . "  " . $latlon["longitude"] . " <br />";
    }
}
include "CloseConnection.php";
Esempio n. 8
0
                <input type="text" class="form-control" name="search" placeholder="ex: University of Central Florida">
            </div>
			
			<button type="submit" class="btn btn-primary">Search</button>
        </form>

<?php 
// TESTING NOTE: To see function results, change "$see_output" value to True
$see_output = False;
if (isset($_POST['search']) && trim($_POST['search']) != '') {
    $search = $_POST['search'];
    $Name = '%' . $search . '%';
    $search_string = htmlentities($search);
    //We use google's geocode api to take in the place of interest
    //and see if we can return a valid result back from it.
    $search_lookup = lookup($search_string);
    if ($see_output) {
        print_r($search_lookup);
    }
    $search_name = "SELECT * \n                FROM University U\n                WHERE U.Name like :name  AND U.University_id <> 1";
    $university_name_params = array(':name' => $Name);
    $result_name = $db->prepare($search_name);
    $result_name->execute($university_name_params);
    $number = $result_name->rowCount();
    if ($number == 1) {
        echo "<h3><strong>{$number} result found searching for '{$search_string}' by Name. </strong></h3><hr/>";
    } else {
        echo "<h3><strong>{$number} results found searching for '{$search_string}' by Name. </strong></h3><hr/>";
    }
    while ($row = $result_name->fetch()) {
        $Name = $row['Name'];
        apologize("Error communicating with databse");
    } else {
        render("sell_form.php", ["title" => "Sell Form", "symbols" => $symbols]);
    }
} else {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // if no stock was selected to back to index
        if ($_POST["symbol"] === " ") {
            redirect("/");
        }
        // put symbol into a variable
        $symbol = $_POST["symbol"];
        // look up the number of shares of that stock a user has
        $shares = query("SELECT shares FROM portfolios WHERE id = ? AND symbol = '{$symbol}'", $_SESSION["id"]);
        // get current information on stock
        $stock = lookup($symbol);
        // the amount of money selling all shares of that stock would be worth
        $sale_value = $stock["price"] * $shares[0]["shares"];
        // delete that stock form their portfolio
        if (query("DELETE FROM portfolios WHERE id = ? AND symbol = '{$symbol}'", $_SESSION["id"]) === false) {
            apologize("error communicating with databse");
        }
        // update the amount of cash a user now has
        if (query("UPDATE users SET cash = cash + {$sale_value} WHERE id = ?", $_SESSION["id"]) === false) {
            apologize("error communicating with databse");
        }
        // put sale into history
        if (query("INSERT INTO history (id, symbol, shares, price, boughtSold)\n            VALUES(?, '{$symbol}', ?, ?, 'SELL')", $_SESSION["id"], $shares[0]["shares"], $stock["price"]) === false) {
            apologize("error communicating with databse");
        }
        // redirect to index
Esempio n. 10
0
                if ($qty == $boh[0]["shares"]) {
                    query("DELETE from shares WHERE id = ? AND ticker = UPPER(?)", $id, $ticker);
                }
                if (query("COMMIT") === false) {
                    if (query("ROLLBACK")) {
                        apologize("TRANSACTION ERROR, ROLLED BACK");
                    } else {
                        apologize("CRITICAL: TRANSACTION ERROR *AND* ROLLBACK FAILED!!!");
                    }
                } else {
                    redirect("index.php");
                }
            }
        }
    }
} else {
    $data = array();
    $stocksheld = query("SELECT * FROM shares WHERE id = ?", $id);
    foreach ($stocksheld as $stock) {
        $stockticker = $stock["ticker"];
        $shares = $stock["shares"];
        $lookup = lookup($stockticker);
        $price = $lookup["price"];
        $name = $lookup["name"];
        $data[$stockticker] = ["ticker" => $stockticker, "shares" => $shares, "price" => $price, "name" => $name];
    }
    if ($stocksheld === false) {
        apologize("No Stock to Sell");
    }
    render("sell_form.php", ["title" => "Sell Shares", "data" => $data]);
}
Esempio n. 11
0
<?php

// configuration
require "../includes/config.php";
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // render the quote (validation in the template... sorry but your MVC videos werent working and I dont see the point
    render("price_quote.php", ["stock" => lookup($_POST["symbol"])]);
} else {
    // else render only form
    render("price_quote_request.php", ["title" => "Request Price Quote"]);
}
Esempio n. 12
0
    $ip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
    $ip = getenv('HTTP_X_FORWARDED_FOR');
} else {
    $ip = getenv('REMOTE_ADDR');
}
if (file_exists('/etc/redhat-release')) {
    $fnewsize = filesize('/etc/redhat-release');
    $fp = fopen('/etc/redhat-release', 'r');
    $redhat = fread($fp, $fnewsize);
    fclose($fp);
}
$Fields = $dbc->db->dsn;
$Fields['SYSTEM'] = $redhat;
$Fields['MYSQL'] = $row['VERSION'];
$Fields['PHP'] = phpversion();
$Fields['FLUID'] = RBAC_VERSION;
$Fields['IP'] = lookup($ip);
$Fields['ENVIRONMENT'] = SYS_SYS;
$Fields['SERVER_SOFTWARE'] = getenv('SERVER_SOFTWARE');
$Fields['SERVER_NAME'] = getenv('SERVER_NAME');
$Fields['SERVER_PROTOCOL'] = getenv('SERVER_PROTOCOL');
$Fields['SERVER_PORT'] = getenv('SERVER_PORT');
$Fields['REMOTE_HOST'] = getenv('REMOTE_HOST');
$Fields['SERVER_ADDR'] = getenv('SERVER_ADDR');
$Fields['HTTP_USER_AGENT'] = getenv('HTTP_USER_AGENT');
$Fields['a'] = $dbc;
$G_PUBLISH = new Publisher();
$G_PUBLISH->SetTo($dbc);
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'rbac/dbInfo', '', $Fields, 'appNew2');
G::RenderPage('publish');
Esempio n. 13
0
<?php

if (isset($portfolio)) {
    if (empty($portfolio)) {
        printf("Your portfolio is empty! Go <a href = \"quote.php\">buy stocks</a> and build your portfolio now!");
    } else {
        ?>
<form method="post" action="sell-confirm.php"> <!--action="sell-confirm.php" -->
    <fieldset> 
        <div class="form-group"> 
            <select class = "form-control" name = "sellStock">
                <?php 
        if (isset($portfolio)) {
            foreach ($portfolio as $item) {
                printf("<option style=\"width:200px;text-align:center\" value = " . $item["symbol"] . ">");
                $ticker = lookup($item["symbol"]);
                printf($ticker["name"] . " (" . $ticker["symbol"] . ")");
                printf("</option>");
            }
        }
        ?>
            </select>
        </div>
        <div class="form-group">
            <input class="form-control" style = "text-align:center" align = "center" autocomplete = "off" name="sellShares" placeholder="Shares" />
        </div>
        <div class = "form-group">
            <p id = "calculation"></p>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-default">Sell Shares</button>
Esempio n. 14
0
function calculateCost($ticker, $shares)
{
    $data = lookup($ticker);
    return $data["price"] * $shares;
}
Esempio n. 15
0
/**
 * Puts data into history table.
 */
function history($transaction, $symbol, $shares)
{
    $price = lookup($symbol);
    // $price["price"] *= $shares;
    query("INSERT INTO history (id, transaction, symbol, shares, price) VALUES(?, ?, ?, ?, ?)", $_SESSION["id"], $transaction, $symbol, $shares, $price["price"]);
}
Esempio n. 16
0
function IP2C($string, $isCLI)
{
    include_once "config.php";
    include_once "functions.php";
    if ($isCLI == 'NO') {
        // Running from a browser
        $when = 'WHERE ' . hextostr($string) . ' AND ';
    } else {
        // Running from the command line
        if ($string == 0) {
            $when = "WHERE ";
        }
        if ($string == 1) {
            $startDate = gmdate("Y-m-d");
            $startTime = "00:00:00";
            $endDate = gmdate("Y-m-d", strtotime($startDate . "+1 day"));
            $endTime = "00:00:00";
            $when = "WHERE e.timestamp BETWEEN '{$startDate} {$startTime}' AND '{$endDate} {$endTime}' AND";
        }
        echo "Performing base queries (this can take a while)..\n\n";
    }
    function lookup($list)
    {
        while ($row = mysql_fetch_row($list)) {
            $ip = $row[0];
            $dot = long2ip((double) $ip);
            $ipLookup = mysql_query("SELECT registry, cc, c_long, type, date, status FROM ip2c WHERE\n                                     {$ip} >=start_ip AND {$ip} <= end_ip LIMIT 1");
            $result = mysql_fetch_array($ipLookup);
            if ($result) {
                $registry = $result[0];
                $cc = $result[1];
                $c_long = $result[2];
                $type = $result[3];
                $date = $result[4];
                $status = $result[5];
                mysql_query("REPLACE INTO mappings (registry,cc,c_long,type,ip,date,status)\n                             VALUES (\"{$registry}\",\"{$cc}\",\"{$c_long}\",\"{$type}\",\"{$ip}\",\"{$date}\",\"{$status}\")");
                echo "-- Mapped {$dot} ({$ip}) to {$cc} ({$c_long})\n";
            }
        }
    }
    // DB Connect
    $db = mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
    mysql_select_db($dbName, $db) or die(mysql_error());
    // Start timing
    $st = microtime(true);
    $sipList = mysql_query("SELECT DISTINCT(e.src_ip) FROM event AS e LEFT JOIN mappings AS m ON e.src_ip=m.ip\n                            WHERE (m.ip IS NULL OR m.cc = '01')");
    $dipList = mysql_query("SELECT DISTINCT(e.dst_ip) FROM event AS e LEFT JOIN mappings AS m ON e.dst_ip=m.ip\n                            WHERE (m.ip IS NULL OR m.cc = '01')");
    $sipCount = $dipCount = 0;
    if ($sipList) {
        $sipCount = mysql_num_rows($sipList);
        if ($sipCount > 0) {
            lookup($sipList);
        }
    }
    if ($dipList) {
        $dipCount = mysql_num_rows($dipList);
        if ($dipCount > 0) {
            lookup($dipList);
        }
    }
    $allRecs = mysql_query("SELECT COUNT(*) FROM mappings");
    $allCount = mysql_fetch_row($allRecs);
    // Stop Timing
    $et = microtime(true);
    $time = $et - $st;
    $rt = sprintf("%01.3f", $time);
    if ($isCLI == 'NO') {
        $html = "\r<table align=left>\n                 \r<tr><td align=left style=\"font-size: 10px;\"><b>&nbsp;-> Query Time: {$rt} seconds</b></td></tr>\n                 \r<tr><td align=left style=\"font-size: 10px;\"><b>&nbsp;-> Source Count: {$sipCount}</b></td></tr>\n                 \r<tr><td align=left style=\"font-size: 10px;\"><b>&nbsp;-> Destination Count: {$dipCount}</b></td>\n                 \r<tr><td align=left style=\"font-size: 10px;\"><b>&nbsp;-> Total Mapped: {$allCount['0']}</b></td></tr>\n                 \r</table>";
        return $html;
    }
    if ($isCLI == 'YES' && $string == 0) {
        echo "\n-> Query Time: {$rt} seconds\n              \r-> Source Count: {$sipCount}\n              \r-> Destination Count: {$dipCount}\n              \r-> Total Mapped: {$allCount['0']}\n\n";
    }
}
Esempio n. 17
0
function tryCreateEvent($db, $is_type_super_admin, $name, $category_id, $description, $location, $room_number, $address, $event_date, $event_time, $event_type, $contact_email, $contact_phone, $rso_id)
{
    $admin_id = $_SESSION['user']['User_id'];
    // Only Admins or Super-Admins can see the form
    // If the event is an RSO event, then approval from the super-admin isn't needed
    $approved = 0;
    if ($event_type == RSO_EVENT || $is_type_super_admin) {
        $approved = 1;
    }
    // Store the date and time into an appropriate format to insert into the database
    list($month, $day, $year) = explode('/', $event_date);
    list($hour, $dayType) = explode(' ', $event_time);
    $hour = $hour != 12 && $dayType == "PM" ? $hour + 12 : $hour;
    $date_time = $year . '-' . $month . '-' . $day . ' ' . $hour . ':00:00';
    // Retrieve the latitude and longitude of the address
    $search_lookup = lookup($address);
    if ($search_lookup['latitude'] == 'failed') {
        return INVALID_LOCATION;
    }
    // Create the location name to be stored into the Location table and check for conflicts
    $location_name = '';
    if ($room_number != '') {
        $location_name .= $room_number . ' at ';
    }
    $location_name .= $location . ' at ';
    $location_name .= $address;
    // Check to see if there is an existing event with the same date, time, and place
    $event_conflict_params = array(':date_time' => $date_time, ':location_name' => strtolower($location_name));
    $event_conflict_query = '
            SELECT COUNT(*)
            FROM Event E, Event_Location EL, Location L
            WHERE (E.date_time = :date_time) AND (E.Event_id = EL.Event_id) AND (EL.Location_id = L.Location_id) AND (LOWER(L.Name) = :location_name)
        ';
    $result = $db->prepare($event_conflict_query);
    $result->execute($event_conflict_params);
    $event_conflict = $result->fetchColumn();
    if ($event_conflict) {
        return CONFLICT;
    }
    // Check the user correctly submitted an RSO to be associated with the event if applicable
    if ($rso_id == 'Not Applicable' && $event_type == RSO_EVENT) {
        return MISSING_RSO;
    }
    if ($rso_id != 'Not Applicable' && $event_type != RSO_EVENT) {
        return UNNEEDED_RSO;
    }
    if ($rso_id != 'Not Applicable' && $event_type == RSO_EVENT) {
        $find_rso_params = array(':rso_id' => $rso_id, ':admin_id' => $admin_id);
        $find_rso_query = '
                SELECT COUNT(*)
                FROM RSO R
                WHERE (R.RSO_id = :rso_id) AND (R.Admin_id = :admin_id)
            ';
        $result = $db->prepare($find_rso_query);
        $result->execute($find_rso_params);
        $admin_of_rso = $result->fetchColumn();
        if (!$admin_of_rso) {
            return WRONG_RSO;
        }
    }
    // Insert the event information into the Event table
    $create_event_params = array(':admin_id' => $admin_id, ':name' => $name, ':category_id' => $category_id, ':description' => $description, ':date_time' => $date_time, ':event_type' => $event_type, ':contact_email' => $contact_email, ':contact_phone' => $contact_phone, ':approved' => $approved);
    $create_event_query = '
            INSERT INTO Event (
                Admin_id,
                Name,
                Category_id,
                Description,
                Date_time,
                Type,
                Contact_email,
                Contact_phone,
                Approved
            ) VALUES (
                :admin_id,
                :name,
                :category_id,
                :description,
                :date_time,
                :event_type,
                :contact_email,
                :contact_phone,
                :approved
            )
        ';
    $result = $db->prepare($create_event_query)->execute($create_event_params);
    // Find the event_id from the Event table
    $event_id = $db->lastInsertId();
    // Update the rso_id from a NULL value if applicable to the Event table
    if ($rso_id != 'Not Applicable') {
        $update_rso_id_params = array(':event_id' => $event_id, ':rso_id' => $rso_id);
        $update_rso_id_query = '
                UPDATE Event
                SET RSO_id = :rso_id
                WHERE Event_id = :event_id
            ';
        $result = $db->prepare($update_rso_id_query)->execute($update_rso_id_params);
    }
    // Insert the relation into the University_Event table
    $create_event_relation_params = array(':university_id' => $_SESSION['user']['University_id'], 'event_id' => $event_id);
    $create_event_relation_query = '
            INSERT INTO University_Event (
                University_id,
                Event_id
            ) VALUES (
                :university_id,
                :event_id
            )
        ';
    $result = $db->prepare($create_event_relation_query)->execute($create_event_relation_params);
    // Insert the location into the Location table
    $create_location_params = array(':location_name' => $location_name, ':latitude' => $search_lookup['latitude'], ':longitude' => $search_lookup['longitude']);
    $create_location_query = '
            INSERT INTO Location (
                Name,
                Latitude,
                Longitude
            ) VALUES (
                :location_name,
                :latitude,
                :longitude
            )
        ';
    $result = $db->prepare($create_location_query)->execute($create_location_params);
    // Find the location_id from the Location table
    $location_id = $db->lastInsertId();
    // Insert the relation into the Event_Location table
    $create_location_relation_params = array(':event_id' => $event_id, ':location_id' => $location_id);
    $create_location_relation_query = '
            INSERT INTO Event_Location (
                Event_id,
                Location_id
            ) VALUES (
                :event_id,
                :location_id
            )
        ';
    $result = $db->prepare($create_location_relation_query)->execute($create_location_relation_params);
    if ($approved) {
        return VALID_SUBMIT_APPROVED;
    }
    return VALID_SUBMIT_PENDING_APPROVAL;
}
Esempio n. 18
0
<?php

require "../includes/config.php";
// check to see if page requested
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // if stock is legitimate then extract symbol, name, price
    $stock = lookup($_POST["ticker"]);
    if ($stock === false) {
        apologize("Stock symbol invalid");
    }
    // render display page, passing in symbol name and price
    render("quote_display.php", ["title" => "quote display", "symbol" => $stock["symbol"], "name" => $stock["name"], "price" => $stock["price"]]);
} else {
    render("quote_form.php");
}
Esempio n. 19
0
<?php

// configuration
require "../includes/config.php";
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate the name
    if (empty($_POST["symbol"])) {
        apologize("Please enter the stock symbol.");
    }
    $s = lookup($_POST["symbol"]);
    if ($s === false) {
        apologize("Please select a valid stock ID.");
    }
    $query = query("SELECT shares FROM portfolio WHERE id = ? and symbol = ?", $_SESSION["id"], $_POST["symbol"]);
    if ($query === false) {
        apologize("Error while selling shares.");
    }
    $value = $s["price"] * $query[0]["shares"];
    $transaction = "SELL";
    $rows = query("SELECT shares FROM portfolio WHERE id = ? and symbol = ?", $_SESSION["id"], $_POST["symbol"]);
    $amount = $rows[0]["shares"];
    query("UPDATE users set cash = cash + ? WHERE id = ?", $value, $_SESSION["id"]);
    query("INSERT INTO history (id, trans, symbol, shares, price) VALUES(?, ?, ?, ?, ?)", $_SESSION["id"], $transaction, $s["symbol"], $amount, $value);
    query("DELETE FROM portfolio where id = ? and symbol = ?", $_SESSION["id"], $_POST["symbol"]);
    redirect("index.php");
} else {
    // else render form
    render("sell.php", ["title" => "Sell"]);
}
Esempio n. 20
0
<table class = "portfolio">
    <?php 
if (isset($deposit)) {
    print "<h4>" . money_format($deposit, 2) . " has been deposited into your account. </h4>";
}
print "<tr>";
print "<th>" . "SYMBOL" . "</th>";
print "<th>" . "NAME" . "</th>";
print "<th>" . "SHARES" . "</th>";
print "<th>" . "COST PER SHARE" . "</th>";
print "<th>" . "CURRENT VALUE" . "</th>";
print "</tr>";
$portfolio_bal = 0;
foreach ($positions as $position) {
    $stock = lookup($position["symbol"]);
    print "<tr>";
    print "<td>" . $position["symbol"] . "</td>";
    print "<td>" . $stock["name"] . "</td>";
    print "<td>" . $position["shares"] . "</td>";
    print "<td>" . "\$ " . number_format($position["price"], 2) . "</td>";
    print "<td>" . "\$ " . number_format($position["price"] * $position["shares"], 2) . "</td>";
    print "</tr>";
    $portfolio_bal += $position["price"] * $position["shares"];
}
print "<tr>";
print "<td>" . "CASH" . "</td>";
print "<td>" . "</td>" . "<td>" . "</td>" . "<td>" . "</td>";
print "<td>" . "\$ " . number_format($balance, 2) . "</td>";
print "</tr>";
$portfolio_bal += $balance;
print "<tr>";
Esempio n. 21
0
        mysql_query("{$RackObject_statement}");
        mysql_query("{$RackObjectHistory_statement}");
        echo "RackObject statement: {$RackObject_statement}\n";
        echo "RackObjectHistory statement: {$RackObjectHistory_statement}\n";
    }
}
function update_master_object($master_object_id)
{
    global $master_object_name;
    global $object_name;
    global $name;
    if ($name != $object_name) {
        $master_object_name_new = preg_replace("/{$object_name}/", $name, $master_object_name);
        //UPDATE ************ mysql update
        $master_object_update_query = "update RackObject set name=\"" . $master_object_name_new . "\" where id=" . $master_object_id;
        mysql_query("{$master_object_update_query}");
    }
}
lookup();
if (authenticate() == 0) {
    exit("incorrect username and/or password");
}
if ($object_id) {
    //if lookup() set $object_id, there was a successfull object lookup
    update_object($object_id);
}
if ($master_object_id) {
    //if lookup() set $master_object_id, there was a successfull master object lookup
    update_master_object($master_object_id);
}
mysql_close();
Esempio n. 22
0
    curl_setopt($ch, CURLOPT_URL, $details_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);
    // If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
    if ($response['status'] != 'OK') {
        return null;
    }
    // print_r($response);
    $geometry = $response['results'][0]['geometry'];
    $longitude = $geometry['location']['lat'];
    $latitude = $geometry['location']['lng'];
    $array = array('latitude' => $geometry['location']['lat'], 'longitude' => $geometry['location']['lng'], 'location_type' => $geometry['location_type']);
    return $array;
}
$city = $_POST['city'];
$array = lookup($city);
$lats = $array['latitude'];
$lons = $array['longitude'];
//echo $lats . "/" . $lons;
if (isset($city)) {
    if (isset($next)) {
        $urls = "http://ws.anomo.com/v210/index.php/webservice/user/search_user/" . $token . "/" . $userid . "/" . $lats . "/" . $lons . "/" . $next . "/0/18/100";
    } else {
        $urls = "http://ws.anomo.com/v210/index.php/webservice/user/search_user/" . $token . "/" . $userid . "/" . $lats . "/" . $lons . "/1/0/18/100";
    }
    //echo $urls;
    $chs = curl_init($urls);
    curl_setopt($chs, CURLOPT_POST, 1);
    // curl_setopt ($chs, CURLOPT_POSTFIELDS, "Keyword=$user");
    curl_setopt($chs, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($chs, CURLOPT_HEADER, 0);
Esempio n. 23
0
File: test.php Progetto: qujian/ydwx
<?php

include_once '../config.php';
include_once './libs/wx.php';
$array = array();
$menu1 = new YDWXMenu();
$menu1->name = "我的标签";
$menu1->type = YDWXMenu::TYPE_VIEW;
$menu1->url = SITE_URI . "app/myqrcodes.php";
$menu2 = new YDWXMenu();
$menu2->name = "购买标签";
$menu2->type = YDWXMenu::TYPE_VIEW;
$menu2->url = SITE_URI . "app/pay.php";
$menu3 = new YDWXMenu();
$menu3->name = "扫描标签";
$menu3->type = YDWXMenu::TYPE_SCANCODE_PUSH;
$menu3->key = "scan_qrcode";
$access_token = lookup("value", "options", "name='access_token'");
//echo "access token",$access_token,"<br/>";
// createMenus($access_token, array($menu1, $menu2, $menu3));
//removeMenus($access_token);
echo "getmenus:<br/>";
print_r(getMenus($access_token));
// $gift_number = lookup("value", "options", "name='new_user_gift_number'");
// createEmptyQrcode($gift_number);
Esempio n. 24
0
<?php

// configuration
require "../includes/config.php";
// common variables
$id = $_SESSION["id"];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["ticker"]) || empty($_POST["qty"])) {
        apologize("Please specify both ticker and qty to purchase stock.");
    } else {
        $balance = query("SELECT cash FROM users where id = ?", $id);
        $balance = $balance[0]["cash"];
        $lookup = lookup($_POST["ticker"]);
        if ($lookup === false) {
            apologize("Sorry, could not lookup stock quote. ABORT.");
        }
        $cost = $lookup["price"] * $_POST["qty"];
        if ($lookup["price"] * $_POST["qty"] > $balance) {
            apologize("INSUFFICIENT FUNDS");
        } else {
            query("START TRANSACTION");
            query("UPDATE users SET cash = cash - ? WHERE id = ?", $cost, $id);
            query("INSERT shares (id, ticker, shares) values (?, UPPER(?), ?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", $id, $_POST["ticker"], $_POST["qty"]);
            query("INSERT INTO history (id, buy, ticker, shares, shareprice) VALUES (?, 1, UPPER(?), ?, ?)", $id, $_POST["ticker"], $_POST["qty"], $lookup["price"]);
            if (query("COMMIT") === false) {
                if (query("ROLLBACK")) {
                    apologize("TRANSACTION ERROR, ROLLED BACK");
                } else {
                    apologize("CRITICAL: TRANSACTION ERROR *AND* ROLLBACK FAILED!!!");
                }
            } else {
Esempio n. 25
0
<?php

// configuration
require "../includes/config.php";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    render("buy_form.php", ["title" => "Sell"]);
} else {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (!preg_match("/^\\d+\$/", $_POST['quantity'])) {
            apologize("Sale canceled. You can only buy whole shares, please indicate a positive integer");
        }
        if (lookup($_POST["symbol"]) === false) {
            apologize("Sale canceled. Please choose a valid stock symbol");
        }
        $sharearray = lookup(strtoupper($_POST["symbol"]));
        $stock = strtoupper($_POST["symbol"]);
        $idrows = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
        $saleprice = moneyformat($sharearray["price"] * $_POST["quantity"]);
        if ($saleprice > $idrows[0]['cash']) {
            apologize("Sale canceled.  Poor you! you don't have enough money to buy these shares of " . $_POST["symbol"]);
        } else {
            query("INSERT INTO portfolio (id, symbol, shares) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE shares = \n            shares + VALUES(shares)", $_SESSION["id"], "{$stock}", $_POST["quantity"]);
            $newbalance = $idrows[0]['cash'] - $saleprice;
            query("UPDATE users SET cash = ? WHERE id = ?", $newbalance, $_SESSION["id"]);
            query("INSERT INTO history (id, symbol, soldorbought, number, price) VALUES (?, ?, 0, ?, ?)", $_SESSION["id"], "{$stock}", $_POST["quantity"], $saleprice);
            redirect("/");
        }
    }
}
?>
        
Esempio n. 26
0
    render("../templates/buy.php", ["title" => "Buy"]);
} else {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // verify presence of symbol and desired number of shares
        if (empty($_POST["symbol"])) {
            apologize("Please name the stock you want to buy");
        } else {
            if (empty($_POST["shares"]) || preg_match("/^\\d+\$/", $_POST["shares"] === false)) {
                apologize("Please give a positive number of shares.");
            } else {
                // make sure symbol is valid
                $symbup = strtoupper($_POST["symbol"]);
                if ($symbol = lookup($symbup) === false) {
                    apologize("This is not a valid stock symbol. Try again!");
                } else {
                    $stock = lookup($symbup);
                    $symbol = $stock["symbol"];
                    $id = $_SESSION["id"];
                    $cash = query("SELECT cash FROM users WHERE id = {$id}");
                    $shares = $_POST["shares"];
                    $price = $stock["price"];
                    $cost = $price * $shares;
                    // verify sufficient cash
                    if ($cost > $cash[0]["cash"]) {
                        apologize("You have insufficient cash to buy this number of the desired shares. Please modify your buying order!");
                    } else {
                        // process the acquisition
                        query("INSERT INTO portfolio (id, symbol, shares) VALUES({$id}, '{$symbol}', {$shares}) \n     \t\t        ON DUPLICATE KEY UPDATE shares = shares + {$shares}");
                        query("UPDATE users SET cash = cash - {$cost} WHERE id = {$id}");
                        query("INSERT INTO history (uid, symbol, shares, price, trans) VALUES ({$id}, '{$symbol}', {$shares}, {$price}, 'BUY')");
                        // confirm the acquisition
Esempio n. 27
0
require "../includes/config.php";
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    $cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
    render("comprar_form.php", ["cash" => $cash[0]["cash"], "nombreUsuario" => $_SESSION["nombreUsuario"], "title" => "Comprar"]);
} else {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        /* Verificar nombre se usuario y contraseña correcta */
        if (empty($_POST["simbolo"])) {
            apologize("¡Debes ingresar un simbolo!");
        } else {
            if (empty($_POST["cantidad"])) {
                apologize("¡Debes ingresar una cantidad!");
            } else {
                // insertar un nuevo usuario a la base de datos
                $stock = lookup($_POST["simbolo"]);
                if ($stock === false) {
                    apologize("¡El simbolo es incorrecto!");
                } else {
                    if (preg_match("/^\\d+\$/", $_POST["cantidad"])) {
                        $filas = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
                        // calcular el costo
                        $costo = $stock["price"] * $_POST["cantidad"];
                        // verificar cantidad de cash
                        if ($costo > $filas[0]["cash"]) {
                            apologize("¡No Tiene sufuciente cash!");
                        } else {
                            $_POST["simbolo"] = strtoupper($_POST["simbolo"]);
                            query("INSERT INTO portfolios (id, simbolo, shares) VALUES (?, ? ,?)\n\t\t\t\t\tON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", $_SESSION["id"], $_POST["simbolo"], $_POST["cantidad"]);
                            query("UPDATE users SET cash = cash - ? WHERE id = ?", $stock["price"] * $_POST["cantidad"], $_SESSION["id"]);
                            // Actualizar historial
Esempio n. 28
0
<?php

require_once "../includes/config.php";
$id = $_SESSION["id"];
$userquery = query("SELECT * FROM users WHERE id  = ?", $id);
$cash = $userquery[0]["cash"];
if (empty($_POST["symbol"]) || empty($_POST["sellshares"])) {
    render("../templates/sell_form.php", ["title" => "Get Quote", "cash" => $cash]);
} else {
    $stocksym = strtoupper($_POST["symbol"]);
    $stocklook = lookup($stocksym);
    $shareprice = $stocklook["price"];
    $sellshares = $_POST["sellshares"];
    $transtype = "SELL";
    if ($stocklook["name"] == "N/A") {
        apologize("The stock symbol you entered does not exist!");
        break;
    }
    if (!is_numeric($sellshares)) {
        apologize("Please enter the number of shares you want to sell!");
        break;
    }
    $idquery = query("SELECT * FROM stocks WHERE id  = ? AND symbol = ?", $id, $stocksym);
    $sharesowned = $idquery[0]["shares"];
    // If query finds no rows w/ this id and stocksym, apologize
    if (empty($idquery)) {
        apologize("You don't own that stock!");
        break;
    } else {
        if ($sellshares > $sharesowned) {
            apologize("You don't own that many shares!");
Esempio n. 29
0
<?php

require "../includes/config.php";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    // else render form
    render("buy.php");
} else {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["symbol"])) {
            apologize("Something went wrong");
        }
        $stock = lookup($_POST["symbol"]);
        if ($stock === false) {
            apologize("Error ocurred - there are no shares with that symbol.");
        }
        if (!preg_match("/^\\d+\$/", $_POST["shares"])) {
            apologize("You can't buy fractions of shares or non-positive number of shares.");
        }
        $money = query("SELECT cash FROM users WHERE id =?", $_SESSION["id"]);
        if ($_POST["shares"] * $stock["price"] > $money[0]["cash"]) {
            apologize("I'm sorry, you can't afford so many shares.");
        }
        $_POST["symbol"] = strtoupper($_POST["symbol"]);
        date_default_timezone_set('Europe/Warsaw');
        $time = date('Y-m-d H:i:s');
        query("INSERT INTO usersStocks (id, symbol, shares) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE shares = shares + ?", $_SESSION["id"], $_POST["symbol"], $_POST["shares"], $_POST["shares"]);
        query("UPDATE users SET cash = cash - ? WHERE id =?", $_POST["shares"] * $stock["price"], $_SESSION["id"]);
        query("INSERT INTO history (id, symbol, shares, transaction, price, time) VALUES (?, ?, ?, 'BUY', ?, ?)", $_SESSION["id"], $_POST["symbol"], $_POST["shares"], $stock["price"], $time);
        $users = query("SELECT * FROM users WHERE id =?", $_SESSION["id"]);
        $address = $users[0]["mail"];
        require_once "libphp-phpmailer/class.phpmailer.php";
Esempio n. 30
0
<?php

// configuration
require "../includes/config.php";
// if we get called via POST containing a quote, then we pass it on
// for display
if (isset($_POST["quote"])) {
    $quote = lookup($_POST["quote"]);
    render("quote.php", ["title" => "Quote", "quote" => $quote]);
} else {
    if (isset($quote)) {
        unset($quote);
    }
    render("quote.php", ["title" => "Quote"]);
}