Example #1
0
function validateImageFile()
{
    $isValid = true;
    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["picToUpload"]["tmp_name"]);
    if ($check !== false) {
        $isValid = true;
    } else {
        sendResponse('INVALID_IMAGE', 'error');
        $isValid = false;
        return $isValid;
    }
    // Check file size
    if ($_FILES["picToUpload"]["size"] / 1024 / 1024 > 5) {
        sendResponse('FILE_SIZE_EXCEEDED', 'error');
        $isValid = false;
        return $isValid;
    }
    // Allow certain file formats
    $imageFileType = $check["mime"];
    if ($imageFileType != "image/jpg" && $imageFileType != "image/png" && $imageFileType != "image/jpeg" && $imageFileType != "image/gif") {
        sendResponse('UNSUPPORTED_IMAGE_FORMAT', 'error');
        $isValid = false;
        return $isValid;
    }
    return $isValid;
}
Example #2
0
 function onErrorResponseFromHandlers($response)
 {
     //
     // transfer some fields from the request to the response
     //
     print "got a response from a handler";
     sendResponse($response);
 }
Example #3
0
function sanitizeResult($result, $code = 200)
{
    if (count($result) > 0) {
        sendResponse($code, json_encode($result));
        return true;
    } else {
        sendResponse($code, json_encode("ERROR"));
        return true;
    }
}
Example #4
0
function listar()
{
    require "../models/imagen.php";
    $img = new Imagen();
    if ($imagenes = $img->getAll()) {
        sendResponse(array("error" => false, "mensaje" => "", "data" => $imagenes));
    } else {
        sendResponse(array("error" => true, "mensaje" => "Error al obtener imágenes"));
    }
}
function obtenerCantidadTweets($request)
{
    require "../models/comentario.php";
    $c = new Comentario();
    $id = $request->id;
    if ($cantidad = $c->getCantidad($id)) {
        sendResponse(array("error" => false, "mensaje" => "", "data" => $cantidad));
    } else {
        sendResponse(array("error" => true, "mensaje" => "Error al obtener la cantidad de tweets."));
    }
}
Example #6
0
function addData($name, $detail, $price, $qty)
{
    $conn = connectDB("localhost", "root", "root", "dbData");
    if (!$conn) {
        sendResponse("error", "เกิดปัญหาในการติดต่อฐานข้อมูล");
        return;
    }
    $sql = "insert into products (id, name,  detail, price, qty) values ('', '{$name}','{$detail}', {$price}, \n{$qty})";
    mysqli_query($conn, $sql) or die(sendResponse("error", "บันทึกข้อมูลไม่ได้") . $sql);
    sendResponse("success", "บันทึกข้อมูลเรียบร้อยแล้ว");
    $sqlStr = "select * from products order by  id asc";
    $qry = mysqli_query($conn, $sqlStr) or die(sendResponse("error", "ไม่พบข้อมูล"));
    ?>
 
<table width="600" border="1" cellspacing="2" cellpadding="5"> 
  <tr> 
    <td>รหัสสินค้า</td> 
    <td>ชื่อสินค้า</td> 
    <td>รายละเอียด</td> 
    <td>ราคา</td> 
    <td>จ านวน</td> 
  </tr> 
 <?php 
    while ($rs = mysqli_fetch_array($qry)) {
        ?>
 
  <tr> 
    <td><?php 
        echo $rs["id"];
        ?>
</td> 
    <td><?php 
        echo $rs["name"];
        ?>
</td> 
    <td><?php 
        echo $rs["detail"];
        ?>
</td> 
    <td><?php 
        echo $rs["price"];
        ?>
</td> 
    <td><?php 
        echo $rs["qty"];
        ?>
</td> 
  </tr> 
  <?php 
    }
    mysqli_close($conn);
}
 function gps_tracker_update()
 {
     $mysql_host = "mysql6.000webhost.com";
     $mysql_database = "a8399093_gps";
     $mysql_user = "******";
     $mysql_password = "******";
     if (isset($_POST["atti"]) && isset($_POST["lon"]) && isset($_POST['user'])) {
         try {
             $ati = $_POST["atti"];
             $lon = $_POST["lon"];
             $meUserid = $_POST['user'];
             $meAtti = sprintf("%01.4f", $ati);
             $meLon = sprintf("%01.4f", $lon);
             $mysqli = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
             if (mysqli_connect_errno()) {
                 echo "Connection Failed: " . mysqli_connect_errno();
                 exit;
             }
             /* Create a prepared statement */
             $sql = "INSERT INTO location (time , user_id ,atti, lon) VALUES (NOW(),?,?,?)";
             $message = "";
             $stmt = $mysqli->prepare($sql);
             //$message .= $stmt . "  ";
             if ($stmt) {
                 /* Bind parameters
                 		 s - string, b - boolean, i - int, etc */
                 $stmt->bind_param('idd', $meUserid, $meAtti, $meLon);
                 /* Execute it */
                 $stmt->execute();
                 $message .= "updated";
                 /* Close statement */
                 $stmt->close();
             } else {
                 /* Error */
                 printf("Prepared Statement Error: %s\n", $mysqli->error);
             }
             /* Close connection */
             $mysqli->close();
             //mysql_close($con);
             $message .= $meAtti . " " . $meLon . " " . $meUserid;
             //mail('*****@*****.**', '$subject', $message);
             sendResponse(200, $message);
             return true;
         } catch (Exception $e) {
             $err = 'Caught exception: ' . $e->getMessage() . "\n";
             sendResponse(200, $err);
             return false;
         }
     }
     sendResponse(400, 'Invalid request');
     return false;
 }
function getUser()
{
    $db = getDB();
    $app = Slim::getInstance();
    // used for degugging if desired.
    $startTime = time();
    $results = Users::getUser($db);
    if (!$results) {
        return;
    }
    // User ID is private so don't send it back to the client
    unset($results->user_id);
    sendResponse($results, $startTime);
}
Example #9
0
function processUploadFile()
{
    $uploadFolder = 'cache/uploads/';
    if (!empty($_FILES)) {
        if (!file_exists($uploadFolder)) {
            @mkdir($uploadFolder);
        }
        $tempFile = $_FILES['file']['tmp_name'];
        $uploadedFile = $uploadFolder . md5($_FILES['file']['tmp_name']);
        move_uploaded_file($tempFile, $uploadedFile);
        sendResponse(array('success' => true, 'uploadFilename' => $uploadedFile, 'originalFilename' => $_FILES['file']['name']), false);
    } else {
        sendResponse('error', true);
    }
}
Example #10
0
function checkToken()
{
    $app = \Slim\Slim::getInstance();
    $token = $app->request->headers->get('token');
    $app = \Slim\Slim::getInstance();
    if ($token) {
        $db = new dbHandler();
        if ($db->isValidToken($token)) {
            return true;
        } else {
            sendResponse(401, initBody(true, "Bad token"), null);
            $app->stop();
        }
    } else {
        sendResponse(401, initBody(true, "Token is missing"), null);
        $app->stop();
    }
}
 function gps_tracker_login()
 {
     $mysql_host = "mysql6.000webhost.com";
     $mysql_database = "a8399093_gps";
     $mysql_user = "******";
     $mysql_password = "******";
     if (isset($_POST["email"]) && isset($_POST["password"])) {
         try {
             $con = mysql_connect($mysql_host, $mysql_user, $mysql_password);
             if (!$con) {
                 die('Could not connect: ' . mysql_error());
             }
             mysql_select_db($mysql_database, $con);
             $email = $_POST["email"];
             $password = $_POST["password"];
             $sql = "SELECT * FROM user WHERE email='{$email}' and password='******'";
             //echo $sql;
             $result = mysql_query($sql);
             //echo $result;
             // Mysql_num_row is counting table row
             $count = mysql_num_rows($result);
             // If result matched $myusername and $mypassword, table row must be 1 row
             $message = NULL;
             if ($count == 1) {
                 $row = mysql_fetch_array($result, MYSQL_ASSOC);
                 $message = $row['id'];
             } else {
                 $message = "Wrong Username or Password";
             }
             //mail('*****@*****.**', '$subject', $message);
             sendResponse(200, $message);
             return true;
         } catch (Exception $e) {
             $err = 'Caught exception: ' . $e->getMessage() . "\n";
             sendResponse(200, $err);
             return false;
         }
     }
     sendResponse(400, 'Invalid request');
     return false;
 }
Example #12
0
 function doWork()
 {
     try {
         if (!isset($_POST["operation"])) {
             $result = array("response" => 'failure', "error" => 'Invalid request. No operation given.', "POST" => $_POST);
             sendResponse(400, json_encode($result));
             return false;
         }
         $op = $_POST["operation"];
         //check which method we want to call
         if ($op == "testConnection") {
             return $this->testConnection();
         }
         switch ($op) {
             case "login":
                 // do some stuff
                 if (login($db, $_POST['username'], $_POST['userID']) == 200) {
                     $result = array("response" => 'User created!');
                     sendResponse(200, json_encode($result));
                     return true;
                 } else {
                     $result = array("response" => 'Server error: unable to create user');
                     sendResponse(500, json_encode($result));
                     return true;
                 }
                 break;
             default:
                 break;
         }
         $result = array("response" => 'Invalid request. Not a valid operation.');
         sendResponse(400, json_encode($result));
         return false;
     } catch (Exception $e) {
         $error = array("response" => 'failure', "message" => 'Server exception: ' . $e->getMessage());
         sendResponse(500, json_encode($error));
         return false;
     }
 }
Example #13
0
    //Take and validate input param only accepting integers between 1 and 3999
    if (!($input = filter_input(INPUT_GET, 'input', FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 3999))))) {
        //Set HTTP response
        $response['code'] = 3;
        $response['status'] = $apiResponseCodes[$response['code']]['HTTP Response'];
        $response['message'] = $apiResponseCodes[$response['code']]['Message'];
        $response['result'] = NULL;
        //Send response to browser
        sendResponse($response);
    }
    $response['code'] = 1;
    $response['status'] = $apiResponseCodes[$response['code']]['HTTP Response'];
    $response['message'] = $apiResponseCodes[$response['code']]['Message'];
    $response['result'] = $oConverter->generate($input);
} elseif (strcasecmp($action, 'parse') == 0) {
    //Take and validate input param only accepting valid roman numbers
    if (empty($_GET['input']) || !($input = filter_input(INPUT_GET, 'input', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/'))))) {
        $response['code'] = 4;
        $response['status'] = $apiResponseCodes[$response['code']]['HTTP Response'];
        $response['message'] = $apiResponseCodes[$response['code']]['Message'];
        $response['result'] = NULL;
    } else {
        $response['code'] = 1;
        $response['status'] = $apiResponseCodes[$response['code']]['HTTP Response'];
        $response['message'] = $apiResponseCodes[$response['code']]['Message'];
        $response['result'] = $oConverter->parse($input);
    }
}
//Send response to browser
sendResponse($response);
Example #14
0
<?php

require 'class.db.php';
if (isset($_POST["values"]) && isset($_POST["type"]) && isset($_POST["interferer"]) && isset($_POST["flag"])) {
    $values = json_decode($_POST["values"]);
    $type = $_POST["type"];
    $interferer = $_POST["interferer"];
    $flag = $_POST["flag"];
    if ($flag == "false") {
        $interferer = "";
    }
    foreach ($values as $item) {
        $update = array('interfereBy' => $interferer);
        //Add the WHERE clauses
        $where_clause = array('companyName' => $item);
        $updated = $database->update('Transaction', $update, $where_clause);
    }
    sendResponse(200, json_encode(array('isSucceed' => $updated)));
} else {
    //    echo "FAILED";
    sendResponse(200, json_encode(array('isSucceed' => false)));
}
Example #15
0
$aes = new \RNCryptor\Decryptor();
//Load the encrypted private key from hard drive
$filename = substr($userKey, -10) . ".txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
unlink($filename);
//Decrypt the private key
$privKey = $aes->decrypt($contents, substr($userKey, 0, 256));
//Decrypt the aes key with RSA and the private key
$rsa = new RSA('', $privKey);
$password = $rsa->decrypt($ePassword);
//Decrypt the data with the aes key and iv
$data = $aes->decrypt($eData, $password);
function getStatusCodeMessage($status)
{
    $codes = parse_ini_file("codes.ini");
    return isset($codes[$status]) ? $codes[$status] : '';
}
function sendResponse($status, $body = '', $content_type = 'text/html')
{
    $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}
sendResponse(201, '<?xml version="1.0" encoding="UTF-8"?>
                <Root>
                    <Success>Yes</Success>
                    <Data>' . $data . '</Data>
                    <Password>' . $password . '</Password>
                </Root>');
        $response["response"] = "success";
        http_response_code(200);
        break;
    case 'POST':
        $response["response"] = "failure";
        http_response_code(403);
        break;
    case 'PUT':
        if (checkHeaders() === true) {
            $json = readBody();
            if (!isset($json['action']) or $json['action'] !== $resource) {
                $response["response"] = "failure";
                http_response_code(400);
            } else {
                $q = "UPDATE " . GAMEROOMS . " SET " . GAMEROOMS . ".state='STARTED' WHERE " . GAMEROOMS . ".id='{$json['gameRoom']}'";
                queryDB($q);
                $response["response"] = "success";
                http_response_code(200);
            }
        } else {
            $response["response"] = "failure";
            http_response_code(400);
        }
        break;
    default:
        $response["response"] = "failure";
        http_response_code(403);
        break;
}
sendResponse();
Example #17
0
function stopAndResponse($type, array $data)
{
    sendResponse($type, $data);
    exit;
}
Example #18
0
<?php

require_once "../includes/initialize.php";
// require key and id parameter.
if (empty($_GET['q']) || empty($_GET['key'])) {
    sendResponse(400, "Invalid request. Please provide \"q\" and \"key\" parameters.");
} else {
    if ($_GET['key'] != API_KEY) {
        sendResponse(403, "Invalid API key.");
    } else {
        $searchTerm = $database->escape_value($_GET['q']);
        $sql = "SELECT * FROM movies WHERE title LIKE '% {$searchTerm}%' OR title LIKE '{$searchTerm}%' ORDER BY popularity DESC LIMIT 6";
        $movies = Movie::find_by_sql($sql);
        $results = array();
        foreach ($movies as $movie) {
            $results[] = $movie->export();
        }
        $popular = array("movies" => $results);
        sendResponse(200, json_encode($popular));
    }
}
Example #19
0
<?php

require_once 'inc/MCAPI.class.php';
require_once 'inc/config.inc.php';
//contains apikey
require_once 'inc/response.helpers.php';
if (isset($_POST["UEmail"])) {
    // Put parameters into local variables
    $UEmail = $_POST["UEmail"];
    $api = new MCAPI($apikey);
    $double_optin = false;
    $send_welcome = false;
    $merge_vars = array('groups' => 'Hope5k');
    $retval = $api->listSubscribe($listId, $UEmail, $merge_vars, $double_optin, $send_welcome);
    $result = array("message" => $api->errorCode);
    if ($api->errorCode) {
        sendResponse(666, $api->errorMessage);
        return false;
    } else {
        sendResponse(200, json_encode($result));
        return true;
    }
}
sendResponse(400, 'Invalid request');
return false;
?>


  
Example #20
0
    } else {
        $query = "SELECT DISTINCT companyName, interfereBy FROM `Transaction` WHERE pickupType = '" . $type . "' AND pickupBy=''";
    }
    $results = $database->get_results($query);
    foreach ($results as $row) {
        array_push($result1, $row["companyName"]);
        array_push($result2, $row["interfereBy"]);
    }
    $isSucceed = true;
}
//if($type == "done"){
//  $query = "SELECT DISTINCT companyName FROM `Transaction` WHERE pickupBy != ''";
//  $results = $database->get_results( $query );
//  foreach( $results as $row )
//  {
//      array_push($result, $row["companyName"]);
//  }
//  $isSucceed = true;
//}else if($type == "emergency" || $type == "regular"){
//    $isEmergency = 0;
//    if($type == "emergency")$isEmergency=1;
//     $query = "SELECT DISTINCT companyName FROM `Transaction` WHERE isEmergency = " . $isEmergency;
//     $results = $database->get_results( $query );
//  foreach( $results as $row )
//  {
//      array_push($result, $row["companyName"]);
//  }
//  $isSucceed = true;
//}
sendResponse(200, json_encode(array('isSucceed' => $isSucceed, 'Company' => $result1, 'Interferer' => $result2)));
Example #21
0
}
function sendResponse($calltype, $result)
{
    header("Content-type: application/json");
    echo json_encode(array($calltype => $result));
}
function buildError($errname, $errdata)
{
    return array("error" => array($errname, $errdata));
}
if (!class_exists('Magmi_Plugin')) {
    if (!isset($_REQUEST['api'])) {
        header('Status 406 : Unauthorized call', true, 406);
        exit;
    }
    $api = $_REQUEST['api'];
    if (!in_array($api, array_keys(Magmi_RemoteAgent::$apidesc))) {
        header('Status 406 : Unauthorized call', true, 406);
        exit;
    }
    $missing = Magmi_RemoteAgent::checkParams($_REQUEST, $api);
    if (count($missing) > 0) {
        header('Status 400 : Invalid parameters', true, 400);
        $error = buildError("missing mandatory parameters", implode(",", $missing));
        sendResponse($api, $error);
    } else {
        $mra = Magmi_RemoteAgent::getInstance();
        $result = $mra->{$api}($_REQUEST);
        sendResponse($api, $result);
    }
}
Example #22
0
                            } else {
                                $moved = move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "/upload/" . $_FILES["file"]["name"]);
                                if ($moved) {
                                    $response["NoError"] = "Stored in: " . getcwd() . "/upload/" . $_FILES["file"]["name"];
                                } else {
                                    $response["errorUploading"] = "Return Code: " . $_FILES["file"]["error"];
                                }
                            }
                        }
                    }
                    sendResponse(200, json_encode($response));
                } else {
                    // user failed to store
                    $response["error"] = 1;
                    $response["error_msg"] = "Error occurred in Registration";
                    sendResponse(4, json_encode($response));
                }
            }
        } else {
            echo "Invalid Request";
        }
    }
} else {
    echo "Access Denied";
}
//
//
//    $response = array("tag" => $tag, "success" => 0, "error" => 0);
//
//
//
Example #23
0
File: api.php Project: LegalEye/API
/**
 *  Handler function for GET /events/:SESSION/attachments/:ID
 *
 * Receives attachment(s), saves to disk, and adds to database. Renews API
 * key when file received.
 *
 * @todo Move the upload location outside the webroot.
 *
 * @param string $id Session ID provided by the dispatcher.
 *
 * @throws ApiKeyNotPrivilegedException
 * @throws DatabaseInsertQueryFailedException
 * @throws DatabaseInvalidQueryTypeException
 * @throws DatabaseNothingSelectedException
 * @throws DatabaseRowNotInsertedException
 * @throws DatabaseSelectQueryFailedException
 * @throws DatabaseStatementNotPreparedException
 * @throws InvalidIdentifierException
 * @throws NoFilesProvidedException
 * @throws WhatTheHeckIsThisException
 */
function api_EVENTS_POST_ID_ATTACHMENTS($id)
{
    global $database;
    if (!isset($id) || strlen($id) != 8) {
        throw new InvalidIdentifierException();
    }
    if (!getPermission("UPLOAD", getScopeByEventSession($id))) {
        throw new ApiKeyNotPrivilegedException();
    }
    if (empty($_FILES)) {
        throw new NoFilesProvidedException();
    }
    $status = ['data' => [], 'error' => ['count' => 0]];
    $sqlQuery = <<<EOF

        SELECT
            eventkey
        FROM
            tbl__events
        WHERE
            session=?
        LIMIT 1

EOF;
    $sessionkey = $database->select($sqlQuery, [["s" => $id]])[0]['eventkey'];
    $pattern = '/' . str_replace('\\', '\\\\', $_SERVER['DOCUMENT_ROOT']) . '\\/(.+)(?=\\\\.+\\.php$)/';
    preg_match($pattern, $_SERVER['SCRIPT_FILENAME'], $matches);
    // $baseDir = $matches[1];
    $baseDir = __DIR__;
    $i = 0;
    foreach ($_FILES as $file) {
        // $status['data']['files'][ $i ]['trace'] = $file;
        if ($file['error'] > 0) {
            $status['data']['files'][$i]['error'] = $file['error'];
            $status['error']['count']++;
        } else {
            $destination = $baseDir . DIRECTORY_SEPARATOR . 'up' . DIRECTORY_SEPARATOR . $id . '_' . $file['name'];
            if (!move_uploaded_file($file['tmp_name'], $destination)) {
                $status['data']['files'][$i]['error'] = "Failed to move \n                `{$file['tmp_name']}` to permanent storage.";
                $status['error']['count']++;
            } else {
                $sqlQuery = <<<EOF

                    INSERT INTO
                        tbl__files
                    (
                        eventkey,
                        filename,
                        filepath
                    )
                    VALUES
                    (?, ?, ?)

EOF;
                $database->insert($sqlQuery, [['i' => $sessionkey], ['s' => $file['name']], ['s' => $destination]]);
                //chmod($destination, 0644);
                $status['data']['files'][$i]['name'] = $file['name'];
            }
        }
        $i++;
    }
    if ($status['error']['count'] == 0) {
        // Everything Worked
        $status['status']['code'] = 200;
    } elseif ($status['error']['count'] == count($status['data']['files'])) {
        // Everything failed.
        $status['status']['code'] = 500;
    } else {
        // Mixed Results
        $status['status']['code'] = 207;
    }
    try {
        if (getPermission("RENEW", getScopeByEventSession($id))) {
            $sqlQuery = <<<EOF

                UPDATE
                    tbl__apikeys
                SET
                    expiration = DATE_ADD(NOW(), INTERVAL 1 HOUR),
                    last_renewal = NOW()
                WHERE
                    scope='EVENT'
                AND scopekey=(SELECT eventkey FROM tbl__events WHERE session=?)
                AND is_expired=0

EOF;
            try {
                //                $eventQuery =
                $database->update($sqlQuery, [['s' => $id]]);
            } catch (DatabaseInsertQueryFailedException $e) {
                //$lastError = print_r($e, true);
            }
        }
    } catch (LeagleEyeException $e) {
        $status['error']['apiKeyRenewalError'] = $e->getResponse();
    }
    sendResponse($status);
}
    sendResponse("report_error");
}
// END - Michael
//send email
// BEGIN - 2009/05/29
// Check if there was an error sending the email.
if (!sendReportEmail($to, $from, $message, $html = true, $subject, $wordWrap = 120, $pfile, $filename . $ext, $receipt)) {
    sendResponse("email_error");
}
// END - 2009/05/29 - Michael
//debug email
//sendReportEmail('*****@*****.**', '*****@*****.**', $fqurl, $html = true, 'debug', $wordWrap = 120, $pfile, $filename.$ext);
//delete file
@unlink($pfile);
// 2009/05/29 - Michael
sendResponse($form_ses);
//set cookie
function sendReportEmail($to, $from = "*****@*****.**", $content = "nuBuilder Email", $html = false, $subject = "", $wordWrap = 120, $filesource, $filename, $receipt = "false")
{
    $mail = new PHPMailer();
    // BEGIN - 2009/06/09 - Michael
    switch ($GLOBALS["NUMailMethod"]) {
        // Use the sendmail binary.
        case "sendmail":
            $mail->IsSendmail();
            break;
            // case
            // Use an SMTP server to send the mail.
        // case
        // Use an SMTP server to send the mail.
        case "smtp":
Example #25
0
 * 	token: {OpenTok subscriber token for `session_id`},
 * 	id: {Database ID for `session_id`}]
 * }
 */
require_once 'common.inc.php';
use OpenTok\Role;
requiredParameters([PARAM_CONTEXT, PARAM_USER, PARAM_USER_NAME]);
$apiResponse = [];
if (($groupSessions = $_SESSION['app']->sql->query("\n    SELECT s.*\n        FROM `group_memberships` AS m\n            LEFT JOIN `groups` AS g ON m.`group` = g.`id`\n            LEFT JOIN `sessions` AS s ON g.`session` = s.`id`\n        WHERE\n            m.`context` = '" . $_SESSION['app']->sql->escape_string($_REQUEST[PARAM_CONTEXT]) . "' AND\n            m.`user` = '" . $_SESSION['app']->sql->escape_string($_REQUEST[PARAM_USER]) . "'\n        LIMIT 1\n")) === false) {
    databaseError(__LINE__);
}
if ($group = $groupSessions->fetch_assoc()) {
    $apiResponse[API_DATABASE_ID] = $group['id'];
    $apiResponse[API_SESSION_ID] = $group['tokbox'];
} else {
    if (($classSessions = $_SESSION['app']->sql->query("\n        SELECT *\n            FROM `sessions`\n            WHERE\n                `type` = '" . TYPE_CLASS . "' AND\n                `context` = '" . $_SESSION['app']->sql->escape_string($_REQUEST[PARAM_CONTEXT]) . "'\n            LIMIT 1\n    ")) === false) {
        databaseError(__LINE__);
    }
    if ($classSession = $classSessions->fetch_assoc()) {
        $apiResponse[API_DATABASE_ID] = $classSession['id'];
        $apiResponse[API_SESSION_ID] = $classSession['tokbox'];
    } else {
        $apiResponse = [];
    }
}
if (!empty($apiResponse[API_SESSION_ID])) {
    $apiResponse[API_KEY] = $_SESSION['app']->config->toString('//tokbox/key');
    $apiResponse[API_SESSION_TOKEN] = $_SESSION['app']->opentok->generateToken($apiResponse[API_SESSION_ID], ['role' => Role::PUBLISHER, 'data' => json_encode(['context' => $_REQUEST[PARAM_CONTEXT], 'user' => $_REQUEST[PARAM_USER], 'user_name' => $_REQUEST[PARAM_USER_NAME]])]);
}
sendResponse($apiResponse);
Example #26
0
                $subnode = $xml->addChild("{$key}");
                array_to_xml($value, $subnode);
            } else {
                $subnode = $xml->addChild("item{$key}");
                array_to_xml($value, $subnode);
            }
        } else {
            $xml->addChild("{$key}", htmlspecialchars("{$value}"));
        }
    }
}
$num = 0;
foreach ($row as $post) {
    $pLat = $post['latitude'];
    $pLong = $post['longitude'];
    if (distanceBetweenPostAndUser($pLat, $pLong, $userLat, $userLong) <= 160000) {
        array_push($postsToDisplay, $post);
        $num++;
    }
}
//Convert $postsToDisplay here into XML to send to the client
$postXML = new SimpleXMLElement('<?xml version="1.0"?><Root></Root>');
array_to_xml($postsToDisplay, $postXML);
$postStr = $postXML->asXML();
//Send back the posts to be displayed
sendResponse(201, '<?xml version="1.0" encoding="UTF-8"?>
            <Root>
                <Success>Yes</Success>
                <Data>' . str_replace('<', '@', $postStr) . '</Data>
                <Number>' . $num . '</Number>
            </Root>');
Example #27
0
    $client = gfGetClient();
    $service = new Google_Service_Drive($client);
    foreach ($fileDetails["files"] as $file) {
        $fileInfo = gfUploadFile($client, $service, LOCAL_FILE_DIR, $file->name, $file->type, $fileDetails["uploadDir"]);
        $file->{"googleDriveUrl"} = $fileInfo["alternateLink"];
        $file->{"googleDriveId"} = $fileInfo["id"];
    }
    return $fileDetails;
}
function sendResponse($response)
{
    echo json_encode($response);
    return $response;
}
function deleteFromGoogleDrive($id)
{
    $client = gfGetClient();
    $service = new Google_Service_Drive($client);
    return gfDeleteFile($service, $id);
}
switch ($_SERVER['REQUEST_METHOD']) {
    case "POST":
        $fileDetails = sendResponse(uploadToGoogleDrive(getLocalFileDetails()));
        removeProcessedFiles($fileDetails);
        break;
    case "GET":
        sendResponse(deleteFromGoogleDrive($_GET["delete"]));
}
?>

Example #28
0
});
$app->get('/trainers/:id/badges', function ($id) use($app) {
    $trainer = Trainer::getById($id);
    sendResponse($trainer->getBadges());
});
$app->get('/gyms', function () use($app) {
    sendResponse(Gym::getAll());
});
$app->get('/gyms/:id', function ($id) use($app) {
    $gym = Gym::getById($id);
    sendResponse($gym->serialize());
});
$app->get('/gyms/:id/leader', function ($id) use($app) {
    $gym = Gym::getById($id);
    sendResponse($gym->getLeader()->serialize());
});
$app->get('/types', function () use($app) {
    sendResponse(Type::getAll());
});
$app->get('/types/:id', function ($id) use($app) {
    $type = Type::getById($id);
    sendResponse($type->serialize());
});
$app->get('/badges', function () use($app) {
    sendResponse(Badge::getAll());
});
$app->get('/badges/:id', function ($id) use($app) {
    $badge = Badge::getById($id);
    sendResponse($badge->serialize());
});
$app->run();
Example #29
0
	$girls = (int)$_POST['girls'];
	
	$looking = ' ';
	
	
		if($guys > 0 && $girls > 0)
		{
			//both
			$looking = 'b';
		}
		else if($guys > 0)
		{
			//just guys
			$looking = 'm';
		}
		else if($girls > 0)
		{
			//just girls
			$looking = 'f';
		}

	//OK
	$User->setLooking($looking);
	
	//Set the status to 1 (success)
	$response['meta']['status'] = 1;

	//Send the response
	sendResponse(200, json_encode($response));
	return true;
?>
<?php

require_once '../../includes/init.php';
session_start();
$req = new Zend_Controller_Request_Http();
$config = getConfig($req->uuid);
if (empty($config)) {
    sendResponse(false);
}
$captcha = $_SESSION['captcha_keystring'];
$isCaptchaOk = $config->isPassCaptcha || $captcha && $req->captcha == $captcha;
if (!$isCaptchaOk) {
    $_SESSION['captcha_keystring'] = null;
    exit(Zend_Json::encode(array('result' => false, 'code' => 'badCaptcha', 'message' => $config->badCaptcha)));
}
$body = $req->getParam('message', '');
$fromEmail = null;
foreach ($config->fields as $field) {
    if (!$fromEmail && $field->type == 'email') {
        $fromEmail = $req->getParam($field->name, '');
    }
    if (in_array($field->name, array('message'))) {
        continue;
    }
    $body .= "\n{$field->title}: " . $req->getParam($field->name, '');
}
$mail = new Zend_Mail('utf-8');
$mail->addHeader('X-Mailer', 'Parallels Web Presence Builder');
$mail->setBodyText($body);
if ($fromEmail) {
    $mail->setFrom($fromEmail, $req->name ? $req->name : '');