unexpected 'A' Postman php api with JSON Response - php

Recently I try to create an API with PHP. all thing goes alright till suddenly I face unexpected 'a' error when trying to parse a JSON from the request throw Postman. I found something related to my issue but there is no solution in my case here : link
I send
{
"teacher_code":"sas"
}
JSON to teachers.php file to assign a student to the teacher
here is the teacher.php file content :
require_once ("classes/Rest.php");
require_once ("classes/api.php");
$api = new Api();
if($api->getHttpmethod() === 'POST'){
$api->validateParameter('teacher_code' ,$teacher_code = $api->getParam('teacher_code') , STRING , true);
$api->checkUserAccessablity();
$api->teacherCodeinRange($teacher_code);
$query = "INSERT INTO `group_users` (`user_id`,`group_id` )
VALUES (:user_id , (SELECT group_id FROM `groups` WHERE group_name = 'all' AND user_id =
(SELECT user_id FROM `teachers` WHERE t_code = :teacher_code)) )";
$keyValue = [
"user_id" => $api->getUserid() ,
"teacher_code" => $teacher_code
];
$result = $api->queryExecute($query , $keyValue );
$api->returnResponse(SUCCESS , SUCCESS_MESSAGE);
}
and api.php file :
require_once ("dbConnect.php");
require_once ("JWT.php");
class Api extends Rest
{
public $dbConn;
private $userId;
public function __construct()
{
parent::__construct();
$db = new dbConnect();
$this->dbConn = $db->connect();
}
public function setUserid($id){
$this->userId = $id;
}
public function getUserid(){
return $this->userId;
}
public function checkUserAccessablity(){
$payload = $this->deCodetoken();
$this->setUserid($payload->user_id);
$this->validateUser();
}
public function validateUser(){
$query = "SELECT * FROM `users` WHERE user_id = :id";
$keyValue = [
"id" => $this->getUserid()
];
$result = $this->queryExecute($query , $keyValue,true );
if(!$result){
$this->throwError(SYSTEM_ERROR , SYSTEM_ERROR_MESSAGE );
}
if(!is_array($result)){
$this->throwError(USER_NOT_FOUND_CODE , USER_NOT_FOUND_MESSAGE . $this->getUserid());
}
//TODO CHECK USER ACTIVE
return true;
}
public function teacherCodeinRange($tCode){
$query = "SELECT * FROM `teachers` INNER JOIN `licenses` ON (licenses.user_id = teachers.user_id)
WHERE teachers.t_code = :tcode LIMIT 1";
$keyValue = [
"tcode" => $tCode
];
$this->queryExecute($query , $keyValue,true );
return true;
}
public function teacherCodeinStudentrange($teacherID){
//TODO SELECT TEACHER STUDENT RANGE
$query = "SELECT DISTICT user_id FROM `teachers` INNER JOIN `groups` ON (groups.user_id = teachers.user_id)
INNER JOIN `group_users` ON (group_users.group_id = groups.group_id)
WHERE teachers.user_id = :teacherID AND groups.group_name = 'all' AND group_users.user_id = :userID ";
$keyValue = [
"userID" => $this->getUserid(),
"teacherID" => $teacherID,
];
$result = $this->queryExecute($query , $keyValue,true );
if(!is_array($result)){
$this->throwError(TEACHER_NOT_FOUND , TEACHER_NOT_FOUND_MESSAGE);
}
return true;
}
public function getHttpmethod(){
return $this->HttpMethod;
}
public function getParam($key){
return $this->arrayFinddeep($this->data , $key);
}
public function queryExecute($query , $keyArray , $isSelect = false){
$queryExec = $this->dbConn->prepare($query);
if(is_array($keyArray) || !empty($keyArray)) {
foreach ($keyArray as $key => &$value) {
$queryExec->bindParam(':' . $key, $value);
}
}
if($isSelect) {
$queryExec->execute();
$result = $queryExec->fetch(PDO::FETCH_ASSOC);
}else {
$result = $queryExec->execute();
}
return $result;
}
public function getLastuserId(){
return $this->dbConn->lastInsertId();
}
public function generateToken($payload , $secretKey){
try{
return \Firebase\JWT\JWT::encode($payload , $secretKey);
}catch (Exception $exception){
$this->throwError(JWT_PROCESSING_ERROR , $exception->getMessage());
}
}
public function deCodetoken(){
try{
$token = $this->getBearerToken();
$payload = \Firebase\JWT\JWT::decode($token , SECURITY_KEY , ['HS256']);
return $payload;
}catch (Exception $exception){
$this->throwError(ACCESS_TOKEN_ERROR , $exception->getMessage());
}
}
}
and the last class is Rest.php :
require_once ("Constans.php");
class Rest
{
protected $HttpMethod;
protected $request;
protected $data;
public function __construct(){
$this->HttpMethod = $_SERVER['REQUEST_METHOD'];
if($this->checkValidhttpMethod()) {
try{
$handler = fopen('php://input', 'r');
$this->request = stream_get_contents($handler);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
$this->validateRequest();
}
}
public function checkValidhttpMethod(){
if(empty($this->HttpMethod) or !in_array($this->HttpMethod,ACCEPTABLE_HTTP_METHOD)){
$this->throwError(NOT_VALID_HTTP_METHOD,NOT_VALID_HTTP_METHOD_Message);
}
return true;
}
public function setJsonheader(){
header("content-type: application/json");
}
public function validateRequest(){
if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
$this->throwError(REQUEST_CONTENT_NOT_VALID , REQUEST_CONTENT_NOT_VALID_MESSAGE);
}
try{
$this->data = json_decode($this->request , true);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
}
public function processAPI(){
}
public function throwError($code , $message){
$this->setJsonheader();
echo json_encode(['error' => ['status' => $code , 'message' => $message]]);
exit;
}
public function returnResponse($code , $data){
$this->setJsonheader();
echo json_encode(['response' => ['status' => $code , 'result' => $data ]]);
exit;
}
//TODO SQL injection Validate
public function validateParameter($fieldName , $value , $dataType , $required = true){
if($required && empty($value)){
$this->throwError(PARAMETR_REQUIRED,PARAMETR_REQUIRED_MESSAGE . $fieldName);
}
//TODO SQL injection
//TODO CHECK The All Data Type
switch ($dataType){
case BOOLEAN :
if(!is_bool($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case INTEGER :
if(!is_numeric($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case STRING :
if(!is_string($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case DONT_CARE :
break;
default:
break;
}
return $value;
}
public function arrayFinddeep($array, $search)
{
foreach($array as $key => $value) {
if (is_array($value)) {
$sub = $this->arrayFinddeep($value, $search);
if (count($sub)) {
return $sub;
}
} elseif ($key === $search) {
return $value;
}
}
return array();
}
/**
* Get hearder Authorization
* */
function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = $this->getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
$this->throwError(AUTHORIZATION_HEADER_NOT_FOUND , AUTHORIZATION_HEADER_NOT_FOUND_MESSAGE);
}
}
all queries go along queryExecute function in api.php class and recently I got that the bindParam function is not going to work fine too.
I really don't have any idea where the problem is, as In the reference said its somehow related to DB queries result. I try to use mysqli also but it did not work.
any help will be appreciated :-)

Related

php redis insert a data at a same time with few queues error

There are 3 queues in redis.
If I insert a data at a same time with different browsers, both requests are accepted.
I get 2 duplicated records. Any helps?
For example, the first request is on the 1st queue.
At the second request, 2nd queue is searched for finding the data.
But the data doesn't exist in the queue.
The second request is inserted on the queue.
Is it understandable?
public function save($evt_no, $type = "redis") {
$name = '';
$res = true;
try{
$headers = getallheaders();
$bodys = $_REQUEST;
$session = $_SESSION;
foreach ($_FILES as $fileKey=>$fileVal) {
if ($fileVal['error'] == 0) {
try {
$uploaded_row = $this->fileL->upload('queueEventParticipant', $fileKey, array() ,'queue');
} catch (\Exception $ex) {
throw $ex;
}
$bodys['file'][_return_numeric($fileKey)] = $uploaded_row;
}
}
$data = array(
'header' => $headers,
'body' => $bodys,
'session' => $session
);
$data['body']['evt_no'] = $evt_no;
$data = json_encode($data);
if($type == "redis"){
$name = $this->attendQueueRedisService->setNewRsvp($data);
} else {
throw new \Exception("No exist");
}
} catch (\Exception $ex){
log_message("error", $ex->getMessage());
throw $ex;
}
if($res){
return $name;
} else {
return "Error";
}
}
class AttendQueueRedisService extends CI_Model {
private $redisClient;
private $redisConfig;
const PREFIX_DONE = 'done_';
const PREFIX_ERROR = 'error_';
public function __construct() {
parent::__construct();
if ($this->load->config('redis', true, true)) {
$this->redisConfig = $this->config->config['redis'];
}
$this->redisClient = new Redis();
$this->redisClient->connect($this->redisConfig['hostname'], $this->redisConfig['port']);
$this->redisClient->auth($this->redisConfig['auth']);
$this->redisClient->select($this->redisConfig['queue']);
}
public function setNewRsvp($data) {
$key = uniqid('rsvp_'.gethostname().'_',true).':redis';
$this->redisClient->set($key, $data, 60 * 30);
return $key;
}
}

I am trying to get some content from s3 bucket AWS and upon requesting data It takes much longer than I can afford around 15 to 20 seconds

heres my api.php file code in try body else case is taking too much time
<?php
require_once(dirname(__FILE__) . "/constants.php");
includeMonstaConfig();
session_start();
require_once(dirname(__FILE__) . '/lib/helpers.php');
require_once(dirname(__FILE__) . '/lib/response_helpers.php');
require_once(dirname(__FILE__) . '/request_processor/RequestMarshaller.php');
if (file_exists(dirname(__FILE__) . '/../../mftp_extensions.php')) {
include_once(dirname(__FILE__) . '/../../mftp_extensions.php');
}
dieIfNotPOST();
require_once(dirname(__FILE__) . '/lib/access_check.php');
$marshaller = new RequestMarshaller();
try {
$request = json_decode($_POST['request'], true);
if ($request['actionName'] == 'fetchFile' || $request['actionName'] == 'downloadMultipleFiles') {
switch ($request['actionName']) {
case 'fetchFile':
$outputPath = $marshaller->prepareFileForFetch($request);
$outputFileName = monstaBasename($request['context']['remotePath']);
break;
case 'downloadMultipleFiles':
$outputResponse = $marshaller->marshallRequest($request, false, true);
$outputPath = $outputResponse["data"];
$outputFileName = "mftp_zip_" . date("Y_m_d_H_i_s") . ".zip";
}
$fileKey = generateRandomString(16);
$_SESSION[MFTP_SESSION_KEY_PREFIX . $fileKey] = array(
"path" => $outputPath,
"fileName" => $outputFileName
);
$response = array(
"success" => true,
"fileKey" => $fileKey
);
print json_encode($response);
} else {
$skipConfigurationActions = array('checkSavedAuthExists', 'writeSavedAuth', 'readSavedAuth',
'readLicense', 'getSystemVars', 'resetPassword', 'forgotPassword', 'validateSavedAuthPassword',
'downloadLatestVersionArchive', 'installLatestVersion');
$skipConfiguration = in_array($request['actionName'], $skipConfigurationActions);
$serializedResponse = $marshaller->marshallRequest($request, $skipConfiguration);
print $serializedResponse;
}
} catch (Exception $e) {
$marshaller->disconnect();
handleExceptionInRequest($e);
}
$marshaller->disconnect();
here is the RequestMarshaller.php code showing only the request code
<?php
require_once(dirname(__FILE__) . '/RequestDispatcher.php');
require_once(dirname(__FILE__) . "/../lib/helpers.php");
require_once(dirname(__FILE__) . "/../system/ApplicationSettings.php");
class RequestMarshaller {
/**
* #var RequestDispatcher
*/
private $requestDispatcher;
private function initRequestDispatcher($request, $skipConfiguration = false) {
if(!$skipConfiguration)
$request['configuration'] = $this->applyConnectionRestrictions($request['connectionType'],
$request['configuration']);
if (is_null($this->requestDispatcher))
$this->requestDispatcher = new RequestDispatcher($request['connectionType'], $request['configuration'],
null, null, $skipConfiguration);
}
public function marshallRequest($request, $skipConfiguration = false, $skipEncode = false) {
$this->initRequestDispatcher($request, $skipConfiguration);
$response = array();
if ($request['actionName'] == 'putFileContents')
$response = $this->putFileContents($request);
else if ($request['actionName'] == 'getFileContents')
$response = $this->getFileContents($request);
else {
$context = array_key_exists('context', $request) ? $request['context'] : null;
$responseData = $this->requestDispatcher->dispatchRequest($request['actionName'], $context);
$response['success'] = true;
if(is_object($responseData)) {
$response['data'] = method_exists($responseData, 'legacyJsonSerialize') ?
$responseData->legacyJsonSerialize() : $responseData;
} else
$response['data'] = $responseData;
}
if ($skipEncode)
return $response;
return json_encode($response);
}
}
}
and here is my RequestDispatcher.php code
<?php
class RequestDispatcher {
/**
* #var ConnectionBase
*/
private $connection;
/**
* #var string
*/
private $connectionType;
/**
* #var array
*/
private $rawConfiguration;
public $username;
public function getusername(){
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
return $this->username;
}
public function __construct($connectionType, $rawConfiguration, $configurationFactory = null,
$connectionFactory = null, $skipConfiguration = false) {
$this->connectionType = $connectionType;
/* allow factory objects to be passed in for testing with mocks */
if ($skipConfiguration) {
$this->connection = null;
} else {
$this->rawConfiguration = $rawConfiguration;
$configurationFactory = is_null($configurationFactory) ? new ConfigurationFactory() : $configurationFactory;
$connectionFactory = is_null($connectionFactory) ? new ConnectionFactory() : $connectionFactory;
$configuration = $configurationFactory->getConfiguration($connectionType, $rawConfiguration);
$this->connection = $connectionFactory->getConnection($connectionType, $configuration);
}
}
public function dispatchRequest($actionName, $context = null) {
if (in_array($actionName, array(
'listDirectory',
'downloadFile',
'uploadFile',
'deleteFile',
'makeDirectory',
'deleteDirectory',
'rename',
'changePermissions',
'copy',
'testConnectAndAuthenticate',
'checkSavedAuthExists',
'writeSavedAuth',
'readSavedAuth',
'readLicense',
'getSystemVars',
'fetchRemoteFile',
'uploadFileToNewDirectory',
'downloadMultipleFiles',
'createZip',
'setApplicationSettings',
'deleteMultiple',
'extractArchive',
'updateLicense',
'reserveUploadContext',
'transferUploadToRemote',
'getRemoteFileSize',
'getDefaultPath',
'downloadForExtract',
'cleanUpExtract',
'resetPassword',
'forgotPassword',
'validateSavedAuthPassword',
'downloadLatestVersionArchive',
'installLatestVersion'
))) {
if (!is_null($context))
return $this->$actionName($context);
else
return $this->$actionName();
}
throw new InvalidArgumentException("Unknown action $actionName");
}
public function getConnection() {
return $this->connection;
}
private function connectAndAuthenticate($isTest = false) {
$sessionNeedsStarting = false;
if (function_exists("session_status")) {
if (session_status() == PHP_SESSION_NONE) {
$sessionNeedsStarting = true;
}
} else {
$sessionNeedsStarting = session_id() == "";
}
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
if ($sessionNeedsStarting && !defined("MONSTA_UNIT_TEST_MODE")) { // TODO: pass in this as parameter to avoid global state
session_start();
$_SESSION["RemoteUsername"]=$configuration->getRemoteUsername();
}
$maxFailures = defined("MFTP_MAX_LOGIN_FAILURES") ? MFTP_MAX_LOGIN_FAILURES : 0;
$loginFailureResetTimeSeconds = defined("MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES")
? MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES * 60 : 0;
if (!isset($_SESSION["MFTP_LOGIN_FAILURES"]))
$_SESSION["MFTP_LOGIN_FAILURES"] = array();
$banManager = new UserBanManager($maxFailures, $loginFailureResetTimeSeconds,
$_SESSION["MFTP_LOGIN_FAILURES"]);
if ($banManager->hostAndUserBanned($configuration->getHost(), $configuration->getRemoteUsername())) {
mftpActionLog("Log in", $this->connection, "", "", "Login and user has exceed maximum failures.");
throw new FileSourceAuthenticationException("Login and user has exceed maximum failures.",
LocalizableExceptionDefinition::$LOGIN_FAILURE_EXCEEDED_ERROR, array(
"banTimeMinutes" => MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES
));
}
try {
$this->connection->connect();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
throw $e;
}
try {
$this->connection->authenticate();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
$banManager->recordHostAndUserLoginFailure($configuration->getHost(),
$configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
throw $e;
}
$banManager->resetHostUserLoginFailure($configuration->getHost(), $configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
if ($isTest) {
// only log success if it is the first connect from the user
mftpActionLog("Log in", $this->connection, "", "", "");
}
if ($configuration->getInitialDirectory() === "" || is_null($configuration->getInitialDirectory())) {
return $this->connection->getCurrentDirectory();
}
return null;
}
public function disconnect() {
if ($this->connection != null && $this->connection->isConnected())
$this->connection->disconnect();
}
public function listDirectory($context) {
$this->connectAndAuthenticate();
$directoryList = $this->connection->listDirectory($context['path'], $context['showHidden']);
$this->disconnect();
return $directoryList;
}
public function downloadFile($context, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->downloadFile($transferOp);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also downloaded
mftpActionLog("Download file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function downloadMultipleFiles($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$zipPath = $zipBuilder->buildZip($foundFiles);
$this->disconnect();
return $zipPath;
}
public function createZip($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$destPath = PathOperations::join($context['baseDirectory'], $context['dest']);
$zipPath = $zipBuilder->buildLocalZip($foundFiles, $destPath);
$this->connection->uploadFile(new FTPTransferOperation($zipPath, $destPath, FTP_BINARY));
$this->disconnect();
return $zipPath;
}
public function uploadFile($context, $preserveRemotePermissions = false, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFile($transferOp, $preserveRemotePermissions);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also uploaded
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function uploadFileToNewDirectory($context) {
// This will first create the target directory if it doesn't exist and then upload to that directory
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFileToNewDirectory($transferOp);
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
$this->disconnect();
}
public function deleteFile($context) {
$this->connectAndAuthenticate();
$this->connection->deleteFile($context['remotePath']);
mftpActionLog("Delete file", $this->connection, dirname($context['remotePath']), monstaBasename($context['remotePath']), "");
$this->disconnect();
}
public function makeDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->makeDirectory($context['remotePath']);
$this->disconnect();
}
public function deleteDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->deleteDirectory($context['remotePath']);
$this->disconnect();
}
public function rename($context) {
$this->connectAndAuthenticate();
if(array_key_exists('action', $context) && $context['action'] == 'move') {
$action = 'Move';
} else {
$action = 'Rename';
}
$itemType = $this->connection->isDirectory($context['source']) ? 'folder' : 'file';
$this->connection->rename($context['source'], $context['destination']);
if ($action == 'Move') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . $context['destination'],
"");
}
if ($action == 'Rename') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . monstaBasename($context['destination']),
"");
}
$this->disconnect();
}
public function changePermissions($context) {
$this->connectAndAuthenticate();
$itemType = $this->connection->isDirectory($context['remotePath']) ? 'folder' : 'file';
$this->connection->changePermissions($context['mode'], $context['remotePath']);
mftpActionLog("CHMOD " . $itemType, $this->connection, dirname($context['remotePath']),
monstaBasename($context['remotePath']) . " to " . decoct($context['mode']), "");
$this->disconnect();
}
public function copy($context) {
$this->connectAndAuthenticate();
$this->connection->copy($context['source'], $context['destination']);
$this->disconnect();
}
public function testConnectAndAuthenticate($context, $isInitalLogin = true) {
$initialDirectory = $this->connectAndAuthenticate($isInitalLogin);
$serverCapabilities = array("initialDirectory" => $initialDirectory);
if (isset($context['getServerCapabilities']) && $context['getServerCapabilities']) {
$serverCapabilities["changePermissions"] = $this->connection->supportsPermissionChange();
}
clearOldTransfers();
return array("serverCapabilities" => $serverCapabilities);
}
public function checkSavedAuthExists() {
if ($this->readLicense() == null)
return false;
return AuthenticationStorage::configurationExists(AUTHENTICATION_FILE_PATH);
}
public function writeSavedAuth($context) {
if ($this->readLicense() == null)
return;
AuthenticationStorage::saveConfiguration(AUTHENTICATION_FILE_PATH, $context['password'],
$context['authData']);
}
public function readSavedAuth($context) {
if ($this->readLicense() == null)
return array();
return AuthenticationStorage::loadConfiguration(AUTHENTICATION_FILE_PATH, $context['password']);
}
public function readLicense() {
$keyPairSuite = new KeyPairSuite(PUBKEY_PATH);
$licenseReader = new LicenseReader($keyPairSuite);
$license = $licenseReader->readLicense(MONSTA_LICENSE_PATH);
if (is_null($license))
return $license;
$publicLicenseKeys = array("expiryDate", "version", "isTrial", "licenseVersion", "productEdition");
$publicLicense = array();
foreach ($publicLicenseKeys as $publicLicenseKey) {
if (isset($license[$publicLicenseKey]))
$publicLicense[$publicLicenseKey] = $license[$publicLicenseKey];
}
return $publicLicense;
}
private function recordAffiliateSource($licenseEmail) {
$affiliateChecker = new AffiliateChecker();
$installUrl = getMonstaInstallUrl();
$affiliateId = defined("MFTP_AFFILIATE_ID") ? MFTP_AFFILIATE_ID : "";
return $affiliateChecker->recordAffiliateSource($affiliateId, $licenseEmail, $installUrl);
}
public function getSystemVars() {
$systemVars = SystemVars::getSystemVarsArray();
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$systemVars['applicationSettings'] = $applicationSettings->getSettingsArray();
return $systemVars;
}
public function setApplicationSettings($context) {
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$applicationSettings->setFromArray($context['applicationSettings']);
$applicationSettings->save();
}
public function validateSavedAuthPassword($context) {
return AuthenticationStorage::validateAuthenticationPassword(AUTHENTICATION_FILE_PATH, $context["password"]);
}
}
i am not that much experienced in this field i am a beginner and got this task to find out the cause of the delay and resolve it . kindly help me in this regard i have tried many things as i thought that json_encoding(response) might be the cause but just 10 items are returning in response

CakePHP allow searching by field using API?

I am trying to create an API using CakePHP that allows searching. For example:
http://localhost:8765/users/index/?username=admin
Which should return users with usernames equal to 'admin':
users: [
{
id: 3,
username: "admin",
image: "",
firstName: "Jeremy",
lastName: "Quick",
userTypeId: 1,
email: "jrquick#test.com",
groupId: 2
}
]
So far, I have been able to accomplish this with a custom get() in the AppController which checks the $_GET and $_POST array for fields on the model. But the function is getting more and more complicated and verging on hackiness as I add more functionality (range search, collection search, and child table filtering). Is there a better, more CakePHP friendly way of accomplishing this? Whether through pure cakephp or a plugin?
I think you want to use the Cakephp Search plugin. It has good documentation and uses a PRG method similar to what you are currently using. It will function just fine through an API. Here's a link to that plugin: github.com/FriendsOfCake/search
If You want to create API, You should create a MiddleWare at first, which will filter tokens, keys etc. to make Your API more protected.
Also, You should use Plugins and RESTful Routes, which will be very helpful.
To create plugin:
bin/cake bake plugin Api
Create Model:
bin/cake bake model Users
For example, You want to have UsersController in Api plugin:
<?php
namespace Api\Controller;
/* This controller will be extending like parent */
use Api\Controller\AppController;
use Api\Model\Table\UsersTable;
/**
* Class UsersController
* #package Api\Controller
* #property UsersTable $Users
*
*/
class UsersController extends AppController{
public function initialize(){
parent::initialize();
$this->loadModel('Api.Users');
}
public function getUser($field ='username', $username = false){
return $this->_jsonResponse(
[
'users' => $this->Users->findBy{ucfirst($field)}($username)
];
)
}
public function _jsonResponse($data, $code = 200){
$this->response->type('json');
$this->response->statusCode($code);
$this->response->body(
json_encode((array)$data)
);
return $this->response;
}
}
Route will be descripbed in plugins/config/routes.php. You need to create Route Map for API in /api path:
function (RouteBuilder $routes) {
$routes->resources('Users', [
'map' => [
'get-user' => [
'action' => 'getUser',
'method' => 'GET' /* Can be also as array ['GET', 'PUT', 'DELETE'] */
]
]
]);
$routes->fallbacks('DashedRoute');
}
If You have frequent calls, You should use Cache that calls and save them for some amount of time. For example - 10 minutes. Cache can be configured in config/app.php. You should create separate Cache prefix and use it in this way:
<?php
use Cake\Cache\Cache;
$data = [];
Cache::write('some_key', $data, 'prefix')
dump(Cache::read('some_key', 'prefix'));
It's just examples. If You will face some problems - just tell in comments :)
Also, use Migrations and Seeds instead dumping sql files
If You want to filter data from Middleware - You should have Event as argument, that will contain request data ($_POST) and request query($_GET) variables that You will be able to easily handle with.
From controllers You need to use $this->request->data to get POST data array or $this->request->query to get GET data array.
I haven't found an answer that seems to work exactly how I am wanting, so here is my current get command. It does allow searching by fields, join tables, greater/less than, in array, and like.
If anyone has recommendations to improve I will update my answer.
public function get() {
$response = new Response();
$model = $this->loadModel();
$fields = $this->getFields();
$joins = $this->getJoins();
$order = $this->getOrder();
$params = $this->getParams();
$limit = $this->getLimit();
$offset = $this->getOffset();
$query = $model->find('all', ['fields' => $fields]);
if (!is_null($joins)) {
$query->contain($joins);
}
if (sizeof($params['equals']) > 0) {
foreach ($params['equals'] as $equalsKey=>$equalsValue) {
$query->andWhere([$equalsKey => $equalsValue]);
}
}
if (sizeof($params['or']) > 0) {
foreach ($params['or'] as $orKey=>$orValue) {
$query->orWhere([$orKey => $orValue]);
}
}
if (!is_null($order)) {
$query->order([$order]);
}
if (!is_null($limit)) {
$query->limit($limit);
if (!is_null($offset)) {
$query->offset($offset);
}
}
$response->addMessage($model->table(), $query->toArray());
$response->respond($this);
}
private function getFields() {
$fields = [];
if (array_key_exists('fields', $_GET)) {
$fields = explode(',', $_GET['fields']);
}
return $fields;
}
private function getLimit() {
$limit = null;
if (array_key_exists('limit', $_GET)) {
$limit = $_GET['limit'];
}
return $limit;
}
private function getJoins() {
$joins = null;
if (array_key_exists('joins', $_GET)) {
$joins = explode(',', $_GET['joins']);
}
return $joins;
}
private function getOffset() {
$offset = null;
if (array_key_exists('offset', $_GET)) {
$offset = $_GET['limit'];
}
return $offset;
}
private function getOrder() {
$results = [];
if (array_key_exists('order', $_GET)) {
$orders = explode(',', $_GET['order']);
foreach ($orders as $order) {
$sign = substr($order, 0, 1);
$direction = 'ASC';
if (in_array($sign, ['+', '-'])) {
if ($sign === '-') {
$direction = 'DESC';
}
$order = substr($order, 1);
}
$result = $order;
if (strpos($result, '.') === false) {
$result = $this->loadModel()->alias() . '.' . $order;
}
$result = $result . ' ' . $direction;
$results[] = $result;
}
}
return (sizeof($results) == 0) ? null : implode(',', $results);
}
private function getParams() {
$params = [
'equals' => [],
'or' => []
];
$parentModel = $this->loadModel();
$array = array_merge($_GET, $_POST);
foreach ($array as $field=>$value) {
$comparisonType = 'equals';
$operator = substr($field, strlen($field) - 1);
if (in_array($operator, ['!', '>', '<'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator .= '=';
} else if (in_array($operator, ['|'])) {
$field = substr($field, 0, strlen($field) - 1);
$comparisonType = 'or';
$operator = '=';
} else if (in_array($operator, ['%'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator = 'LIKE';
$value = '%'.$value.'%';
} else {
$operator = '=';
}
if ($value == 'null') {
$operator = (strpos($operator, '!') === false) ? 'IS' : 'IS NOT';
$value = null;
}
$field = str_replace('_', '.', $field);
if (strpos($field, '.') === false) {
$alias = $parentModel->alias();
} else {
$fieldExplosion = explode('.', $field);
$alias = $fieldExplosion[0];
$field = $fieldExplosion[1];
}
$model = null;
if ($parentModel->alias() !== $alias) {
$association = $parentModel->associations()->get($alias);
if (!is_null($association)) {
$model = $this->loadModel($association->className());
}
} else {
$model = $parentModel;
}
if (!is_null($model)) {
if ($model->hasField(rtrim($field, 's')) && !$model->hasField($field)) {
$field = rtrim($field, 's');
$value = '(' . $value . ')';
$operator = ' IN';
}
if ($model->hasField($field)) {
$params[$comparisonType][$alias.'.'.$field . ' ' . $operator] = $value;
}
}
}
return $params;
}

Fatal error: Call to a member function selectCollection() on a non-object in C:\xampp\htdocs\phpmongodb\db.php

Can someone please help me, I get this fatal error message when I try to run the code in a browser. I have searched through various topics and couldn't find the answer. I have two very similar functions and only one of them is reporting an error. Function getById is working just fine, but function get reports an error. Here's my db.php file:
class DB {
private $db;
public $limit = 5;
public function __construct($config){
$this->connect($config);
}
private function connect($config){
try{
if ( !class_exists('Mongo')){
echo ("The MongoDB PECL extension has not been installed or enabled");
return false;
}
$connection= new MongoClient($config['connection_string'],array('username'=>$config['username'],'password'=>$config['password']));
return $this->db = $connection->selectDB($config['dbname']);
}catch(Exception $e) {
return false;
}
}
public function create($collection,$article){
$table = $this->db->selectCollection($collection);
return $result = $table->insert($article);
}
public function get($page,$collection){
$currentPage = $page;
$articlesPerPage = $this->limit;
//number of article to skip from beginning
$skip = ($currentPage - 1) * $articlesPerPage;
$table = $this->db->selectCollection($collection); **//here reports an error**
$cursor = $table->find();
//total number of articles in database
$totalArticles = $cursor->count();
//total number of pages to display
$totalPages = (int) ceil($totalArticles / $articlesPerPage);
$cursor->sort(array('saved_at' => -1))->skip($skip)->limit($articlesPerPage);
//$cursor = iterator_to_array($cursor);
$data=array($currentPage,$totalPages,$cursor);
return $data;
}
public function getById($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new MongoId($id);
}
$table = $this->db->selectCollection($collection);
$cursor = $table->find(array('_id' => $id));
$article = $cursor->getNext();
if (!$article ){
return false ;
}
return $article;
}
public function delete($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->remove(array('_id'=>$id));
if (!$id){
return false;
}
return $result;
}
public function update($id,$collection,$article){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->update(
array('_id' => new \MongoId($id)),
array('$set' => $article)
);
if (!$id){
return false;
}
return $result;
}
public function commentId($id,$collection,$comment){
$postCollection = $this->db->selectCollection($collection);
$post = $postCollection->findOne(array('_id' => new \MongoId($id)));
if (isset($post['comments'])) {
$comments = $post['comments'];
}else{
$comments = array();
}
array_push($comments, $comment);
return $postCollection->update(
array('_id' => new \MongoId($id)),
array('$set' => array('comments' => $comments))
);
}
}

Session data changed in php

This is my code
class WcfClient {
public $wcfClient = null;
public $user = null;
public function __construct(){
if(isset($_SESSION['APIClient']) && $_SESSION['APIClient'] != null){
$this->wcfClient = $_SESSION['APIClient'];
}
}
public function __destruct(){
}
// Authanticate
private function Authenticate(){
global $_sogh_soapUrl, $_isDebug, $_sogh_header;
$wcargs = array();
$consumerAuthTicket = null;
if($this->wcfClient == null){
$args = array(
'clubname'=>'Wellness Institute at Seven Oaks',
'consumerName'=>'api',
'consumerPassword'=>'api'
);
try{
$wcargs = array(
'soap_version'=>SOAP_1_2
);
if($_isDebug){
$wcargs = array(
'soap_version'=>SOAP_1_2,
'proxy_host'=>"192.168.0.1",
'proxy_port'=>8080
);
}
// Connect to the API with soapclient
$soapAPIClient = new SoapClient($_sogh_soapUrl, $wcargs);
$response = $soapAPIClient->AuthenticateClubConsumer($args);
if(isset($response->AuthenticateClubConsumerResult)){
if(isset($response->AuthenticateClubConsumerResult->IsException) && $response->AuthenticateClubConsumerResult->IsException == true){
// some error occur
$this->wcfClient = null;
$_SESSION['APIClient'] = $this->wcfClient;
} else{
// set consumer ticket
$consumerAuthTicket = $response->AuthenticateClubConsumerResult->Value->AuthTicket;
// $loginData = $responseCode->ReturnValueOfConsumerLoginData;
$headers = array();
$headers[] = new SoapHeader($_sogh_header, "ConsumerAuthTicket", $consumerAuthTicket);
$soapAPIClient->__setSoapHeaders($headers);
// add to session
$this->wcfClient = $soapAPIClient;
$_SESSION['APIClient'] = $this->wcfClient;
}
}
} catch(SoapFault $fault){
$this->error('Fault: ' . $fault->faultcode . ' - ' . $fault->faultstring);
} catch(Exception $e){
$this->error('Error: ' . $e->getMessage());
}
}
return $this->wcfClient;
}
I store the soap client object in $_SESSION['APIClient'], but second times when run some data has been changed in session, I am use this class in drupal 7, I want to save the time using session, because authenticating takes long time.
Please help
Thank in advance

Categories