Google Cloud Api in Sales : ps

This commit is contained in:
VE10-Sanjeev 2023-02-15 18:08:19 +05:30
parent 0468de1738
commit e179c98d21
7 changed files with 3364 additions and 189 deletions

View File

@ -22,12 +22,14 @@
"tecnickcom/tcpdf": "^6.6",
"phpmailer/phpmailer": "^6.0",
"php-curl-class/php-curl-class": "^8.5",
"guzzlehttp/guzzle": "^6.3",
"guzzlehttp/guzzle": "^7.4.4",
"twilio/sdk": "^6.10",
"phpoffice/phpspreadsheet": "^1.27",
"johnathanmiller/secure-env-php": "^2.0",
"google/apiclient": "^2.0",
"jurosh/pdf-merge": "^2.1"
"jurosh/pdf-merge": "^2.1",
"symfony/symfony": "^3.0",
"google/cloud": "^0.197.0"
},
"suggest": {

File diff suppressed because it is too large Load Diff

View File

@ -107,6 +107,7 @@ defined('ROUTE_LOGIN_D') OR define('ROUTE_LOGIN_D', 'saveFlyhiPDImage');
defined('ROUTE_LOGIN_C') OR define('ROUTE_LOGIN_C', 'getCreditPDReportforCETApp');
defined('ROUTE_LOGIN_B') OR define('ROUTE_LOGIN_B', 'getSalesPDReportforCETApp');
defined('ROUTE_LOGIN_A') OR define('ROUTE_LOGIN_A', 'getAuditedImages'); // no errors
defined('LOGIN') OR define('LOGIN', 'login');
defined('TURN_SERVER_API') OR define('TURN_SERVER_API', 'getServerInfo'); // no errors
defined('VIDEO_CHAT_ACCESS_KEY_API') OR define('VIDEO_CHAT_ACCESS_KEY_API', 'getVideoChatAccessKey'); // no errors
defined('SAVEROOMINFO_API') OR define('SAVEROOMINFO_API', 'saveRoomInfo'); // no errors
@ -729,3 +730,12 @@ defined('TEMPLATE_JSON_V2') OR define('TEMPLATE_JSON_V2',"m_template_json_v2");
defined('TEMPLATE_MAP_V2') OR define('TEMPLATE_MAP_V2',"m_template_mapping_v2");
defined('DATADUMPREQUEST') OR define('DATADUMPREQUEST',"t_datadump_request");
/*********************Define Constant For GCP****************************************************/
defined('GOOGLE_CLOUD_ID') OR define('GOOGLE_CLOUD_ID', '');
defined('GOOGLE_CLOUD_SECRET') OR define('GOOGLE_CLOUD_SECRET', '');
defined('GOOGLE_CLOUD') OR define('GOOGLE_CLOUD', '');
$config[''] = '';
$config['GOOGLE_CLOUD'] = '';
$googleCloud = 'https://accounts.google.com/o/oauth2/auth?scope=' . urlencode(GOOGLE_CLOUD) . '&redirect_uri=' . REDIRECT_URI . '&response_type=code&client_id=' . GOOGLE_CLOUD_ID . '&access_type=online';

View File

@ -158,6 +158,7 @@ class Sales_PD_Controller extends REST_Controller {
// }
function prepareSalesPDReport($sales_pd_id,$api = true)
{
$this->load->library('Googlecloud');
log_message('ERROR','####PREPARE SALESPD REPORT CALLED'.$sales_pd_id);
$columns = array('SALES_PD_DATA.*','ENTITY.short_name','PRODUCT.abbr','USERPROFILE.smc_emp_code');
$table = SALES_PD_DATA.' as SALES_PD_DATA';
@ -212,6 +213,21 @@ class Sales_PD_Controller extends REST_Controller {
}
// print_r($view_data['section3']);die();
$view_data['section9'] = $this->Sales_PD_Model->selectCustomRecords(array('*'),array('fk_sales_pd_id' => $sales_pd_id,'img_name !=' => 'satellite','isactive' => 1),SALEPD_DOCS);
if($view_data['section9']){
$gcpBucketName = 'sales-pd-demo';
foreach ($view_data['section9'] as $key => $value){
if($value['img'] == '' ){
$objectName = "pd".$sales_pd_id."/images/".$value['img_name'].".png";
$img_gcp_url = $this->googlecloud->getSingleObjectInaBucketAsSignedURI($gcpBucketName,$objectName);
$view_data['section9'][$key]['img'] = $img_gcp_url ? $img_gcp_url : "";
// echo "img". $img_gcp_url;
}
}
}
// print_r($view_data['section9']);die();
$view_data['satellite_image'] = $this->Sales_PD_Model->selectCustomRecords(array('*'),array('fk_sales_pd_id' => $sales_pd_id,'img_name' => 'satellite','isactive' => 1),SALEPD_DOCS);
$view_data['product_id'] = $sales_pd_data[0]['product_id'];
$view_data['geo_location'] = $sales_pd_data[0]['geo_location'];
@ -229,6 +245,15 @@ class Sales_PD_Controller extends REST_Controller {
$bucket_data = array('bucket_name'=>$bucket_name,'key'=>$key,'sourcefile'=>$this->external_path.'/sales_pd/'.$sales_pd_id.'/temp.pdf');
log_message('ERROR','####SALES PD REPORT UPLOAD TO S3'.$sales_pd_id);
$s3result= $this->aws_s3->uploadFileToS3Bucket($bucket_data);
/*** GCP Report Upload here */
$gcpBucketName = 'sales-pd-demo';
$gcpObjectName = "pd".$sales_pd_id."/report/".$pdf_name.".pdf";
$source=$output_file;
$gcpResult = $this->googlecloud->uploadFileToGCPBucket($gcpBucketName,$gcpObjectName,$source);
$report_gcp_url = '';
if($gcpResult == true){
$report_gcp_url = $this->googlecloud->getSingleObjectInaBucketAsSignedURI($gcpBucketName,$gcpObjectName);
}
if(is_object($s3result) && $s3result['ObjectURL'] != '' && $s3result['@metadata']['statusCode'] == 200)
{
@ -253,9 +278,11 @@ class Sales_PD_Controller extends REST_Controller {
}else {
$singed_uri = $this->aws_s3->getSingleObjectInaBucketAsSignedURI($bucket_name,$old_key,'30 minutes');
}
$data['dataStatus'] = true;
$data['status'] = REST_Controller::HTTP_OK;
$data['records'] = $singed_uri;
$data['gcpUrl'] = $report_gcp_url;
$this->response($data,REST_Controller::HTTP_OK);
}
}
@ -272,9 +299,15 @@ class Sales_PD_Controller extends REST_Controller {
}else {
$singed_uri = $this->aws_s3->getSingleObjectInaBucketAsSignedURI($bucket_name,$old_key,'30 minutes');
}
$gcpBucketName = 'sales-pd-demo';
// $gcpObjectName = "pd".$sales_pd_id."/report/new.pdf";
$gcpObjectName = "pd".$sales_pd_id."/report/".$pdf_name.".pdf";
$report_gcp_url = $this->googlecloud->getSingleObjectInaBucketAsSignedURI($gcpBucketName,$gcpObjectName);
$data['dataStatus'] = true;
$data['status'] = REST_Controller::HTTP_OK;
$data['records'] = $singed_uri;
$data['gcpUrl'] = $report_gcp_url;
$this->response($data,REST_Controller::HTTP_OK);
}
}
@ -736,7 +769,16 @@ class Sales_PD_Controller extends REST_Controller {
$this->Flyhi_Model->updateRecords($update_fields2,SALEPD_DOCS,array('doc_id'=>$records['img_id']));
}
unset($records['img_id']);
$id = $this->Sales_PD_Model->saveRecords($records,SALEPD_DOCS);
$this->load->library('Googlecloud');
$gcpBucketName = 'sales-pd-demo';
$objectName = "pd".$records['fk_sales_pd_id']."/images/".$records['img_name'].".png";
$source=$records['img'];
$result = $this->googlecloud->uploadFileToGCPBucket($gcpBucketName,$objectName,$source);
if($result == true){
unset($records['img']);
$id = $this->Sales_PD_Model->saveRecords($records,SALEPD_DOCS);
}
if($id)
{
$data['dataStatus'] = true;
@ -1315,22 +1357,27 @@ public function filterSalesPDList_post() {
$product_short_name = $this->Sales_PD_Model->selectCustomRecords(array('abbr'),array('product_id' => $sales_pd_master_data[0]['product_id']),PRODUCTS);
$is_flyhi_pd = ($sales_pd_master_data[0]['sales_pd_type'] == "3" || $sales_pd_master_data[0]['sales_pd_type'] == "4") ? 1 : 0 ;
$sales_pd_img_data = $this->Sales_PD_Model->selectCustomRecords(array('doc_id', 'fk_sales_pd_id','img','img_name','location','isactive'),array('fk_sales_pd_id' => $sales_pd_master_data[0]['sales_pd_id'],'isactive' => 1,'img_name!=' => 'satellite'),SALEPD_DOCS);
// print_r($sales_pd_img_data);
// print_r($product_short_name);die();
//sales tele pd img structure array
$imgs = array('selfie_with_person_met' => array('is_multiple' => 0,'img_name' => 'Selfie of the person contacted'),'name_board_seen' => array('is_multiple' => 1,'img_name' => 'Business Name Board'),'stock_image' => array('is_multiple' => 1,'img_name' => 'Stock Images'),'workplace_interior_image' => array('is_multiple' => 1,'img_name' => 'Work Place Interior'));
$imgs = array('selfie_with_person_met' => array('is_multiple' => 0,'img_name' => 'Selfie of the person contacted'),'name_board_seen' => array('is_multiple' => 1,'img_name' => 'Business Name Board'),'stock_image' => array('is_multiple' => 1,'img_name' => 'Stock Images'),'workplace_interior_image' => array('is_multiple' => 1,'img_name' => 'Work Place Interior'),'approach_to_pd_location' => array('is_multiple' => 1,'img_name' => 'approach_to_pd_location') );
if($product_short_name[0]['abbr'] == 'MEQ')
{
$imgs = array('selfie_with_person_met' => array('is_multiple' => 0,'img_name' => 'Selfie of the person contacted'),'hospital_building' => array('is_multiple' => 1,'img_name' => 'Institute Building photo'),'name_board_seen' => array('is_multiple' => 1,'img_name' => 'Name Board'),'institute_interior' => array('is_multiple' => 1,'img_name' => 'Institute interior potographs'));
}
$img_data = array();
$this->load->library('Googlecloud');
$gcpBucketName = 'sales-pd-demo';
$objectName = "pd".$sales_pd_master_data[0]['sales_pd_id']."/images/";
if(count($sales_pd_img_data))
{
// print_r($sales_pd_img_data);
foreach ($imgs as $key => $value)
{
//echo "FISRT LOOP****$key";
foreach ($sales_pd_img_data as $sales_pd_img_data_key => $sales_pd_img_data_value)
{
//echo "SEC LOOP****";
@ -1340,18 +1387,28 @@ public function filterSalesPDList_post() {
if($value['is_multiple'])
{
if(!array_key_exists($key,$img_data))
{
$img_data[$key] = array('img_key' => $key,'img_name' => $value['img_name'],'img_data' => [array('img_url' => $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : '','img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '')],'is_multiple' => 1,'section_heading' => $value['img_name']);
{
$img_gcp_url = $this->googlecloud->getSingleObjectInaBucketAsSignedURI($gcpBucketName,$objectName.$value['img_name'].".png");
$img_url = $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : ($img_gcp_url ? $img_gcp_url : "");
$img_data[$key] = array('img_key' => $key,'img_name' => $value['img_name'],'img_data' => [array('img_url' => $img_url,'img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '')],'is_multiple' => 1,'section_heading' => $value['img_name']);
// $img_data[$key] = array('img_key' => $key,'img_name' => $value['img_name'],'img_data' => [array('img_url' => $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : '','img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '')],'is_multiple' => 1,'section_heading' => $value['img_name']);
}
else
{
$img_data[$key]['img_data'][] = array('img_url' => $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : '','img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '');
$img_gcp_url = $this->googlecloud->getSingleObjectInaBucketAsSignedURI($gcpBucketName,$objectName.$value['img_name'].".png");
$img_url = $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : ($img_gcp_url ? $img_gcp_url : "");
$img_data[$key]['img_data'][] = array('img_url' => $img_url,'img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '');
// $img_data[$key]['img_data'][] = array('img_url' => $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : '','img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '');
}
}
else
{
$img_data[$key] = array('img_key' => $key,'img_name' => $value['img_name'],'img_url' => $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : '','is_multiple' => 0,'section_heading' => $value['img_name'],'img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '');//$sales_pd_img_data_value['img']
$img_gcp_url = $this->googlecloud->getSingleObjectInaBucketAsSignedURI($gcpBucketName,$objectName.$value['img_name'].".png");
$img_url = $sales_pd_img_data_value['img'] ? $sales_pd_img_data_value['img'] : ($img_gcp_url ? $img_gcp_url : "");
$img_data[$key] = array('img_key' => $key,'img_name' => $value['img_name'],'img_url' => $img_url,'is_multiple' => 0,'section_heading' => $value['img_name'],'img_id'=>($sales_pd_img_data_value['doc_id']) ? $sales_pd_img_data_value['doc_id'] : '','location'=>($sales_pd_img_data_value['location']) ? $sales_pd_img_data_value['location'] : '');//$sales_pd_img_data_value['img']
}
unset($sales_pd_img_data[$sales_pd_img_data_key]);
@ -1614,8 +1671,8 @@ public function filterSalesPDList_post() {
log_message('ERROR','## In NewSalesPd');
$sales_pd_type = $this->get('type');
$productname = $this->get('prod');
$applicantname = $this->get('apcntname');
$applicantid = $this->get('apcntid');
$applicantname = $this->get('applicantname');
$applicantid = $this->get('applicantid');
$userid = $this->get('uid');
$createdby = null;
$lenderid = (ENVIRONMENT == 'production' ? 7 : 35);
@ -1735,11 +1792,12 @@ public function filterSalesPDList_post() {
$fields = array('sales_pd_id' => $id, 'section_id' => $data_value['section_id'], 'status' =>1,'section_data' => $section_data_arr,'createdby' => $createdby);
$reponse = $this->Sales_PD_Model->saveRecords($fields,SALESPD_SECTION_DATA);
$msg = $msg." ( ".$data_value['section_name']." ID : ".$reponse. " )";
log_message('ERROR','## 5) msg : '.$msg);
}
}
$data['dataStatus'] = true;
$data['status'] = REST_Controller::HTTP_OK;
$data['records'] = $msg;
$data['msg'] = "Sales PD : ".$salepd_serial_no;
} else {
$data['dataStatus'] = false;
$data['status'] = REST_Controller::HTTP_NOT_FOUND;
@ -1753,6 +1811,26 @@ public function filterSalesPDList_post() {
$this->response($data,REST_Controller::HTTP_OK);
}
function uploadSalesImages_get(){
$sales_pd_id = $this->get('sales_pd_id');
// 2961
$photograph_data = $this->Sales_PD_Model->selectCustomRecords(array('*'),array('fk_sales_pd_id' => $sales_pd_id,'isactive' => 1),SALEPD_DOCS);
if(count($photograph_data)>0){
for ($i = 0; $i < count($photograph_data); $i++){
$img_fields = $common_fields;
$img_fields['img_name'] = $photograph_data[$i]['img_name'];
$img_split = explode( ',', $photograph_data[$i]['img']);
$img_fields['img'] = $img_split[1];
// $img_fields[0]['img'] = $photograph_data[$i]['img'];
$img_result = cet_salespd::pushwithcetphotographapi($img_fields,$i);
}
}
}
}

View File

@ -0,0 +1,12 @@
{
"type": "service_account",
"project_id": "smclos",
"private_key_id": "927e4710b0f3f7659d343f8df86371a82337e8cc",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDUTCELgyqBYP0V\nfZvbzWZ/Z9xB/C8cNA3fHEa3dq2KD/SjcWtIa2Jpvw0SSI/itS8+7koJMdvwKP1l\nJVx47iF27TMFl9QBN1wwPZpbtQFGGYitneNuxkJ6mKbbhP8v2qvWxUtKr8GvgdZO\n1cST0HV/vv1jw2YB/vj+Yghwfj8UBhj/iMPwamVVrgsA7UXNPc2JwXVNxPZ3Tr1J\nHarPrG9V6IUrMwa2sNBMvqJJIBiMylw4qVcagg40T7hcnMl021RnjTWT8lXZkT0e\nGDuHrGwqwn6vqZo3D/oBmcSABjuXogg/KSeVQ3aEMhgUZkIujj5w5c9AOolMhLEq\n3RoA0FfXAgMBAAECggEAYO8x13PYoKKMbJeh5sbumhXuOCLRz+rkuo7Kq1KBAp0u\ncsKC3dpKYUZezY5cRIO+QtnC7FfbuNi+esSIaJ8yoH7F4TPmFXgVm+FE7cLEBiH6\nimuhQR89k4TIC0u6yTrrY3FKY5vEsEJ0fCKXU3bHb8DhKgA6P4cQYfaZK+Q5IQai\nfteXvIuxp7AQR4JCH9mMoYJvrOYU94XsEFBlc3ue3t17a/pLTw88JgXC1VieaF/v\nmzgV6cLZL4yCpSIaVU879mG3YWHGu86MAu8pillJkDXQkWWEQfSANSrx8bC3xAdo\neVGmGUSM8I6XxF/FOA+E0DLd7HupU+zUjOUV8ePIgQKBgQD2v2n1NXqKCImabG8i\n0k+Uaa6QV+771AyydwHYoOhaQ/V08GjGQKuSobWQW0n0rxDe0dWy+y6E0QeYFZxq\nDg25lP7KFMTpmk9NLOuD5La9CKrF7Qbz1ipNRVC7Bq+uzE8jJd0LDqPJ1o8OVNCe\nr8SGMXsr8JQ/v+KwmRQKOfKPMQKBgQDcQgTP/sQSBkIKVZMZe7QLhJ7GlB9mNjVQ\n4lv37auYSFs1p2PE2MH4mfF8MJq8eppz08kxvkWVey/hKVxKzl+t3oTbgbMnWUD7\nDQlus2U1Oof07QQg7Mg6Hkx3c6KBh4p/hw6WvB8Fxxm+nCu2y/tmU9B+J1vpZQWU\nE8X1INDlhwKBgQCMOGzDX1e6t21TJ0nk1PVKVuBPwNjbnT518LFI5PAF09baVICG\nIVwfIOxoE6isdww0Q7SYWKuv6IXTRHy1vDTKgMRmHHVmdz2Xku5n7oJ2XEWH4tHv\noYY6kSh2kC8oO4zBYZQC45fqbJaxQzum4iXhSJ9Bch8dNzNgvi0oPpP8EQKBgDZf\nDbUSnPAeH1tRuJhH0zAsss0ub3nZ09t9pVpUj1FuOyXJhnVnVKq7xcL0dJ4mXc5N\n75KZ969o027vuNq2iyPulDljkQgbnlDa7QMowckcA8fQYn6GNP8zz4iFQQ5cmTHV\n8yH+mmHgvlgxURE01YBzHDqoGKZKy8+7+dgDG84tAoGBAJyyGo9B+s/ect3Scnyp\n/O8Nj1NFQY0NYWJFx9GA0AOmt3lSFcDoF67ASDV5HY4vpszobwxoIZ3/DfuxX4m0\n1SZLCqpc7UlgolFT7mZgcvKaKZNjivpAVf4CZebUEU790HDz095Ner2/A0bKW5kG\nNQkH6e0qfaXXAk//w1ziBvp/\n-----END PRIVATE KEY-----\n",
"client_email": "email-case-interaction@smclos.iam.gserviceaccount.com",
"client_id": "100280942351690305149",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/email-case-interaction%40smclos.iam.gserviceaccount.com"
}

View File

@ -72,7 +72,7 @@ class AUTHORIZATION
}
if( $routingName == ROUTE_LOGIN_X || $routingName == ROUTE_LOGIN_Y || $routingName == ROUTE_LOGIN_Z || $routingName == ROUTE_LOGIN_W || $routingName == ROUTE_LOGIN_V || $routingName == ROUTE_LOGIN_A || $routingName == TURN_SERVER_API || $routingName == VIDEO_CHAT_ACCESS_KEY_API || $routingName ==SAVEROOMINFO_API || $routingName ==SAVESMCCREDITPDIMAGE_API || $routingName ==GETSMCPDIMGSECTIONDATA_API || $routingName == ROUTE_LOGIN_T || $routingName == ROUTE_LOGIN_U || $routingName == ROUTE_LOGIN_B || $routingName == ROUTE_LOGIN_C || $routingName == ROUTE_LOGIN_D || $routingName == ROUTE_LOGIN_E || $routingName == ROUTE_LOGIN_F || $routingName == ROUTE_LOGIN_S || $routingName == ROUTE_LOGIN_G || $routingName == ROUTE_LOGIN_H || $routingName == ROUTE_LOGIN_I)
if( $routingName == LOGIN || $routingName == ROUTE_LOGIN_X || $routingName == ROUTE_LOGIN_Y || $routingName == ROUTE_LOGIN_Z || $routingName == ROUTE_LOGIN_W || $routingName == ROUTE_LOGIN_V || $routingName == ROUTE_LOGIN_A || $routingName == TURN_SERVER_API || $routingName == VIDEO_CHAT_ACCESS_KEY_API || $routingName ==SAVEROOMINFO_API || $routingName ==SAVESMCCREDITPDIMAGE_API || $routingName ==GETSMCPDIMGSECTIONDATA_API || $routingName == ROUTE_LOGIN_T || $routingName == ROUTE_LOGIN_U || $routingName == ROUTE_LOGIN_B || $routingName == ROUTE_LOGIN_C || $routingName == ROUTE_LOGIN_D || $routingName == ROUTE_LOGIN_E || $routingName == ROUTE_LOGIN_F || $routingName == ROUTE_LOGIN_S || $routingName == ROUTE_LOGIN_G || $routingName == ROUTE_LOGIN_H || $routingName == ROUTE_LOGIN_I)
{
return true;
}

View File

@ -0,0 +1,320 @@
<?php
/**
* @package Google Cloud Platform
*
* @author Velz
*
*
* Description : To upload images and files.
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');
include_once APPPATH.'/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
class Googlecloud
{
private $googleClient;
private $CI;
public function __construct()
{
// 'keyFilePath' => APPPATH.'/client_secret_storage_389134811365-cnd4r6014l500bfpskt7ahs2apvcu3mm.apps.googleusercontent.com.json'
$this->CI =& get_instance();
$this->googleClient = new StorageClient([
'keyFilePath' => APPPATH.'/googleCloud.json'
]);
// Authenticate using keyfile data
// $this->googleClient = new StorageClient([
// 'keyFile' => json_decode(file_get_contents(APPPATH.'/client_secret_storage_389134811365-cnd4r6014l500bfpskt7ahs2apvcu3mm.apps.googleusercontent.com.json'), true)
// ]);
}
/**
 * List all Cloud Storage buckets for the current project.
* Refer : get_bucket_metadata() in GCP Docs
 */
public function listAllBuckets()
{
// $storage = new StorageClient();
$storage = $this->googleClient;
$array = array();
try{$buckets = $storage->buckets();
foreach ($storage->buckets() as $bucket) {
// printf('Bucket: %s' . PHP_EOL, $bucket->name());
array_push($array, $bucket->name());
}
return $array;
}
catch (Exception $ex) {
return $ex->getMessage() . "\n<pre>";
print_r($ex->getTraceAsString());
"</pre>";
}
}
/**
 * Create a new bucket with a custom default storage class and location.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
* Refer : create_bucket_class_location() in GCP Docs
 */
function createNewBucket(string $bucketName): string
{
// $storage = new StorageClient();
try {
$storage = $this->googleClient;
$storageClass = 'COLDLINE';
$location = 'ASIA';
$bucket = $storage->createBucket($bucketName, [
'storageClass' => $storageClass,
'location' => $location,
]);
$objects = $bucket->objects([
'encryption' => [ 'defaultKmsKeyName' => null,]
]);
return $bucketName;
// printf('Created bucket %s in %s with storage class %s', $bucketName, $storageClass, $location);
} catch (Exception $ex) {
return $ex->getMessage() . "\n<pre>";
print_r($ex->getTraceAsString());
"</pre>";
}
}
/**
 * Upload a file.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 * (e.g. 'my-object')
 * @param string $source The path to the file to upload.
 * (e.g. '/path/to/your/file')
* Refer : upload_object() in GCP Docs
 */
function uploadFileToGCPBucket(string $bucketName, string $objectName, string $source)
{
// $storage = new StorageClient();
$result = '';
try {
$storage = $this->googleClient;
$file = fopen($source, 'r');
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName
]);
// $result = $object;
// print_r($result);
$result = true;
}
catch (Exception $ex) {
$result = false;
}
return $result;
// printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}
/**
 * Generate a v4 signed URL for downloading an object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 * (e.g. 'my-object')
* Refer : get_object_v4_signed_url() in GCP Docs
 */
function getSingleObjectInaBucketAsSignedURI(string $bucketName, string $objectName): string
{
try {
$storage = $this->googleClient;
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$url = $object->signedUrl(
# This URL is valid for 15 minutes
new \DateTime('15 min'),
[
'version' => 'v4',
]
);
$presignedUrl = (string) $url;
// print('Generated GET signed URL:' . PHP_EOL);
// print($url . PHP_EOL);
// print('You can use this URL with any user agent, for example:' . PHP_EOL);
// print('curl ' . $url . PHP_EOL);
}catch (Exception $ex) {
return $ex->getMessage() . "\n<pre>";
print_r($ex->getTraceAsString());
"</pre>";
}
return $presignedUrl;
}
/**
 * List Cloud Storage bucket objects.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
* Refer : list_objects() in GCP Docs
 */
function getAllObjectsInaBucket(string $bucketName)
{
// $storage = new StorageClient();
$objects = array();
try {
$storage = $this->googleClient;
$bucket = $storage->bucket($bucketName);
foreach ($bucket->objects() as $object) {
// printf('Object: %s' . PHP_EOL, $object->name());
array_push($objects, $object->name());
}
} catch (Exception $ex) {
return $ex->getMessage() . "\n<pre>";
print_r($ex->getTraceAsString());
"</pre>";
}
return $objects;
}
/**
 * Delete an object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 * (e.g. 'my-object')
* Refer : delete_object() in GCP Docs
 */
function deleteSingleObjFromBucket(string $bucketName, string $objectName): string
{
// $storage = new StorageClient();
$storage = $this->googleClient;
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$object->delete();
// printf('Deleted gs://%s/%s' . PHP_EOL, $bucketName, $objectName);
return 'Deleted gs://%s/%s' . PHP_EOL.$objectName;
}
/**
 * Change the default storage class for the given bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
 */
function change_default_storage_class(string $bucketName): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$storageClass = 'COLDLINE';
$bucket->update([
'storageClass' => $storageClass,
]);
printf(
'Default storage class for bucket %s has been set to %s',
$bucketName,
$storageClass
);
}
/**
 * Delete a Cloud Storage Bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
* Refer : delete_bucket() in GCP Docs.
 */
function delete_bucket(string $bucketName): void
{
// $storage = new StorageClient();
$storage = $this->googleClient;
$bucket = $storage->bucket($bucketName);
$bucket->delete();
printf('Bucket deleted: %s' . PHP_EOL, $bucket->name());
}
/**
 * Get bucket metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
* Refer : get_bucket_metadata() in GCP Docs
 */
function get_bucket_metadata(string $bucketName): void
{
// $storage = new StorageClient();
$storage = $this->googleClient;
$bucket = $storage->bucket($bucketName);
$info = $bucket->info();
printf('Bucket Metadata: %s' . PHP_EOL, print_r($info));
}
/**
 * Download an object from Cloud Storage and save it as a local file.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 * (e.g. 'my-object')
 * @param string $destination The local destination to save the object.
 * (e.g. '/path/to/your/file')
* Refer : download_object() in GCP Docs
 */
function download_object(string $bucketName, string $objectName, string $destination): void
{
$storage = $this->googleClient;
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$object->downloadToFile($destination);
printf(
'Downloaded gs://%s/%s to %s' . PHP_EOL,
$bucketName,
$objectName,
basename($destination));
}
/**
 * Copy an object to a new name and/or bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 * (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 * (e.g. 'my-object')
 * @param string $newBucketName The destination bucket name.
 * (e.g. 'my-other-bucket')
 * @param string $newObjectName The destination object name.
 * (e.g. 'my-other-object')
* Refer : copy_object() in GCP Docs
 */
function copyGCPObject(string $bucketName, string $objectName, string $newBucketName, string $newObjectName): void
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$object->copy($newBucketName, ['name' => $newObjectName]);
printf('Copied gs://%s/%s to gs://%s/%s' . PHP_EOL,
$bucketName, $objectName, $newBucketName, $newObjectName);
}
}
?>