Esempio n. 1
0
/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
function authenticate(\Slim\Route $route)
{
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();
    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        $db = new DbHandler();
        // get the api key
        $api_key = $headers['Authorization'];
        // validating api key
        if (!$db->isValidApiKey($api_key)) {
            // api key is not present in users table
            $response["error"] = true;
            $response["message"] = "Acesso negado.";
            echoResponse(401, $response);
            $app->stop();
        } else {
            global $user_id;
            // get user primary key id
            $user = $db->getUserByApiId($api_key);
            if ($user != NULL) {
                $user_id = $user["id"];
            }
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key necessária";
        echoResponse(400, $response);
        $app->stop();
    }
}
Esempio n. 2
0
function getStocksMaterials($id_location)
{
    global $db;
    $constant = 'constant';
    $rows = $db->selectComplex("\n        SELECT gs.id_stock, gs.id_location, gs.id_article as gs_id_article, gs.quantite_current,\n        gs.stock_alert, gs.stock_min, gs.type_stock, gs.status , ga.id_article, ga.nom, ga.code_barre,\n        ga.description_f, ga.id_family, ga.mark, ga.vat, ga.unite, ga.type_article,\n        gl.description_f as name_location, gf.description as name_family\n        FROM gestion_stock gs\n            LEFT JOIN gestion_article ga\n                ON ga.id_article = gs.id_article\n            LEFT JOIN gestion_location gl\n                ON gl.id_location = gs.id_location\n            LEFT JOIN gestion_family gf\n                ON gf.id_family = ga.id_family\n        WHERE ga.id_service = {$constant('TRAVAUX_SERVICE')}\n            AND gs.type_stock = 'MATERIAL'\n            AND gs.id_location = {$id_location}\n    ");
    echoResponse(200, $rows);
}
Esempio n. 3
0
 /**
  *  Gets the current session if exists
  */
 public static function RestictedAccess($level = false)
 {
     if (!isset($_SESSION['isLogged']) || !$_SESSION['isLogged']) {
         echoResponse(401);
     }
     //TODO: change hardcoded level name
     if ($level === 'admin' && !$_SESSION['isAdmin']) {
         echoResponse(401);
     }
 }
Esempio n. 4
0
function validateEmail($email)
{
    $app = \Slim\Slim::getInstance();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response["error"] = true;
        $response["message"] = 'Email address is not valid';
        echoResponse(400, $response);
        $app->stop();
    }
}
/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Api-Key' header
 */
function mw_auth()
{
    // Master DB
    include_once SessionData::getInstance()->getRootDir() . '/config/database.php';
    ORM::configure('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . '');
    ORM::configure('username', DB_USERNAME);
    ORM::configure('password', DB_PASSWORD);
    ORM::configure('logging', true);
    ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
    ORM::reset_db();
    // Datum setzen
    date_default_timezone_set('Europe/Berlin');
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();
    // Verifying Authorization Header
    if (isset($headers['Api-Key'])) {
        $apikey = $headers['Api-Key'];
        // API-KEY vorhanden?
        $user = ORM::for_table('user')->where('api_key', $apikey)->find_one();
        if ($user != null) {
            // API aktiviert?
            if ($user['active'] == 1) {
                // Everything is OK
                // Set Session Data
                SessionData::getInstance()->setUserId($user['id']);
            } else {
                $response["error"] = true;
                $response["message"] = "API-Key not activated!";
                echoResponse(400, $response);
                $app->stop();
            }
        } else {
            $response["error"] = true;
            $response["message"] = "API-KEY unknown!";
            echoResponse(400, $response);
            $app->stop();
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key is missing";
        echoResponse(400, $response);
        $app->stop();
    }
}
Esempio n. 6
0
function authenticateToken()
{
    global $db;
    $app = \Slim\Slim::getInstance();
    $headers = apache_request_headers();
    $token;
    foreach ($headers as $header => $value) {
        if ($header == 'Authorization') {
            $token = str_replace('"', "", $value);
        }
    }
    $tokenFromDB = Users_model::get_user_by_token($db, $token);
    if (!$tokenFromDB) {
        echoResponse(403, $token);
        exit;
    }
}
Esempio n. 7
0
function putBatiments($id)
{
    global $app;
    $data = json_decode($app->request()->getBody());
    unset($data->save);
    unset($data->dt_creation);
    $dt_update = 'dt_update';
    $data->{$dt_update} = date("Y-m-d H:i");
    $condition = array('id_batiment' => $id);
    $mandatory = array();
    global $db;
    $rows = $db->update("gestion_batiment", $data, $condition, $mandatory);
    if ($rows["status"] == "success") {
        $rows["message"] = "Batiment information updated successfully.";
        $rows["dt_update"] = date("d-m-Y H:i");
    }
    echoResponse(200, $rows);
}
Esempio n. 8
0
function verifyRequiredParams($fields, $params)
{
    $error = false;
    $error_fields = '';
    foreach ($fields as $field) {
        if (!isset($params->{$field}) || strlen(trim($params->{$field})) < 1) {
            $error = true;
            $error_fields .= $field . ',';
        }
    }
    if ($error) {
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response['status'] = 'error';
        $response['message'] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
        echoResponse(200, $response);
        $app->stop();
    }
}
Esempio n. 9
0
/**
 * Verifying required params posted or not
 */
function verifyRequiredParams($required_fields, $request_params)
{
    $error = false;
    $error_fields = "";
    foreach ($required_fields as $field) {
        if (!isset($request_params->{$field}) || strlen(trim($request_params->{$field})) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }
    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response["status"] = "error";
        $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
        echoResponse(200, $response);
        $app->stop();
    }
}
Esempio n. 10
0
 function verifyRequiredParams($inArray, $requiredColumns)
 {
     $error = false;
     $errorColumns = "";
     foreach ($requiredColumns as $field) {
         // strlen($inArray->$field);
         if (!isset($inArray->{$field}) || strlen(trim($inArray->{$field})) <= 0) {
             $error = true;
             $errorColumns .= $field . ', ';
         }
     }
     if ($error) {
         $response = array();
         $response["status"] = "error";
         $response["message"] = 'Required field(s) ' . rtrim($errorColumns, ', ') . ' is missing or empty';
         echoResponse(200, $response);
         exit;
     }
 }
Esempio n. 11
0
                // Set last_login
                $user->last_login = time();
                // save user data
                $user->save();
                // role (fk)
                $role = ORM::for_table('role')->where('id', $user->role_id)->find_one();
                $response["role_id"] = $role->name;
                //name
                $role = ORM::for_table('role')->where('id', $user->role_id)->find_one();
                $response["user_name"] = $user->name;
                echoResponse(200, $response);
                $app->stop();
            } else {
                $response["error"] = true;
                $response["message"] = "Passwort falsch!";
                echoResponse(400, $response);
                $app->stop();
            }
        } else {
            $response["error"] = true;
            $response["message"] = "E-Mail Adresse unbekannt!";
            echoResponse(400, $response);
            $app->stop();
        }
    } else {
        $response["error"] = true;
        $response["message"] = "Bitte E-Mail und Passwort eingeben!";
        echoResponse(400, $response);
        $app->stop();
    }
});
Esempio n. 12
0
    include_once '../function/funcs.php';
    include_once '../configuration/ClassAsset.php';
    include_once '../configuration/ClassCustomer.php';
    $code = sanitizeInput($_POST['assetCode']);
    $type = sanitizeInput($_POST['assetType']);
    $brand = sanitizeInput($_POST['assetBrand']);
    $model = sanitizeInput($_POST['assetModel']);
    $site = sanitizeInput($_POST['assetSite']);
    $ip = sanitizeInput($_POST['assetIp']);
    $assignee = sanitizeInput($_POST['assetAssignee']);
    $asset = new Asset();
    $msg = $asset->createAsset($code, $type, $brand, $model, $site, $ip, $assignee);
    $customer = new Customer();
    $customer->getCustomerBy($assignee);
    $customer->addAssetList($code);
    echoResponse('yes', $msg);
}
//function: add asset to list
if (isset($_POST['updateAssetList'])) {
    include_once 'ClassCustomer.php';
    $assetCode = $_POST['assetCode'];
    $newCustomerID = $_POST['assetAssignee'];
    $originalCustomerID = $_POST['originalAssetAssignee'];
    if ($newCustomerID != $originalCustomerID) {
        $originalCustomer = new Customer();
        $originalCustomer->getCustomerBy($originalCustomerID);
        $originalCustomer->delAssetList($assetCode);
        $newCustomer = new Customer();
        $newCustomer->getCustomerBy($newCustomerID);
        $newCustomer->addAssetList($assetCode);
        echo $newCustomer->surname[0] . "," . $newCustomer->name[0];
Esempio n. 13
0
    echoResponse(200, $output);
});
$app->put('/devices/', function () use($app) {
    $body = $app->request->getBody();
    $params = json_decode($body);
    if (array_key_exists("deviceid", $params)) {
        if (array_key_exists("status", $params) && array_key_exists("level", $params)) {
            $output1 = shell_exec('./changestate.sh ' . $params->deviceid . ' ' . $params->status);
            $output2 = shell_exec('./changelevel.sh ' . $params->deviceid . ' ' . $params->level);
            echoResponse(200, '{' . $output1 . ',' . $output2 . '}');
        } else {
            if (array_key_exists("status", $params)) {
                $output = shell_exec('./changestate.sh ' . $params->deviceid . ' ' . $params->status);
                echoResponse(200, '{' . $output . '}');
            } else {
                if (array_key_exists("level", $params)) {
                    $output = shell_exec('./changelevel.sh ' . $params->deviceid . ' ' . $params->level);
                    echoResponse(200, '{' . $output . '}');
                } else {
                    echoResponse(200, '{"Response":"Must include a status or level"}');
                }
            }
        }
    } else {
        echoResponse(200, '{"Response":"Must include a deviceid"}');
    }
});
$app->get('/', function () use($app) {
    echoResponse(200, '{"Error":"Must include the deviceid"}');
});
$app->run();
Esempio n. 14
0
<?php

session_start();
require_once '../function/funcs.php';
if (isset($_POST['logout'])) {
    session_destroy();
    echoResponse('yes', 'Logged Out');
}
Esempio n. 15
0
function deleteRememberMeField($fieldName)
{
    $db = new RememberMeDbHandler();
    $response = array();
    $result = $db->deleteRememberMeField($fieldName);
    if ($result) {
        $response["error"] = false;
        $response["message"] = "Remember me field : " . $fieldName . " deleted successfully";
    } else {
        $response["error"] = true;
        $response["message"] = "Remember me field : " . $fieldName . " was NOT deleted because it was not found. Please try again!";
    }
    echoResponse(200, $response);
}
Esempio n. 16
0
/**
 * Validating the data inside the params
 * This is to check if the correct fields have been set
 * @param: arr();
 *
 * Rules
 *		FirstName -> Is validated on frontend
 *		LastName -> Is validated on frontend
 *		Email -> If exists it must be a valid email
 *		Phone -> Must start with the digit 9 or 4, and be within 10 pre-defined series
 *		Birth -> Must be over 16 years
 */
function validateRequest($obj)
{
    $errors = array();
    //Validate Email only if email is provied
    if ($obj->email) {
        if (!filter_var($obj->email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Epostadressen du har skrevet inn er ikke en gyldig epostadresse';
        }
    }
    //Validate Phone
    //RegEx pattern
    $pattern = '/^[4,9]\\d{7}$/';
    if (!preg_match($pattern, $obj->phone)) {
        $errors[] = 'Telefonnummeret må starte med 9 eller 4 og inneholde 8 siffer';
    }
    //Check if number matches the predefined numbers
    $predefined_phonenumbers = array('90909010', '90909020', '90909030', '90909040', '90909050', '40404010', '40404020', '40404030', '40404040', '40404050');
    if (!in_array($obj->phone, $predefined_phonenumbers)) {
        //We also return de predefined set. This is a bit messy, we should probaby have this information elsewhere
        $errors[] = 'Telefonnummeret må være innefor et predefinert sett';
    }
    //Validate Birth
    $setage = '16';
    $birth = new DateTime($obj->birth);
    $today = new DateTime(date("Y-m-d"));
    $interval = $today->diff($birth);
    if (intval($interval->y) < $setage) {
        $errors[] = 'Du må være 16 år eller eldre for å registrere deg her.';
    }
    if (!empty($errors)) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response["status"] = "error";
        $response["message"] = $errors;
        echoResponse(200, $response);
        $app->stop();
    }
}
Esempio n. 17
0
    global $db;
    $data = json_decode($app->request->getBody());
    $rows = Competitions_model::create_competition($db, $data);
    echoResponse(200, $rows);
});
$app->get('/competitions', function () use($app) {
    global $db;
    $data = json_decode($app->request->getBody());
    $rows = Competitions_model::get_competitions($db);
    echoResponse(200, $rows);
});
$app->get('/competitions/season/:year', function ($year) use($app) {
    global $db;
    $data = json_decode($app->request->getBody());
    $rows = Competitions_model::get_competitions_for_season($db, $year);
    echoResponse(200, $rows);
});
$app->put('/competitions/:id', 'authenticateToken', function ($id) use($app) {
    global $db;
    $data = json_decode($app->request->getBody());
    $rows = Competitions_model::update_competition($db, $data, $id);
    if ($rows["status"] == "success") {
        $rows["message"] = "Competition information updated successfully.";
    }
    echoResponse(200, $rows);
});
$app->delete('/competitions/:id', 'authenticateToken', function ($id) use($app) {
    global $db;
    $rows = Competitions_model::delete_competition($db, $id);
    echoResponse(200, $rows);
});
Esempio n. 18
0
        $quantity_buy = 1;
        $query_insert_sales = $db->sales->insert(array("paymentId" => $query_get_PaymentId, "productId" => $menuId, "state" => $payment->getState(), "salePrice" => $amount_client, "quantity" => $quantity_buy));
        echoResponse(200, $response);
    } catch (\PayPal\Exception\PayPalConnectionException $exc) {
        if ($exc->getCode == 404) {
            $response["error"] = true;
            $response["message"] = "payment not found";
        } else {
            $response["error"] = true;
            $response["message"] = "Unknown error occurred!" . $exc->getMessage();
            echoResponse(500, $response);
        }
    } catch (Exception $exc) {
        $response["error"] = true;
        $response["message"] = "Unknown error occurred!" . $exc->getMessage();
        echoResponse(500, $response);
    }
});
/**
 * method to store the saled items in sales table
 */
// function insertItemSales($paymentId, $transaction, $state) {
//     $item_list = $transaction->getItemList();
//     // $db = new DbHandler();
//     $server = 'localhost';
// 	$db_name = 'paypal';
// 	$db_user = '******';
// 	$db_pass = '';
//     $pdo = new PDO("mysql:host=$server;dbname=$db_name", $db_user, $db_pass);
//     foreach ($item_list->items as $item) {
//         $sku = $item->sku;
Esempio n. 19
0
/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
function authenticate(\Slim\Route $route)
{
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();
    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        // get the api key
        $apikey = $headers['Authorization'];
        // validating api key
        /*
                if (!APIKey::isValidKey($api_key)) {
                    // api key is not present in users table
                    $response["error"] = true;
                    $response["message"] = "Access Denied. Invalid Api key";
                    echoResponse(401, $response);
                    $app->stop();
                } else {
                    global $user_id;
                    // get user primary key id
                    $user = APIKey::getUserId($api_key);
                    if ($user != NULL)
                        $user_id = $user["id"];
                }
        */
        global $user_id;
        $user_id = 'dcim';
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoResponse(400, $response);
        $app->stop();
    }
}
Esempio n. 20
0
        for ($row = 2; $row <= $highestRow; $row++) {
            $array['rows'][] = array('c' => array(array('v' => 'Date(' . date('Y, m , j', strtotime('-1 month', strtotime(date('Y-m-j', PHPExcel_Shared_Date::ExcelToPHP($sheet->getCellByColumnAndRow(0, $row)->getValue()))))) . ')'), array('v' => $sheet->getCellByColumnAndRow('1', $row)->getValue()), array('v' => $sheet->getCellByColumnAndRow('2', $row)->getValue()), array('v' => $sheet->getCellByColumnAndRow('3', $row)->getValue())));
        }
        echoResponse(200, $array);
    }
});
$app->get('/etude/:id/courbe/patient', function ($id) {
    $db = new DbHandler();
    $query = "SELECT laboratoire.libelle as lab,etude.libelle as et FROM etude , laboratoire WHERE etude.id_laboratoire=laboratoire.id and etude.id={$id}";
    $response = $db->execute($query);
    foreach ($response as &$value) {
        $rep = "../../data/" . $value['lab'] . "/" . $value['et'] . "/Courbe_Patients.xlsx";
    }
    date_default_timezone_set('Europe/Paris');
    $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objReader->setReadDataOnly(true);
    if (file_exists($rep)) {
        $objPHPExcel = $objReader->load($rep);
        $sheet = $objPHPExcel->getActiveSheet();
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        //  Loop through each row of the worksheet in turn
        $array['cols'][] = array('type' => 'date', 'id' => 'date', 'label' => 'Date');
        $array['cols'][] = array('type' => 'number', 'id' => 'Theorique', 'label' => 'Théorique');
        $array['cols'][] = array('type' => 'number', 'id' => 'Recrutement patient', 'label' => 'Recrutement patients');
        for ($row = 2; $row <= $highestRow; $row++) {
            $array['rows'][] = array('c' => array(array('v' => 'Date(' . date('Y, m , j', strtotime('-1 month', strtotime(date('Y-m-j', PHPExcel_Shared_Date::ExcelToPHP($sheet->getCellByColumnAndRow(0, $row)->getValue()))))) . ')'), array('v' => $sheet->getCellByColumnAndRow('1', $row)->getValue()), array('v' => $sheet->getCellByColumnAndRow('2', $row)->getValue())));
        }
        echoResponse(200, $array);
    }
});
Esempio n. 21
0
/**
 * Get revision data of a particular generator ID
 * @param String $name nameString of User in database
 * method GET
 * url /names/name
 */
function getAnImplementedDateGenRevision($date, $genID, $revId)
{
    $response = array();
    $db = new DbHandler();
    if ($revId == 'count' && !is_numeric($revId)) {
        $result = $db->getImplementedDateGenRevisionCount($date, $genID);
        if (gettype($result) == "string") {
            $response["error"] = true;
            $response["message"] = $result;
        } else {
            $response["error"] = false;
            $response["count"] = $result->fetch_assoc()['count'];
        }
        echoResponse(200, $response);
    } else {
        if ($revId == 'latest' && !is_numeric($revId)) {
            $result = $db->getImplementedDateRevisionCount($date);
            if (gettype($result) == "string") {
                $response["error"] = true;
                $response["message"] = $result;
                echoResponse(200, $response);
            } else {
                $count = $result->fetch_assoc()['count'];
                getAnImplementedDateGenRevision($date, $genID, $count);
            }
        } else {
            if (is_numeric($revId) || $revId == null) {
                // fetching all users with a particular name
                $result = $db->getAnImplementedDateGenRevisionData($date, $genID, $revId);
                //$result1 = $db->getAnImplementedDateGenRevisionParams($date, $revId);
                if (gettype($result) == "string") {
                    $response["error"] = true;
                    $response["message"] = $result;
                } else {
                    $response["error"] = false;
                    $response["revNumber"] = $revId;
                    $response["date"] = $date;
                    $response["revData"] = array();
                    // looping through result and preparing names array
                    while ($task = $result->fetch_assoc()) {
                        $tmp = array();
                        $tmp["p_id"] = $task["p_id"];
                        $tmp["from_b"] = $task["from_b"];
                        $tmp["to_b"] = $task["to_b"];
                        $tmp["cat"] = $task["cat"];
                        $tmp["val"] = $task["val"];
                        array_push($response["revData"], $tmp);
                    }
                    // looping through result and preparing names array
                    /*while ($task = $result1->fetch_assoc()) {
                          $response["comment"] = $task["comment"];
                          $response["TO"] = $task["time"];
                      }*/
                }
                echoResponse(200, $response);
            } else {
                $response["error"] = true;
                $response["message"] = "Invalid Revision data request url";
                echoResponse(200, $response);
            }
        }
    }
}
Esempio n. 22
0
<?php

$app->get('/article', function () use($app, $db) {
    $dbquery = $db->prepare("select * from articles");
    $dbquery->execute();
    $data = $dbquery->fetchAll(PDO::FETCH_ASSOC);
    echoResponse(200, $data);
});
Esempio n. 23
0
<?php

$app->get('/courses', function () {
    $db = new DbHelper();
    $columns = "ID,title,description,price,start_date,end_date,max_number_of_students,ID_subject";
    $table = "course";
    $where = array();
    $orwhere = array();
    //$limit = 1;
    $result = $db->select($table, $columns, $where, $orwhere);
    echoResponse(200, $result);
});
Esempio n. 24
0
    $params = $app->request->post();
    $flowData = parseFlowData($params);
    if (!file_exists($flowData['location']['dir'])) {
        mkdir($flowData['location']['dir']);
    }
    if (!file_exists($flowData['location']['dir'] . DIRECTORY_SEPARATOR . 'old')) {
        mkdir($flowData['location']['dir'] . DIRECTORY_SEPARATOR . 'old');
    }
    if ($flowData['location']['file']) {
        copy($flowData['location']['file'], $flowData['location']['backup']);
    }
    if (move_uploaded_file($flowData['location']['temp'], $flowData['location']['file']) === true) {
        $success = true;
    }
    $data = array('success' => $success, 'files' => $_FILES, 'post' => $params, 'flowData' => $flowData);
    echoResponse(200, array('params' => $data));
});
function parseFlowData($flowData)
{
    $ds = DIRECTORY_SEPARATOR;
    $flowIdData = explode('--data--', $flowData['flowIdentifier']);
    $idData = explode('--', $flowIdData[1]);
    $table = $idData[0];
    $id = $idData[1];
    $size = $_FILES['file']['size'];
    $name = $flowIdData[0];
    $ext = substr($flowData['flowRelativePath'], strrpos($flowData['flowRelativePath'], '.') + 1);
    $temp = $_FILES['file']['tmp_name'];
    $dir = __DIR__ . $ds . '..' . $ds . '..' . $ds . '..' . $ds . 'img' . $ds . $table;
    $file = $dir . $ds . str_pad($id, 5, '0', STR_PAD_LEFT) . '.' . $ext;
    $backup = $dir . $ds . 'old' . $ds . str_pad($id, 5, '0', STR_PAD_LEFT) . '-' . time() . '.' . $ext;
Esempio n. 25
0
function updateMaterials()
{
    $request_body = file_get_contents('php://input');
    $jsonData = json_decode($request_body);
    $result = false;
    $itemsUpdated = 0;
    $db = new MaterialDbHandler();
    if (count($jsonData->data) == 1) {
        $result = $db->updateMaterial($jsonData->data);
        if ($result) {
            $itemsUpdated = 1;
        }
    } else {
        if (count($jsonData->data) > 1) {
            foreach ($jsonData->data as $material) {
                $result = $db->updateMaterial($material);
                if ($result) {
                    $itemsUpdated++;
                }
            }
        }
    }
    $response["error"] = $itemsUpdated == count($jsonData->data) ? false : true;
    $response["message"] = "Total materials updated: " . $itemsUpdated;
    $response["data"] = $jsonData->data;
    $errorCode = 201;
    if ($response["error"]) {
        $errorCode = 500;
    }
    echoResponse($errorCode, $response);
}
Esempio n. 26
0
        $response["status"] = UsersService::$USER_SUCCESSFULLY_REGISTERED;
        $response["user"] = $user;
        $response["errorMessage"] = "";
    } else {
        $response["status"] = UsersService::$USER_REGISTRATION_ERROR;
        $response["errorMessage"] = "Error al registrar Usuario.";
    }
    echoResponse(200, $response);
});
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//Login
$app->post('/login', function () use($app) {
    //Get Json body
    $bodyJson = json_decode($app->request->getBody());
    //Parse User
    $user = User::fromJsonObject($bodyJson->user);
    //Check Login
    if (!UsersService::checkLogin($user->login, $user->password)) {
        $response["errorMessage"] = "Usuario y/o contraseña incorrecta.";
        echoResponse(200, $response);
        return;
    }
    //Return Api Key
    $user = UsersService::loadUserByLogin($user->login);
    $response["user"] = $user;
    $response["errorMessage"] = "";
    echoResponse(201, $response);
});
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//Run
$app->run();
Esempio n. 27
0
    $response = array();
    //
    $db = new DbHandler();
    $datos = $db->getAllRecord("call sp_sel_sip_organo( )");
    //var_dump($datos);
    if ($datos != NULL) {
        $response = $datos;
    } else {
        $response['status'] = "info";
        $response['message'] = 'No hay información';
    }
    echoResponse(200, $response);
});
// Opción para eliminar un registro de la tabla sip_organo
$app->get('/organoD/:id', 'sessionAlive', function ($id) use($app) {
    $response = array();
    //
    //
    $db = new DbHandler();
    $resId = $db->deleteRecord("call sp_del_sip_organo(?)", $id);
    if ($resId == 0) {
        $response['status'] = "success";
        $response['message'] = 'Datos eliminados';
    } else {
        if ($resId < 0) {
            $response['status'] = "error " . $resId;
            $response['message'] = 'No pudo eliminar los Datos';
        }
    }
    echoResponse(200, $response);
});
Esempio n. 28
0
function deleteSportTypeById($id)
{
    $db = new SportTypeDbHandler();
    $response = array();
    $result = $db->deleteSportType($id);
    if ($result) {
        $response["error"] = false;
        $response["message"] = "Sport type with id: " . $id . " deleted successfully";
    } else {
        $response["error"] = true;
        $response["message"] = "Sport type with id: " . $id . " was NOT deleted because it was not found. Please try again!";
    }
    echoResponse(200, $response);
}
Esempio n. 29
0
/**
 * Validating score value
 */
function validateScore($score)
{
    $app = \Slim\Slim::getInstance();
    if (is_numeric($score)) {
        if ($score < 0 || $score > 5) {
            $response["error"] = true;
            $response["message"] = 'The score must be a number between 0 and 5';
            echoResponse(400, $response);
            $app->stop();
        }
    } else {
        $response["error"] = true;
        $response["message"] = 'Score must be numeric value';
        echoResponse(400, $response);
        $app->stop();
    }
}
Esempio n. 30
0
 * # PUT
 * http://dominio.com/carpeta_del_api/hello_world/1
 * Parámetros: {nombre:<nombre>, apellido:<apellido>}
 */
$app->put("/hello_world/:id_person", function ($id_person) use($app) {
    $params = $app->request->getBody();
    $params = json_decode($params);
    $nombre = "";
    $apellido = "";
    if (isset($params->nombre)) {
        $nombre = $params->nombre;
    }
    if (isset($params->apellido)) {
        $apellido = $params->apellido;
    }
    $oResponse = new stdObject();
    $oResponse->id_person = $id_person;
    $oResponse->data->nombre = array("My", "name", "is", $nombre);
    $oResponse->data->apellido = array("My", "lastname", "is", $apellido);
    echoResponse($oResponse);
});
/**
 * @description
 * # DELETE
 * http://dominio.com/carpeta_del_api/hello_world/1
 */
$app->delete("/hello_world/:id_person", function ($id_person) use($app) {
    $oResponse = new stdObject();
    $oResponse->id_person = "Se eliminará a la persona {$id_person}";
    echoResponse($oResponse);
});