sample review_model file
<?php
//production
class Review_model extends CI_Model{
public function get_userDetails($emailid)
{
$this->load->database();
$sql = "SELECT * FROM user_m WHERE email ='$emailid'";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function post_userDetails($emailId,$password)
{
// First it will get the ip of the user and then by sending that it will get the location details.
$ipAddress = $this->input->ip_address();
$userLocation = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$ipAddress"));
// to get the latitude and longitude of the user with country name
$latitide = $userLocation['geoplugin_latitude'];
$longitude = $userLocation['geoplugin_longitude'];
$countryName = $userLocation['geoplugin_countryName'];
// generate a hash of email and password.
$salt = hash ( "sha256", $emailId . ' ' . $password);
// get a 10 digit random number.
$sqlUser = $this->getRandomAlphaNumericValue(10);
$sqlPassBuff = $this->getRandomAlphaNumericValue(10);
$sqlPass = substr(hash ( "sha256", $sqlPassBuff), 0, 10);
$sql="SELECT * FROM user_m WHERE email ='$emailId'";
$this->load->database();
$query = $this->db->query($sql);
if($query->num_rows() > 0){
return "F";
}else{
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$data = array(
'email' => $emailId,
'salt' => $salt,
'latitude' => $latitide,
'longitude' => $longitude,
'date_time_created' => $date,
'last_updated' => $date,
'country' => $countryName,
'all_time_requests' => '0',
'current_month_requests' => '0',
'is_active' => '1',
'mysql_user' => $sqlUser,
'mysql_password' => $sqlPass,
);
$query = $this->db->insert('user_m',$data);
if ($this->db->affected_rows() > 0)
{
$this->load->database();
$query = $this->db->query("CREATE USER '$sqlUser'@'localhost' IDENTIFIED BY '$sqlPass'");
return "S";
}
}
}
public function getRandomAlphaNumericValue($length) {
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
try {
$token .= $codeAlphabet[$this->crypto_rand_secure(0, $max - 1)];
} catch (Exception $e) {
}
}
return $token;
}
public function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd > $range);
return $min + $rnd;
}
public function post_createUserProject()
{
$projectName = $this->input->post('projectName');
$sqlUser = $this->input->post('mysqlUser');
$sql="SELECT * FROM project_m WHERE project_name = '$projectName'";
$this->load->database();
$query = $this->db->query($sql);
if($query->num_rows() > 0){
return "F";
}else{
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$data = array(
'project_name' => $this->input->post('projectName'),
'project_description' => $this->input->post('projectDescription'),
'date_time_created' => $date,
'last_updated' => $date,
'user_id' => $this->input->post('userId'),
'is_active' => $this->input->post('isActive'),
'all_time_requests' => $this->input->post('allTimeRequests'),
'current_month_requests' => $this->input->post('currentMonthRequests'),
);
$query = $this->db->insert('project_m',$data);
if ($this->db->affected_rows() > 0)
{
$this->load->database();
$query = $this->db->query("CREATE DATABASE $projectName");
$query = $this->db->query("GRANT ALL PRIVILEGES ON $projectName.* TO '$sqlUser'@localhost");
return "S";
}
}
}
public function get_projectDetails($userId)
{
$this->load->database();
$sql = "SELECT * FROM project_m WHERE user_id = '$userId' AND is_active = 1";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function post_updateProjectFlag(){
$this->load->database();
$projectId = $this->input->post('projectId');
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$status = $this->db->query("UPDATE project_m SET last_updated = '$date',is_active = 0 WHERE project_id = '$projectId'");
if ($this->db->affected_rows() > 0)
{return "S";}
else
{return "F";}
// $data = array(
// 'is_active' => '0',
// );
// $this->db->where('project_id', $this->input->post('projectId'));
// $this->db->update('project_m', $data);
}
public function get_fieldTypes()
{
$this->load->database();
$sql = "SELECT * FROM const_table_field_types";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function get_indexTypes()
{
$this->load->database();
$sql = "SELECT * FROM const_table_index_types";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function post_createUserProjectTable() {
$projectId = $this->input->post('projectId');
$tableName = $this->input->post('tableName');
$projectDb = $this->input->post('projectDB');
$sql="SELECT * FROM table_m WHERE table_name = '$tableName' AND project_id = $projectId";
$this->load->database();
$query = $this->db->query($sql);
if($query->num_rows() > 0){
return "F";
} else{
$this->load->database();
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$stringRepresentation= json_encode($this->input->post('columnJson'));
$json = json_decode($stringRepresentation);
// insert data into table_m and get the table id to insert data into table_fields_m.
$data = array(
'project_id' => $this->input->post('projectId'),
'user_id' => $this->input->post('userId'),
'date_time_created' => $date,
'last_updated' => $date,
'table_name' => $this->input->post('tableName'),
'table_description' => $this->input->post('tableDescription'),
'table_field_count' => $this->input->post('tableFieldCount'),
'is_active' => $this->input->post('isActive'),
);
$query = $this->db->insert('table_m',$data);
//to get the id of the last inserted row in table_m.
$tableId = $this->db->insert_id();
if ($this->db->affected_rows() > 0) {
$this->load->database();
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$json = json_decode($json);
foreach($json as $obj){
// to insert data into table_field_m.
$date2 = array(
'table_id' => $tableId,
'user_id' => $this->input->post('userId'),
'project_id' => $this->input->post('projectId'),
'field_name' => $obj->_cName,
'field_type' => $obj->_cType,
'can_be_null' => $obj->_cNull,
'length' => $obj->_cLength,
'default' => '1',
'a_i' => $obj->_cAi,
'index' => $obj->_cIndex,
'comments' => $this->input->post('userId'),
'date_time_created' => $date,
'last_updated' => $date,
);
$query2 = $this->db->insert('table_fields_m', $date2);
}
if ($this->db->affected_rows() > 0) {
//create a table after inserting all the rows in two tables.
$createTableString = '';
foreach($json as $obj){
$createTableString = $createTableString . $obj->_cName . ' ';
$createTableString = $createTableString . $obj->_cType;
$createTableString = $createTableString . '(' .$obj->_cLength . ')' . ' ';
if ($obj->_cNull == '0') {
$createTableString = $createTableString . 'NOT NULL' . ' ';
} else {
$createTableString = $createTableString . 'NULL' . ' ';
}
if ($obj->_cAi == '1') {
$createTableString = $createTableString . 'AUTO_INCREMENT' . ' ';
}
if ( $obj->_cIndex == 'PRIMARY') {
$createTableString = $createTableString . 'PRIMARY KEY' . ' ';
}
else if ($obj->_cIndex == 'UNIQUE') {
$createTableString = $createTableString . 'UNIQUE' . ' ';
}
$createTableString = $createTableString . ',';
}
$this->load->database();
// switch over to cubes DB
$this->db->query('use ' . $projectDb);
$finalString = substr($createTableString, 0,strlen($createTableString)-2);
$query = $this->db->query("CREATE TABLE IF NOT EXISTS $tableName ($finalString)");
return $finalString;
}
}
}
}
public function get_projectTableDetails($userId,$projectId)
{
$this->load->database();
$sql = "SELECT * FROM table_m WHERE project_id = $projectId AND user_id = $userId AND is_active = 1";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function get_projectTableColumnDetails($tableId)
{
$this->load->database();
$sql = "SELECT
tf.table_field_id,
tf.field_name,
tf.field_type,
tf.length,
tf.index,
IF(tf.can_be_null, 'true','false') as can_be_null,
IF(tf.a_i, 'true', 'false') as a_i,
t.table_name,
t.table_description
FROM table_m as t
RIGHT JOIN table_fields_m as tf
ON t.table_id = tf.table_id
WHERE t.table_id = $tableId";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function post_deleteTable(){
$this->load->database();
$tableId = $this->input->post('tableId');
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$status = $this->db->query("UPDATE table_m SET last_updated = '$date',is_active = 0 WHERE table_id = '$tableId'");
if ($this->db->affected_rows() > 0)
{return "S";}
else
{return "F";}
// $data = array(
// 'is_active' => '0',
// );
// $this->db->where('project_id', $this->input->post('projectId'));
// $this->db->update('project_m', $data);
}
public function get_tableData($tableName,$projectName)
{
$this->load->database();
// switch over to different database
$this->db->query('use ' . $projectName);
$sql = "SELECT * FROM $tableName";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function post_insertTableData() {
$tableData = $this->input->post('tableData');
$userId = $this->input->post('userId');
$tableName= $this->input->post('tableName');
$stringRepresentation= json_encode($this->input->post('tableData'));
$json2 = json_decode($stringRepresentation);
$json = json_decode($json2);
//create a table after inserting all the rows in two tables.
$createTableNameString = '';
$createTableValueString = '';
$tableValue = 0;
foreach($json as $obj){
$createTableNameString = $createTableNameString . $obj->_cName . ',';
}
$finalTableNameString = substr($createTableNameString, 0,strlen($createTableNameString)-1);
foreach($json as $obj){
if ($obj->$tableValue == '' && $obj->_cIndex == 'PRIMARY') {
$createTableValueString = $createTableValueString . 'NULL' . ',';
} else if ($obj->_cType == 'VARCHAR') {
$createTableValueString = $createTableValueString ."'". $obj->$tableValue ."'". ',';
} else {
$createTableValueString = $createTableValueString . $obj->$tableValue . ',';
}
}
$finalTableValueString = substr($createTableValueString, 0,strlen($createTableValueString)-1);
$this->load->database();
// switch over to cubes DB
$projectName= $this->input->post('projectName');
$this->db->query('use ' . $projectName);
$query = $this->db->query("INSERT INTO $tableName ($finalTableNameString) VALUES ($finalTableValueString)");
return "S";
}
public function post_deleteTableRow(){
$this->load->database();
$tableName = $this->input->post('tableName');
$projectName = $this->input->post('projectName');
$columnNameOne = $this->input->post('columnNameOne');
$columnNameValueOne = $this->input->post('columnNameValueOne');
$stringRepresentation= json_encode($this->input->post('columnNameValueOne'));
$json2 = json_decode($stringRepresentation);
$json = json_decode($json2);
$deleteTableValueString = $json-> $columnNameOne;
// switch over to cubes DB
$this->db->query('use ' . $projectName);
$status = $this->db->query("DELETE FROM $tableName WHERE $columnNameOne = $deleteTableValueString");
if ($this->db->affected_rows() > 0)
{return "S";}
else
{return "F";}
}
public function post_editTableRow(){
$this->load->database();
$projectName = $this->input->post('projectName');
$tableName = $this->input->post('tableName');
// switch over to cubes DB
$this->db->query('use ' . $projectName);
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$status = $this->db->query("UPDATE $tableName SET user_id = ,user_name = ,user_address = ,user_password = WHERE 1");
if ($this->db->affected_rows() > 0)
{return "S";}
else
{return "F";}
}
public function post_TableTest() {
$this->load->database();
// switch over to cubes DB
$this->db->query('use cubes_db');
$query = $this->db->query("CREATE TABLE Persons (PersonID int,LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City TIMESTAMP(10))");
return $query;
}
public function get_queryViewer($projectId,$userId)
{
$this->load->database();
$sql = "SELECT qm.project_id,qm.query_id,qm.query_location,qm.query_name,qm.last_updated,qm.query_type,
am.api_link,am.api_location,am.is_deployed,am.all_time_requests,am.current_month_requests,am.displayable_all_time_request
FROM queries_m as qm
LEFT JOIN api_m as am
ON qm.query_id = am.query_id
WHERE qm.project_id = $projectId AND qm.user_id = $userId";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function post_updateDeployFlag($deployStatus,$queryId){
$this->load->database();
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$status = $this->db->query("UPDATE api_m SET is_deployed= $deployStatus WHERE query_id = $queryId");
if ($this->db->affected_rows() > 0)
{return "S";}
else
{return "F";}
// $data = array(
// 'is_active' => '0',
// );
// $this->db->where('project_id', $this->input->post('projectId'));
// $this->db->update('project_m', $data);
}
public function get_specificProjectDetails($userId,$projectId)
{
$this->load->database();
$sql = "SELECT * FROM project_m WHERE user_id = '$userId' AND project_id = '$projectId'";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "F";
}
}
public function get_QueryResults($sqlQuery,$projectName)
{
$this->load->database();
$this->db->query('use ' . $projectName);
$sql = "$sqlQuery";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return 'F';
}
}
public function post_saveQueryDetails($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath)
{
/* if front end query id is 0 then it means query is saved for the first time so check whether the query name is already available
if available then send the response as F and ask the user to rename the query.*/
if ($frontEndQueryId !== '0') {
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_id = $frontEndQueryId AND project_id = $projectId AND user_id = $userId";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
/* checks whether the data base query name for the present query name is same or not*/
if (strcasecmp( $query->result_array()[0]['query_name'], $queryName) === 0 ) {
$savedQiIdDetails = $this->saveQueryDetailsDb($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath);
return $savedQiIdDetails;
} else {
/* when the query name is different it means the user want to change the query name to a different name.
check where the new name is not overriding the old query names for the same project.*/
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_name = '$queryName' AND project_id = $projectId AND user_id = $userId";
$query = $this->db->query($sql);
/* the new query name already exists then return f so that the user will rename and try to save the query one more time.*/
if ($query->num_rows() > 0) {
return "F";
} else {
$savedQiIdDetails = $this->saveQueryDetailsDb($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath);
return $savedQiIdDetails;
}
}
} else {
return "F";
}
} else {
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_name = '$queryName' AND project_id = $projectId AND user_id = $userId";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
return "F";
} else {
$savedQiIdDetails = $this->saveQueryDetailsDb($projectId, $frontEndQueryId, $userId, $queryName, $queryFields, $queryItemId, $sqlQuery, $userEmailAdd, $projectName, $queryDirPath);
return $savedQiIdDetails;
}
}
}
/* this function will get all the data required to
-> save the query string in a sql file in the desired directory (saveQueryTextFile)
-> saveQueryTextFile will return back the query location path
-> Inside saveQueryTextFile we are creating the directories with a function createDirectory
-> Inside saveQueryTextFile we used getQueryTextFileNames function to get the previously inserted file names so we are taking the last inserted file name and incrementing the teh file name by one.
-> */
public function saveQueryDetailsDb($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath) {
/* first it will check if there is any change in the query name if there is a change then it will change the
query name.(directory name)*/
$userEmailHash = hash ( "sha256", $userEmailAdd );
/* if there is any change in the query name then the query directory name should be changed*/
$old_folder_name = $queryDirPath;
$new_folder_name = "/var/www/html/backendless_io/user/$userEmailHash/sql/$projectName/$queryName";
if ($frontEndQueryId !== '0') {
rename($old_folder_name, $new_folder_name);
}
$queryPathLocation = $this->saveQueryTextFile($sqlQuery,$userEmailAdd,$projectName,$queryName);
// pass the query string and get the first word of the string base on the word set the field type.
$queryFirstWordArr = explode(' ',trim($sqlQuery));
if (strcasecmp($queryFirstWordArr[0], 'SELECT') == 0) {
$queryFirstWord = 'SELECT';
} else if (strcasecmp($queryFirstWordArr[0], 'INSERT') == 0) {
$queryFirstWord = 'INSERT';
} else if (strcasecmp($queryFirstWordArr[0], 'DELETE') == 0) {
$queryFirstWord = 'DELETE';
} else if (strcasecmp($queryFirstWordArr[0], 'UPDATE') == 0) {
$queryFirstWord = 'UPDATE';
} else {
$queryFirstWord = 'UNDEFINED';
}
$queryType = $queryFirstWord;
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
// getting query fields(variables) and converting to a array
$queryFieldsArray = explode(',', $queryFields);
/* getting the previously inserted query_input_m qi_id to delete it and insert the new updated values*/
$queryItemIdArray = array_map('intval', explode(',', $queryItemId));
/* checking whether the query id is there or not in our database if there it will update the values or it will insert.*/
// if the user is saving the query for the first time then the $frontEndQueryId will be '0'.
$sql="SELECT * FROM queries_m WHERE query_id = $frontEndQueryId";
$this->load->database();
$query = $this->db->query($sql);
if($query->num_rows() > 0){
// update the present details with the new one. (UPDATE query)
$this->load->database();
// update data into queries_m with the help of 'query_id';
$data = array(
'last_updated' => $date,
'query_name' => $queryName,
'query_location' => $queryPathLocation,
'query_type' => $queryType,
);
$this->db->where('query_id', $frontEndQueryId);
$this->db->update('queries_m', $data);
$this->load->database();
/*delete the previously inserted rows in the query_input_m with the help of previously inserted qi_id.*/
for ($i = 0; $i < sizeof($queryItemIdArray); $i++) {
$status = $this->db->query("DELETE FROM query_input_m WHERE query_input_m.qi_id = $queryItemIdArray[$i]");
}
if ($this->db->affected_rows() > 0) {
// again inserting the new update values into the query_input_m
for ($i = 0; $i < sizeof($queryFieldsArray); $i++) {
$data2 = array(
'query_id' => $frontEndQueryId,
'user_id' => $userId,
'project_id' => $projectId,
'field_name' => $queryFieldsArray[$i],
'date_time_created' => $date,
'last_updated' => $date,
);
$this->db->insert('query_input_m', $data2);
}
}
else
{return "Error while deleting the rows";}
// after inserting the values into query_input_m get the inserted qi_id and send it to front end.
$qi_idDetails = $this->getQueryInputIdSave($frontEndQueryId,$projectId,$userId);
return $qi_idDetails;
} else {
// insert query.
$this->load->database();
// insert data into query_m and get the query id to insert data into query_input_m.
$data = array(
'project_id' => $projectId,
'user_id' => $userId,
'date_created' => $date,
'last_updated' => $date,
'query_name' => $queryName,
'query_location' => $queryPathLocation,
'query_type' => $queryType,
);
$this->db->insert('queries_m', $data);
//to get the id of the last inserted row in queries_m.
$queryId = $this->db->insert_id();
/* inserting the new values into the query_input_m*/
for ($i = 0; $i < sizeof($queryFieldsArray); $i++) {
$data2 = array(
'query_id' => $queryId,
'user_id' => $userId,
'project_id' => $projectId,
'field_name' => $queryFieldsArray[$i],
'date_time_created' => $date,
'last_updated' => $date,
);
$this->db->insert('query_input_m', $data2);
}
// after inserting the values into query_input_m get the inserted qi_id and send it to front end.
$qi_idDetails = $this->getQueryInputIdSave($queryId,$projectId,$userId);
return $qi_idDetails;
}
}
public function saveQueryTextFile($sqlQuery,$userEmailAdd,$projectName,$queryName) {
$userEmailData = hash ( "sha256", $userEmailAdd );
$path = "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName/$queryName";
$latestQuerySavedFileName = $this->getQueryTextFileNames($path);
$latestQuerySavedFileName = (int)mb_substr($latestQuerySavedFileName, 0, NULL, 'utf-8');
$latestQuerySavedFileName = $latestQuerySavedFileName+1;
$queryFileName = $latestQuerySavedFileName;
if ( ! write_file( "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName/$queryName/$queryFileName.sql", $sqlQuery, "w+" ))
{
// it comes here when the there are no folders already created.
// paths of all the folders which has to be created.
$pathEmail = "/var/www/html/backendless_io/user/$userEmailData";
$pathSql = "/var/www/html/backendless_io/user/$userEmailData/sql";
$pathProjectName = "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName";
$pathQueryName = "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName/$queryName";
// calling a function to create the folders sequentially.
$this->createDirectory($pathEmail);
$this->createDirectory($pathSql);
$this->createDirectory($pathProjectName);
$this->createDirectory($pathQueryName);
//finally creating a text file with the query data.
if ( ! write_file( "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName/$queryName/$queryFileName.sql", $sqlQuery, "w+" )) {
// directories are not created properly and file is not inserted properly.
return 'F';
}else {
// file is inserted correctly and then we are giving back the saved file path
return "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName/$queryName/$queryFileName.sql";
}
}
else {
// file is inserted correctly and then we are giving back the saved file path
return "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName/$queryName/$queryFileName.sql";
}
}
/* this method is used to create directories when the path is given as a parameter.*/
function createDirectory($path) {
if(!is_dir($path)) //create the folder if it's not already exists
{
mkdir($path,0777,TRUE);
} else {
return 'unable to create path folder';
}
}
/*// this function is used to get the already saved file names in an array if we give the path.
// this is used to increment the file number when the same file is saved again and again.*/
public function getQueryTextFileNames($path)
{
$pathQueryName = $path;
$controllers = get_filenames($pathQueryName);
if(!empty($controllers)) {
$numArray = array();
for ($x = 0; $x < count($controllers) ; $x++) {
$numArray[] = (int)substr($controllers[$x], 0, -4);
rsort($numArray);
}
return (string)current($numArray);
}else {
return '0';
}
}
/* this method will get the qi_id and query_id from the query_input_m table*/
public function getQueryInputIdSave($queryid, $projectid, $userid) {
$this->load->database();
$sql = "SELECT qi.qi_id, qi.query_id, q.query_location FROM query_input_m AS qi
LEFT JOIN queries_m AS q ON q.query_id = qi.query_id
WHERE qi.query_id = $queryid AND qi.project_id = $projectid AND qi.user_id = $userid";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "some error in getQueryInput";
}
}
public function get_queryInputVariableDetails($queryId,$projectId,$userId){
$qi_idDetails = $this->getQueryInputIdSave($queryId,$projectId,$userId);
return $qi_idDetails;
}
/* for getting the latest stored query string */
public function get_sqlQueryString($path){
$queryString = file_get_contents($path);
return $queryString;
}
public function post_deployQueryDetails($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath,$apiDirPath)
{
if ($apiDirPath !== ""){
unlink($apiDirPath);
}
$userEmailHash = hash ( "sha256", $userEmailAdd);
$userProjectHash = hash ( "sha256", $projectName);
$analyticsFileName = "_analytics_".substr(hash ( "sha256",hash ( "sha256", hash ( "sha256", hash ( "sha256", "$projectName + backendless")))), 0, 16);
$dbConfigFileName = "_db_config";
$dbConnectionFileName = "_db_connection";
$apiName = $queryName;
// project name = hash of first 15 characters.
$userProjectHash = substr($userProjectHash, 0, 15);
/* if front end query id is 0 then it means query is saved for the first time so check whether the query name is already available
if available then send the response as F and ask the user to rename the query.*/
if ($frontEndQueryId !== '0') {
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_id = $frontEndQueryId AND project_id = $projectId AND user_id = $userId";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
/* checks whether the data base query name for the present query name is same or not*/
if (strcasecmp( $query->result_array()[0]['query_name'], $queryName) === 0 ) {
$savedQiIdDetails = $this->saveQueryDetailsDb($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath);
} else {
/* when the query name is different it means the user want to change the query name to a different name.
check where the new name is not overriding the old query names for the same project.*/
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_name = '$queryName' AND project_id = $projectId AND user_id = $userId";
$query = $this->db->query($sql);
/* the new query name already exists then return f so that the user will rename and try to save the query one more time.*/
if ($query->num_rows() > 0) {
return "F";
} else {
$savedQiIdDetails = $this->saveQueryDetailsDb($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath);
}
}
} else {
return "F";
}
} else {
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_name = '$queryName' AND project_id = $projectId AND user_id = $userId";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
return "F";
} else {
$savedQiIdDetails = $this->saveQueryDetailsDb($projectId, $frontEndQueryId, $userId, $queryName, $queryFields, $queryItemId, $sqlQuery, $userEmailAdd, $projectName, $queryDirPath);
}
}
// /*before deploying first save the file so that in between save and deploy any changes are there then they will be updated.*/
// $savedQiIdDetails = $this->saveQueryDetailsDb($projectId,$frontEndQueryId,$userId,$queryName,$queryFields,$queryItemId,$sqlQuery,$userEmailAdd,$projectName,$queryDirPath);
$analytics_data_string = $this->getAnalyticsString($projectName);
$db_config_data_string = $this->getDbConfigString($projectName,$userId);
$db_connection_data_string = $this->getDbConnection();
$select_api_data_string = $this->getSelectApi($projectName, 234,$sqlQuery,$projectId,(int)$savedQiIdDetails[0]["query_id"],$userId);
$create_update_delete_api_data_string = $this->getCreateUpdateDeleteApi($projectName, 234,$sqlQuery,$projectId,(int)$savedQiIdDetails[0]["query_id"],$userId);
$url = $this->createPhpFiles($userEmailHash,$userProjectHash,$analyticsFileName,$analytics_data_string);
$url = $this->createPhpFiles($userEmailHash,$userProjectHash,$dbConfigFileName,$db_config_data_string);
$url = $this->createPhpFiles($userEmailHash,$userProjectHash,$dbConnectionFileName,$db_connection_data_string);
// pass the query string and get the first word of the string base on the word set the field type.
$queryFirstWordArr = explode(' ',trim($sqlQuery));
if (strcasecmp($queryFirstWordArr[0], 'SELECT') == 0) {
$apiLocation = $this->createPhpFiles($userEmailHash,$userProjectHash,$apiName,$select_api_data_string);
} else if (strcasecmp($queryFirstWordArr[0], 'INSERT') == 0) {
$apiLocation = $this->createPhpFiles($userEmailHash,$userProjectHash,$apiName,$create_update_delete_api_data_string);
} else if (strcasecmp($queryFirstWordArr[0], 'DELETE') == 0) {
$apiLocation = $this->createPhpFiles($userEmailHash,$userProjectHash,$apiName,$create_update_delete_api_data_string);
} else if (strcasecmp($queryFirstWordArr[0], 'UPDATE') == 0) {
$apiLocation = $this->createPhpFiles($userEmailHash,$userProjectHash,$apiName,$create_update_delete_api_data_string);
} else {
return "D";
}
$this->insertORUpdareApiMTable($apiLocation,(int)$savedQiIdDetails[0]["query_id"],$projectId,$userId);
$qi_details = $this->getQueryInputIdDeploy((int)$savedQiIdDetails[0]["query_id"],$projectId,$userId);
return $qi_details;
}
public function createPhpFiles($userEmailHash,$userProjectHash,$phpFileName, $fileDataString) {
if ( ! write_file( "/var/www/html/backendless_io/user/$userEmailHash/api/$userProjectHash/$phpFileName.php", $fileDataString, "w+" ))
{
// it comes here when the there are no folders already created.
// paths of all the folders which has to be created.
/*start the deployment part*/
$pathApi = "/var/www/html/backendless_io/user/$userEmailHash/api";
$pathProjectHash = "/var/www/html/backendless_io/user/$userEmailHash/api/$userProjectHash";
// calling a function to create the folders sequentially.
$this->createDirectory($pathApi);
$this->createDirectory($pathProjectHash);
//finally creating a text file with the query data.
if ( ! write_file( "/var/www/html/backendless_io/user/$userEmailHash/api/$userProjectHash/$phpFileName.php", $fileDataString, "w+" )) {
// directories are not created properly and file is not inserted properly.
return 'F';
}else {
// file is inserted correctly and then we are giving back the saved file path
return "/var/www/html/backendless_io/user/$userEmailHash/api/$userProjectHash/$phpFileName.php";
}
}
else {
// file is inserted correctly and then we are giving back the saved file path
return "/var/www/html/backendless_io/user/$userEmailHash/api/$userProjectHash/$phpFileName.php";
}
}
public function getAnalyticsString($projectName) {
$projectNameHash = hash ( "sha256", hash ( "sha256", hash ( "sha256", $projectName)));
// All the variables required to create analytics file.
$clientIP = "clientIP";
$clientGeoObject = "clientGeoObject";
$clientGeoObjectCountry = "clientGeoObject[\"country\"]";
$clientGeoObjectLatitude = "clientGeoObject[\"latitude\"]";
$clientGeoObjectLongitude = "clientGeoObject[\"longitude\"]";
$clientCountry = "clientCountry";
$clientLat = "clientLat";
$clientLong = "clientLong";
$ip = "ip";
$result = "result";
$response = "response";
$apiReferenceNumber = "apiReferenceNumber";
$execution_time = "execution_time";
// First it will get the ip of the user and then by sending that it will get the location details.
$ipAddress = $this->input->ip_address();
$userLocation = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$ipAddress"));
/* the string which is going to insert in to _analytics_hjg75.php file. */
$_analytics_string = "<?php
function analytics_$projectNameHash($$apiReferenceNumber, $$execution_time){
$$clientIP = getClientIP_$projectNameHash();
$$clientGeoObject = getClientLocation_$projectNameHash($$clientIP);
$$clientCountry = $$clientGeoObjectCountry;
$$clientLat = $$clientGeoObjectLatitude;
$$clientLong = $$clientGeoObjectLongitude;
callAPI_$projectNameHash($$apiReferenceNumber, $$execution_time, $$clientIP, $$clientCountry, $$clientLat, $$clientLong);
}
function getClientIP_$projectNameHash(){
return \"$ipAddress\";
}
function getClientLocation_$projectNameHash($$ip){
$$result = array(
country => \"$userLocation[geoplugin_countryName]\",
latitude => \"$userLocation[geoplugin_latitude]\",
longitude => \"$userLocation[geoplugin_longitude]\"
);
return $$result;
}
function callAPI_$projectNameHash($$apiReferenceNumber, $$execution_time, $$clientIP, $$clientCountry, $$clientLat, $$clientLong){
$$response = file_get_contents('http://example.com/path/to/api/call.php?ip=' . $$clientIP . '&country=' . $$clientCountry . '&latitude=' . $$clientLat . '&longitude=' . $$clientLong . '&execution_time' . $$execution_time . '&api_reference_number' . $$apiReferenceNumber);
}
?>";
return $_analytics_string;
}
public function getDbConfigString($projectName,$userId) {
$this->load->database();
$sql = "SELECT * FROM user_m WHERE user_id = $userId";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
$mySqlUserName = $query->result_array()[0]['mysql_user'];
$mySqlPassword = $query->result_array()[0]['mysql_password'];
$_db_config_string = "<?php
define('USERNAME', \"$mySqlUserName\");
define('PASSWORD', \"$mySqlPassword\");
define('DATABASE_NAME', \"$projectName\");
define('SERVER_NAME', \"localhost\");
define('STATUS_SUCCESS', \"success\");
define('STATUS_FAIL', \"fail\");
define('STATUS_ERROR', \"error\");
/*??*/
define('CREDIT_NAME_PREFIX', \"BC\");
define('BACKENDLESS_CONSTANT', 400);
/*leave it as of now*/
define('RELAY_URL', \"http://63.142.251.219/backendless/something/blahblah\");
// Success Messages
define('SUCCESS_CREATE_OPERATION', \"Insert query successfully executed\");
define('SUCCESS_READ_OPERATION', \"Read query successfully executed\");
define('SUCCESS_READ_OPERATION_NO_ROW', \"Read query successfully executed, but 0 rows outputted\");
define('SUCCESS_UPDATE_OPERATION', \"Update query successfully executed\");
define('SUCCESS_DELETE_OPERATION', \"Delete query successfully executed\");
// Fail Messages
define('FAIL_REQUIRED_PARAMETERS_NOT_PRESENT', \"Fail. Required parameters not present\");
// Error Messages
define('ERROR_INTERNAL_API_ERROR', \"Error, Internal API error. Re-call API\");
?>
";
return $_db_config_string;
}
else {
return "F";
}
}
public function getDbConnection() {
$conn = "conn";
$_db_connection_string = "
<?php
require('_db_config.php');
function getDatabaseConnection(){
$$conn = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD, DATABASE_NAME);
if (!$$conn) {
die(\"Connection failed: \" . mysqli_connect_error());
}
return $$conn;
}
function closeDatabaseConnection($$conn){
mysqli_close($$conn);
}
?>";
return $_db_connection_string;
}
public function getSelectApi($projectName, $apiId, $sqlQuery,$projectId,$queryId,$userId) {
$this->load->database();
$sql = " SELECT * FROM `query_input_m` WHERE `query_id` = $queryId AND `project_id` = $projectId AND`user_id` = $userId";
$query = $this->db->query($sql);
if($query->num_rows() > 0) {
$variableNameString = '';
$getVariableString = '';
$postVariableString = '';
$getToVarString = '';
$postToVarString = '';
$varToJsonString = '';
$varEdgeCaseString = '';
$crudVarString = '';
// for getting the variable string $variable1 = null;
for ($i = 0; $i < count($query->result_array()); $i++) {
$variableName[] = $query->result_array()[$i]['field_name'] ." = null;\n";
$variableNameString = $variableNameString . $variableName[$i];
}
$variableNameString = str_replace("@","$", $variableNameString,$i);
// for getting the if condition get string isset($_GET["variable1"])
for ($j = 0; $j < count($query->result_array()); $j++) {
$getVariableName[] = 'isset($_GET["' .$query->result_array()[$j]['field_name']. '"]) && ';
$getVariableString = $getVariableString . $getVariableName[$j];
}
$getVariableString = substr( $getVariableString, 0, -4 );
$getVariableString = str_replace("@","", $getVariableString,$j);
// for getting the if condition get string isset($_POST["variable1"])
for ($k = 0; $k < count($query->result_array()); $k++) {
$postVariableName[] = 'isset($_POST["' .$query->result_array()[$k]['field_name']. '"]) && ';
$postVariableString = $postVariableString . $postVariableName[$k];
}
$postVariableString = substr($postVariableString, 0, -4 );
$postVariableString = str_replace("@","", $postVariableString,$k);
// for getting the variable string $variable1 = $_GET["variable1"];;
for ($l = 0; $l < count($query->result_array()); $l++) {
$assignGetToVar[] = $query->result_array()[$l]['field_name'] ." = " . '$_GET["' .str_replace("@","", $query->result_array()[$l]['field_name'],$a). '"];';
$getToVarString = $getToVarString . $assignGetToVar[$l];
}
$getToVarString = str_replace("@","$", $getToVarString,$l);
// for getting the variable string $variable1 = $_POST["variable1"];;
for ($m = 0; $m < count($query->result_array()); $m++) {
$assignPostToVar[] = $query->result_array()[$m]['field_name'] ." = " . '$_POST["' .str_replace("@","", $query->result_array()[$m]['field_name'],$b). '"];';
$postToVarString = $postToVarString . $assignPostToVar[$m];
}
$postToVarString = str_replace("@","$", $postToVarString,$m);
// for getting the variable string $variable1 = $json_obj -> variable1;
for ($n = 0; $n < count($query->result_array()); $n++) {
$assignVarToJson[] = $query->result_array()[$n]['field_name'] ." = " . '$json_obj ->' .str_replace("@","", $query->result_array()[$n]['field_name'],$a). ';';
$varToJsonString = $varToJsonString . $assignVarToJson[$n];
}
$varToJsonString = str_replace("@","$", $varToJsonString,$n);
// for getting the variable string Edge Case condition -> ($variable1 == null) || ($variable2 == null)
for ($o = 0; $o < count($query->result_array()); $o++) {
$assignEdgeCaseCond[] = '('.$query->result_array()[$o]['field_name'] .'== null) || ';
$varEdgeCaseString = $varEdgeCaseString . $assignEdgeCaseCond[$o];
}
$varEdgeCaseString = substr($varEdgeCaseString, 0, -4 );
$varEdgeCaseString = str_replace("@","$", $varEdgeCaseString,$o);
// for getting the variable string perform CRUD operation -> $variable1, $variable2
for ($p = 0; $p < count($query->result_array()); $p++) {
$assignCRUDVar[] = $query->result_array()[$p]['field_name'] . ',';
$crudVarString = $crudVarString . $assignCRUDVar[$p];
}
$crudVarString = substr($crudVarString, 0, -1 );
$crudVarString = str_replace("@","$", $crudVarString,$p);
/*-------------------------------------------------------------------------------------*/
$apiIdHash = substr(hash ( "sha256", "$projectName + $apiId"), 0, 10);
$projectNameHash = hash ( "sha256", hash ( "sha256", hash ( "sha256", $projectName)));
$start = "start ";
$successMessage = "successMessage";
$message = "message";
$status = "status";
$response = "response";
// $variable1 = "variable1";
// $variable2 = "variable2";
//
// $get1 = "_GET[\"variable1\"]";
// $get2 = "_GET[\"variable2\"]";
//
// $post1 = "_POST[\"variable1\"]";
// $post2 = "_POST[\"variable2\"]";
$formattedSqlQuery = str_replace("@","$", $sqlQuery,$c);
$json_str = "json_str";
$json_obj = "json_obj";
$messageStatus = "messageStatus";
$messageStatusMessage = "messageStatus[\"message\"]";
$messageStatusStatus = "messageStatus[\"status\"]";
$messageStatusResponse = "messageStatus[\"response\"]";
$execution_time = "execution_time";
$conn = "conn";
$sql = "sql";
$result = "result";
$row = "row";
$output = "output";
$v = "v";
$apiID_ = "apiID_";
$select_api = "<?php
# Enable this comment if there are any errors while you develop after testing remove it
//error_reporting(E_ALL);
//ini_set('display_errors', 'On');
# https://labs.omniti.com/labs/jsend
$$start = microtime(true);
require_once('_db_connection.php');
$$successMessage = SUCCESS_READ_OPERATION;
$$message = \"\";
$$status = \"\";
$$response = \"\";
$variableNameString
# --[start] Making sure all desired variables are passed in the API
# and assigning it to variables above
if($getVariableString){
# GET Request
$getToVarString
}else if($postVariableString){
# POST Request as parameters
$postToVarString
}else if(file_get_contents('php://input') !== \"\" || file_get_contents('php://input') !== null){
# Post Request -> As JSON Body
$$json_str = file_get_contents('php://input');
$$json_obj = json_decode($$json_str);
$varToJsonString
}else{
$$status = STATUS_FAIL;
$$message = FAIL_REQUIRED_PARAMETERS_NOT_PRESENT;
}
# --[end]
# --[start] Edge Case -> if this is called then this code is not working
if($$status != STATUS_FAIL){
if(($varEdgeCaseString)){
$$status = STATUS_ERROR;
$$message = ERROR_INTERNAL_API_ERROR;
}
}
# --[end]
# --[start] proceed only if all flags are clear,
# perform CRUD operation, set message
if(($$status != STATUS_ERROR) && ($$status != STATUS_FAIL)){
$$messageStatus = crudQuery($$successMessage, $crudVarString);
$$message = $$messageStatusMessage;
$$status = $$messageStatusStatus;
$$response = $$messageStatusResponse;
}
# --[end]
$$execution_time = microtime(true) - $$start;
outputRestApi($$status, $$message, $$execution_time, $$response);
function crudQuery($$successMessage, $crudVarString){
$$conn = getDatabaseConnection();
$$sql = getSQLQuery($crudVarString);
$$result = mysqli_query($$conn, $$sql);
$$response = array();
if (mysqli_num_rows($$result) > 0) {
while($$row = mysqli_fetch_assoc($$result)) {
array_push($$response,$$row);
}
$$message = $$successMessage;
$$status = STATUS_SUCCESS;
} else if(!$result) {
$$message = \"Error: \" . $$sql . \"<br>\" . mysqli_error($$conn);
$$status = STATUS_ERROR;
}else{
$$message = SUCCESS_READ_OPERATION_NO_ROW;
$$status = STATUS_SUCCESS;
}
closeDatabaseConnection($$conn);
return Array(
message => $$message,
status => $$status,
response => $$response
);
}
function outputRestApi($$status, $$message, $$execution_time, $$response){
$$output = array(
'response' => array(
'status' => $$status,
'message' => $$message,
'api_cost' => apiCost($$execution_time),
'result' => $$response
)
);
echo json_encode($$output);
}
function getSQLQuery($crudVarString) {
return \"$formattedSqlQuery\";
}
function apiCost($$execution_time){
$$v = round($$execution_time*BACKENDLESS_CONSTANT,3) . \" \" . CREDIT_NAME_PREFIX;
return $$v;
}
?>
<?php
require_once('_analytics_A2FAA5FBD72DCA98.php');
# In this example lets say api_id => 234 and project name is => devlogs
# to obtain variable name below perform (\"apiID_\" + first_10_digits(sha256(\"d evlogs + 234\")))
# use website https://passwordsgenerator.net/sha256-hash-generator/ and enter -> devlogs + 234 for learning purpose
$$apiID_$apiIdHash = $apiId ;
analytics_$projectNameHash($$apiID_$apiIdHash, $$execution_time)
?>
";
return $select_api;
} else {
return "F";
}
}
public function insertORUpdareApiMTable($apiLocation,$queryId,$projectId,$userId) {
$this->load->database();
$sql = "SELECT * FROM `api_m` WHERE `query_id` = $queryId AND `project_id` = $projectId AND `user_id` = $userId";
$query = $this->db->query($sql);
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
if($query->num_rows() > 0)
{
// update the present details with the new one. (UPDATE query)
$this->load->database();
// update data into queries_m with the help of 'query_id';
$data = array(
'api_location' => $apiLocation,
'is_deployed' => 1,
'last_updated' => $date,
);
$this->db->where('api_id', $query->result_array()[0]["api_id"]);
$this->db->update('api_m', $data);
}
else {
$this->load->database();
// insert data into api_m.
$data = array(
'query_id' => $queryId,
'project_id' => $projectId,
'user_id' => $userId,
'api_location' => $apiLocation,
'is_deployed' => 1,
'all_time_requests' => 0,
'current_month_requests' => 0,
'displayable_all_time_request' => 0,
'date_time_created' => $date,
'last_updated' => $date,
);
$query = $this->db->insert('api_m',$data);
}
}
/* this method will get the qi_id and query_id from the query_input_m table and apiLocation from api_m table*/
public function getQueryInputIdDeploy($queryid, $projectid, $userid) {
$this->load->database();
$sql = "SELECT qi.qi_id, qi.query_id, q.query_location, a.api_location FROM query_input_m AS qi
LEFT JOIN queries_m AS q ON q.query_id = qi.query_id
LEFT JOIN api_m AS a ON q.query_id = a.query_id
WHERE qi.query_id = $queryid AND qi.project_id = $projectid AND qi.user_id = $userid";
$query = $this->db->query($sql);
if($query->num_rows() > 0)
{
return $query->result_array();
}
else {
return "some error in getQueryInput";
}
}
public function getCreateUpdateDeleteApi($projectName, $apiId, $sqlQuery,$projectId,$queryId,$userId) {
$this->load->database();
$sql = " SELECT * FROM `query_input_m` WHERE `query_id` = $queryId AND `project_id` = $projectId AND`user_id` = $userId";
$query = $this->db->query($sql);
if($query->num_rows() > 0) {
$variableNameString = '';
$getVariableString = '';
$postVariableString = '';
$getToVarString = '';
$postToVarString = '';
$varToJsonString = '';
$varEdgeCaseString = '';
$crudVarString = '';
// for getting the variable string $variable1 = null;
for ($i = 0; $i < count($query->result_array()); $i++) {
$variableName[] = $query->result_array()[$i]['field_name'] ." = null;\n";
$variableNameString = $variableNameString . $variableName[$i];
}
$variableNameString = str_replace("@","$", $variableNameString,$i);
// for getting the if condition get string isset($_GET["variable1"])
for ($j = 0; $j < count($query->result_array()); $j++) {
$getVariableName[] = 'isset($_GET["' .$query->result_array()[$j]['field_name']. '"]) && ';
$getVariableString = $getVariableString . $getVariableName[$j];
}
$getVariableString = substr( $getVariableString, 0, -4 );
$getVariableString = str_replace("@","", $getVariableString,$j);
// for getting the if condition get string isset($_POST["variable1"])
for ($k = 0; $k < count($query->result_array()); $k++) {
$postVariableName[] = 'isset($_POST["' .$query->result_array()[$k]['field_name']. '"]) && ';
$postVariableString = $postVariableString . $postVariableName[$k];
}
$postVariableString = substr($postVariableString, 0, -4 );
$postVariableString = str_replace("@","", $postVariableString,$k);
// for getting the variable string $variable1 = $_GET["variable1"];;
for ($l = 0; $l < count($query->result_array()); $l++) {
$assignGetToVar[] = $query->result_array()[$l]['field_name'] ." = " . '$_GET["' .str_replace("@","", $query->result_array()[$l]['field_name'],$a). '"];';
$getToVarString = $getToVarString . $assignGetToVar[$l];
}
$getToVarString = str_replace("@","$", $getToVarString,$l);
// for getting the variable string $variable1 = $_POST["variable1"];;
for ($m = 0; $m < count($query->result_array()); $m++) {
$assignPostToVar[] = $query->result_array()[$m]['field_name'] ." = " . '$_POST["' .str_replace("@","", $query->result_array()[$m]['field_name'],$b). '"];';
$postToVarString = $postToVarString . $assignPostToVar[$m];
}
$postToVarString = str_replace("@","$", $postToVarString,$m);
// for getting the variable string $variable1 = $json_obj -> variable1;
for ($n = 0; $n < count($query->result_array()); $n++) {
$assignVarToJson[] = $query->result_array()[$n]['field_name'] ." = " . '$json_obj ->' .str_replace("@","", $query->result_array()[$n]['field_name'],$a). ';';
$varToJsonString = $varToJsonString . $assignVarToJson[$n];
}
$varToJsonString = str_replace("@","$", $varToJsonString,$n);
// for getting the variable string Edge Case condition -> ($variable1 == null) || ($variable2 == null)
for ($o = 0; $o < count($query->result_array()); $o++) {
$assignEdgeCaseCond[] = '('.$query->result_array()[$o]['field_name'] .'== null) || ';
$varEdgeCaseString = $varEdgeCaseString . $assignEdgeCaseCond[$o];
}
$varEdgeCaseString = substr($varEdgeCaseString, 0, -4 );
$varEdgeCaseString = str_replace("@","$", $varEdgeCaseString,$o);
// for getting the variable string perform CRUD operation -> $variable1, $variable2
for ($p = 0; $p < count($query->result_array()); $p++) {
$assignCRUDVar[] = $query->result_array()[$p]['field_name'] . ',';
$crudVarString = $crudVarString . $assignCRUDVar[$p];
}
$crudVarString = substr($crudVarString, 0, -1 );
$crudVarString = str_replace("@","$", $crudVarString,$p);
/*-------------------------------------------------------------------------------------*/
$apiIdHash = substr(hash ( "sha256", "$projectName + $apiId"), 0, 10);
$projectNameHash = hash ( "sha256", hash ( "sha256", hash ( "sha256", $projectName)));
$start = "start ";
$successMessage = "successMessage";
$message = "message";
$status = "status";
// $variable1 = "variable1";
// $variable2 = "variable2";
//
// $get1 = "_GET[\"variable1\"]";
// $get2 = "_GET[\"variable2\"]";
//
// $post1 = "_POST[\"variable1\"]";
// $post2 = "_POST[\"variable2\"]";
$formattedSqlQuery = str_replace("@","$", $sqlQuery,$c);
$json_str = "json_str";
$json_obj = "json_obj";
$messageStatus = "messageStatus";
$messageStatusMessage = "messageStatus[\"message\"]";
$messageStatusStatus = "messageStatus[\"status\"]";
$messageStatusResponse = "messageStatus[\"response\"]";
$execution_time = "execution_time";
$conn = "conn";
$sql = "sql";
$result = "result";
$row = "row";
$output = "output";
$v = "v";
$apiID_ = "apiID_";
$create_api = "<?php
# Enable this comment if there are any errors while you develop after testing remove it
//error_reporting(E_ALL);
//ini_set('display_errors', 'On');
# https://labs.omniti.com/labs/jsend
$$start = microtime(true);
require_once('_db_connection.php');
$$successMessage = SUCCESS_READ_OPERATION;
$$message = \"\";
$$status = \"\";
$variableNameString
# --[start] Making sure all desired variables are passed in the API
# and assigning it to variables above
if($getVariableString){
# GET Request
$getToVarString
}else if($postVariableString){
# POST Request as parameters
$postToVarString
}else if(file_get_contents('php://input') !== \"\" || file_get_contents('php://input') !== null){
# Post Request -> As JSON Body
$$json_str = file_get_contents('php://input');
$$json_obj = json_decode($$json_str);
$varToJsonString
}else{
$$status = STATUS_FAIL;
$$message = FAIL_REQUIRED_PARAMETERS_NOT_PRESENT;
}
# --[end]
# --[start] Edge Case -> if this is called then this code is not working
if($$status != STATUS_FAIL){
if(($varEdgeCaseString)){
$$status = STATUS_ERROR;
$$message = ERROR_INTERNAL_API_ERROR;
}
}
# --[end]
# --[start] proceed only if all flags are clear,
# perform CRUD operation, set message
if(($$status != STATUS_ERROR) && ($$status != STATUS_FAIL)){
$$messageStatus = crudQuery($$successMessage, $crudVarString);
$$message = $$messageStatusMessage;
$$status = $$messageStatusStatus;
}
# --[end]
$$execution_time = microtime(true) - $$start;
outputRestApi($$status, $$message, $$execution_time);
function crudQuery($$successMessage, $crudVarString){
$$conn = getDatabaseConnection();
$$sql = getSQLQuery($crudVarString);
$$result = mysqli_query($$conn, $$sql);
if ($$result) {
$$message = $$successMessage;
$$status = STATUS_SUCCESS;
} else {
$$message = \"Error: \" . $$sql . \"<br>\" . mysqli_error($$conn);
$$status = STATUS_ERROR;
}
closeDatabaseConnection($$conn);
return Array(
message => $$message,
status => $$status
);
}
function outputRestApi($$status, $$message, $$execution_time){
$$output = array(
'response' => array(
'status' => $$status,
'message' => $$message,
'api_cost' => apiCost($$execution_time),
)
);
echo json_encode($$output);
}
function getSQLQuery($crudVarString) {
return \"$formattedSqlQuery\";
}
function apiCost($$execution_time){
$$v = round($$execution_time*BACKENDLESS_CONSTANT,3) . \" \" . CREDIT_NAME_PREFIX;
return $$v;
}
?>
<?php
require_once('_analytics_A2FAA5FBD72DCA98.php');
# In this example lets say api_id => 234 and project name is => devlogs
# to obtain variable name below perform (\"apiID_\" + first_10_digits(sha256(\"d evlogs + 234\")))
# use website https://passwordsgenerator.net/sha256-hash-generator/ and enter -> devlogs + 234 for learning purpose
$$apiID_$apiIdHash = $apiId ;
analytics_$projectNameHash($$apiID_$apiIdHash, $$execution_time)
?>
";
return $create_api;
} else {
return "F";
}
}
/*--------------------------------------------------TESTING---------------------------------------------*/
/* only for testing not used in live.*/
public function get_queryFileNames($sqlQuery,$userEmailAdd,$projectName,$queryName){
$userEmailData = hash ( "sha256", $userEmailAdd );
$pathQueryName = "/var/www/html/backendless_io/user/$userEmailData/sql/$projectName/$queryName";
$controllers = get_filenames($pathQueryName);
return $controllers;
}
public function get_deleteDirectory()
{
if ( ! delete_files('/var/www/html/backendless_io/user/73163f95f0554068d87039a5b2a7891feaa1630a0710560fd1174aebcfb2e051/api/fe5137839501d7f', TRUE))
{
return 'File Not Deleted';
}
else
{
return 'File Deleted!';
}
// if ( !unlink("/var/www/html/backendless_io/user/jas/api/caa188a35bccd66/getUsers.php"))
// {
// return 'File Not Deleted';
// }
// else
// {
// return 'File Deleted!';
// }
}
public function testFile() {
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_id = 1 AND project_id = 1 AND user_id = 1";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
if (strcasecmp( $query->result_array()[0]['query_name'], "getuserdetails2") === 0 ) {
return "query name same";
} else {
$this->load->database();
$sql = "SELECT * FROM queries_m WHERE query_name = 'getquerydetails2' AND project_id = 1 AND user_id = 1";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
return "query name already exists for this project please rename your query";
} else {
return "allow query name to change to this new name";
}
}
} else {
return "query does not exists";
}
}
public function testFile2() {
// First it will get the ip of the user and then by sending that it will get the location details.
$ipAddress = $this->input->ip_address();
$userLocation = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$ipAddress"));
$latitide = $userLocation['geoplugin_latitude'];
$longitude = $userLocation['geoplugin_longitude'];
$countryName = $userLocation['geoplugin_countryName'];
$salt = hash ( "sha256", 'vjvr03@gmail.com' . ' ' . '123456');
$sqlUser = $this->getRandomAlphaNumericValue(10);
$sqlPassBuff = $this->getRandomAlphaNumericValue(10);
$sqlPass = substr(hash ( "sha256", $sqlPassBuff), 0, 10);
// return $latitide.$countryName.$longitude.$salt.$sqlUser;
return $latitide;
}
/*--------------------------------------------------TESTING ENDS---------------------------------------------*/
}
?>