/** * Create new file and write into it from file pointer. * Return new file path or false on error. * * @param resource $fp file pointer * @param string $dir target dir path * @param string $name file name * @param array $stat file stat (required by some virtual fs) * * @return bool|string * * @author Dmitry (dio) Levashov **/ protected function _save($fp, $path, $name, $stat) { if ($name !== '') { $path .= '/' . $name; } list($parentId, $itemId, $parent) = $this->_gd_splitPath($path); if ($name === '') { $stat['iid'] = $itemId; } if (!$stat || empty($stat['iid'])) { $opts = ['q' => sprintf('trashed=false and "%s" in parents and name="%s"', $parentId, $name), 'fields' => self::FETCHFIELDS_LIST]; $srcFile = $this->_gd_query($opts); $srcFile = empty($srcFile) ? null : $srcFile[0]; } else { $srcFile = $this->_gd_getFile($path); } try { $mode = 'update'; $mime = isset($stat['mime']) ? $stat['mime'] : ''; $file = new Google_Service_Drive_DriveFile(); if ($srcFile) { $mime = $srcFile->getMimeType(); } else { $mode = 'insert'; $file->setName($name); $file->setParents([$parentId]); } if (!$mime) { $mime = self::mimetypeInternalDetect($name); } if ($mime === 'unknown') { $mime = 'application/octet-stream'; } $file->setMimeType($mime); $size = 0; if (isset($stat['size'])) { $size = $stat['size']; } else { $fstat = fstat($fp); if (!empty($fstat['size'])) { $size = $fstat['size']; } } // set chunk size (max: 100MB) $chunkSizeBytes = 100 * 1024 * 1024; if ($size > 0) { $memory = elFinder::getIniBytes('memory_limit'); if ($memory) { $chunkSizeBytes = min([$chunkSizeBytes, intval($memory / 4 / 256) * 256]); } } if ($size > $chunkSizeBytes) { $client = $this->client; // Call the API with the media upload, defer so it doesn't immediately return. $client->setDefer(true); if ($mode === 'insert') { $request = $this->service->files->create($file, ['fields' => self::FETCHFIELDS_GET]); } else { $request = $this->service->files->update($srcFile->getId(), $file, ['fields' => self::FETCHFIELDS_GET]); } // Create a media file upload to represent our upload process. $media = new Google_Http_MediaFileUpload($client, $request, $mime, null, true, $chunkSizeBytes); $media->setFileSize($size); // Upload the various chunks. $status will be false until the process is // complete. $status = false; while (!$status && !feof($fp)) { elFinder::extendTimeLimit(); // read until you get $chunkSizeBytes from TESTFILE // fread will never return more than 8192 bytes if the stream is read buffered and it does not represent a plain file // An example of a read buffered file is when reading from a URL $chunk = $this->_gd_readFileChunk($fp, $chunkSizeBytes); $status = $media->nextChunk($chunk); } // The final value of $status will be the data from the API for the object // that has been uploaded. if ($status !== false) { $obj = $status; } $client->setDefer(false); } else { $params = ['data' => stream_get_contents($fp), 'uploadType' => 'media', 'fields' => self::FETCHFIELDS_GET]; if ($mode === 'insert') { $obj = $this->service->files->create($file, $params); } else { $obj = $this->service->files->update($srcFile->getId(), $file, $params); } } if ($obj instanceof Google_Service_Drive_DriveFile) { return $this->_joinPath($parent, $obj->getId()); } else { return false; } } catch (Exception $e) { return $this->setError('GoogleDrive error: ' . $e->getMessage()); } }
function insertFile($sDir, $oFile, $service, $description, $parentId, $mimeType) { global $client; $sPath = $sDir . '/' . $oFile; $file = new Google_Service_Drive_DriveFile(); $aFile = explode('.', $oFile); //$file->setTitle(@$aFile[0]); $file->setTitle(@$oFile); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($sPath); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'multipart')); // Uncomment the following line to print the File ID // print 'File ID: %s' % $createdFile->getId(); return $createdFile->getId(); } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
private function uploadSupplement($supplementFolderId, $tmpfile, $uploaded_name) { $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($uploaded_name); $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($supplementFolderId); $file->setParents(array($parent)); $file = $this->getDriveService()->files->insert($file, array('data' => file_get_contents($tmpfile), 'mimeType' => 'application/pdf', 'uploadType' => 'multipart')); return $file; }
public function createFile($name, $mime, $description, $content, Google_Service_Drive_ParentReference $fileParent = null) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle("test.txt"); //$name ); $file->setDescription($description); $file->setMimeType($mime); if ($fileParent) { $file->setParents(array($fileParent)); } $createdFile = $this->sef->files->insert($file, array('data' => $content, 'mimeType' => $mime)); return $createdFile['id']; }
public static function uploadFile($access_token, $uploadFile, $fileName, $config) { if (!isset($access_token)) { return; } $userId = \HttpReceiver\HttpReceiver::get('userId', 'string'); $client = self::getGoogleClient($config); try { $access_token = (array) $access_token; $client->setAccessToken($access_token); } catch (\InvalidArgumentException $e) { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config)); } $service = new \Google_Service_Drive($client); //Insert a file $file = new \Google_Service_Drive_DriveFile(); if (!isset($fileName) || strlen($fileName) == 0 || $fileName == '0') { $tmp = explode('/', $uploadFile); $fileName = $tmp[sizeof($tmp) - 1]; } else { $fileName .= '.pdf'; } $file->setTitle($fileName); $file->setDescription('A test document'); $file->setMimeType('application/pdf'); $data = file_get_contents($uploadFile); $folderInfo = self::getFolder($access_token, $config); $id = 0; if ($folderInfo['status'] === 'ok') { $id = $folderInfo['id']; } else { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config)); } $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($id); $file->setParents(array($parent)); try { $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'application/pdf', 'uploadType' => 'resumable')); } catch (\Exception $e) { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config)); } if (isset($createdFile) && isset($createdFile['id']) && strlen($createdFile['id']) > 0) { return array('status' => 'ok'); } else { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth($userId, $config)); } }
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($filename); $createdFile = $service->files->insert($file, array('data' => $data, 'convert' => true, 'mimeType' => $mimeType, 'uploadType' => 'multipart')); return $createdFile; } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
public function Copy($oAccount, $sFromType, $sToType, $sFromPath, $sToPath, $sName, $sNewName, &$bResult, &$bBreak) { $oClient = $this->GetClient($oAccount, $sFromType); if ($oClient) { $bResult = false; $bBreak = true; $oDrive = new Google_Service_Drive($oClient); $sToPath = $sToPath === '' ? 'root' : trim($sToPath, '/'); $parent = new Google_Service_Drive_ParentReference(); $parent->setId($sToPath); $copiedFile = new Google_Service_Drive_DriveFile(); // $copiedFile->setTitle($sNewName); $copiedFile->setParents(array($parent)); try { $oDrive->files->copy($sName, $copiedFile); $bResult = true; } catch (Exception $ex) { $bResult = false; } } }
function insertFile($service, $parentId) { $filename = Request::file('file'); $kelas = Request::input('kelas'); $mimeType = $filename->getClientMimeType(); $title = $kelas . '_' . $filename->getClientOriginalName(); $description = $filename->getClientMimeType(); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($filename); $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'media')); // Uncomment the following line to print the File ID // print 'File ID: %s' % $createdFile->getId(); return $createdFile; } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
private function parent_id_resolve_step($root_id, $folder) { // decode top folder $ids_string = get_transient('w3tc_cdn_google_drive_folder_ids'); $ids = @unserialize($ids_string); if (isset($ids[$root_id . '_' . $folder])) { return $ids[$root_id . '_' . $folder]; } // find folder $items = $this->_service->files->listFiles(array('q' => '"' . $root_id . '" in parents ' . 'and title = "' . $folder . '" ' . 'and mimeType = "application/vnd.google-apps.folder" ' . 'and trashed = false')); if (count($items) > 0) { $id = $items[0]->id; } else { // create folder $file = new \Google_Service_Drive_DriveFile(array('title' => $folder, 'mimeType' => 'application/vnd.google-apps.folder')); $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($root_id); $file->setParents(array($parent)); $created_file = $this->_service->files->insert($file); $id = $created_file->id; $permission = new \Google_Service_Drive_Permission(); $permission->setValue(''); $permission->setType('anyone'); $permission->setRole('reader'); $this->_service->permissions->insert($id, $permission); } if (!is_array($ids)) { $ids = array(); } $ids[$root_id . '_' . $folder] = $id; set_transient('w3tc_cdn_google_drive_folder_ids', serialize($ids)); return $id; }
public function Customer_FolderCreation($service, $title, $description, $parentId) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType('application/vnd.google-apps.folder'); if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $createdFile = $service->files->insert($file, array( 'mimeType' => 'application/vnd.google-apps.folder', )); return $createdFile->id; } catch (Exception $e) { return 0; } }
public function CUST_invoice($UserStamp,$service,$unit,$customername,$companyname,$invoiceid,$invoicesno,$invoicedate,$rent,$process,$deposit,$sdate,$edate,$roomtype,$Leaseperiod,$rentcheck,$sendmailid,$docowner,$formname,$waived,$custid,$parentId) { try { $sum='';$proratedrentflag='';$length='';$newfile='test'; $invoiceidcode=$invoiceid; $Slno=intval($invoicesno); $Sdate=$invoicedate; $tenant_fetch=$customername; $unit_fetch=$unit; $company_fetch=$companyname; if($company_fetch==null||$company_fetch=="") { $company_fetch=' ';} $checkin_fetch=$sdate; $checkout_fetch=$edate; $deposit=$deposit; if($deposit==null||$deposit=='') { $A3='00.00'; } else { $A3=$deposit; } $process=$process; if($process==""||$waived!="" ||$process=='null') {$A4='00.00';}else{$A4=$process;} $A5=$rent; $lease_fetch=$Leaseperiod; $SdateD = $Sdate; $sysdate =date('d-m-Y'); $todaydatc = date('Y-m-d');// Utilities.formatDate(new Date(sysdate), TimeZone, "yyyy/MM/dd"); $todaysDate=date('Ymd',strtotime($todaydatc)); $todaydat = date('d-m-Y');//Utilities.formatDate(new Date(), TimeZone, "dd/MM/yyyy"); $todaydatR =date('m-d-Y');// Utilities.formatDate(new Date(), TimeZone, "MM/dd/yyyy"); $this->load->model('EILIB/Mdl_eilib_common_function'); if(strtotime($SdateD) == strtotime("today")) { $Slno=$Slno+1; if(0<=$Slno && $Slno<=9){ $Slno= (String)("00".$Slno); } else if(10<=$Slno && $Slno<=99){ $Slno= "0".$Slno; } $this->Mdl_eilib_common_function->CUST_invoicesearialnoupdation($Slno,$UserStamp); } else { $Slno = 1; if($Slno==1){ $Slno= (String)("00".$Slno); } $todaydatc = date("d/m/Y");// Utilities.formatDate(new Date(sysdate), TimeZone, "dd/MM/yyyy"); $cc_invoicedate = date("Y/m/d");// Utilities.formatDate(new Date(sysdate), TimeZone, "yyyy/MM/dd"); $this->Mdl_eilib_common_function->CUST_invoiceserialandinvoicedateupdation($Slno, $cc_invoicedate,$UserStamp); } $todaydatestring = date("d-M-Y"); $pc = floatval($A3); // processing cost to float $ren = floatval($A5); // rent amount to float $das = floatval($A4); // deposite amount to float $check_in_dated_minus=strtotime($checkin_fetch); $check_in_date= date("Y-m-d",$check_in_dated_minus); $dateStringCheckin=strtotime($check_in_date); $check_in_date1= date("d/M/Y",$dateStringCheckin); $check_out_dated_lastmonth=strtotime($checkout_fetch); $check_out_date= date("Y-m-d",$check_out_dated_lastmonth); $check_out_date1= date("d/M/Y",$check_out_dated_lastmonth); $curr_date = 0; $curr_month = intval(date("m", $check_in_dated_minus)); $curr_month++; $curr_year = intval(date("Y", $check_in_dated_minus)); $cdate1=""; $cdate2=""; strpos($lease_fetch,"Year")===false?$yearchk=-1:$yearchk=strpos($lease_fetch,"Year"); strpos($lease_fetch,"Months")===false?$monthschk=-1:$monthschk=strpos($lease_fetch,"Months"); strpos($lease_fetch,"Month")===false?$monthchk=-1:$monthchk=strpos($lease_fetch,"Month"); strpos($lease_fetch,"Day")===false?$daychk=-1:$daychk=strpos($lease_fetch,"Day"); $check_in_dated_lastmonth = strtotime ("+1 month",$dateStringCheckin); $LastMonth= date("Y-m-d",$check_in_dated_lastmonth); $rent_check=$rentcheck; $this->load->model('EILIB/Mdl_eilib_invoice_contract'); $nonPror_monthCal= $this->Mdl_eilib_invoice_contract->nonproratedmonthcalculation($check_in_date,$check_out_date); $prorated_monthCal= $this->Mdl_eilib_invoice_contract->proratedmonthcalculation($check_in_date,$check_out_date); $Pror_monthCal_concate_start='';$Pror_monthCal_concate_end=''; $this->load->model('EILIB/Mdl_eilib_prorated_calc'); $proratedrent=$this->Mdl_eilib_prorated_calc->wMonthProratedCalc($check_in_date,$check_out_date,$rent); $proratedsmonth=$this->Mdl_eilib_prorated_calc->sMonthProratedCalc($check_in_date,$rent); $proratedemonth=$this->Mdl_eilib_prorated_calc->eMonthProratedCalc($check_out_date,$rent); $month_calculation=$this->nonproratedmonthcalculation( $check_in_date, $check_out_date); $startdate_array= $month_calculation[0]; $enddate_array= $month_calculation[1]; $arrCheckDateAmtConcate="";$singlemonth='';$reminingmonths=''; if( $formname=="CREATION" || $formname=="RECHECKIN") { if(( $yearchk>0)||( $monthschk>0)||(( $monthchk>0)&&( $daychk>0))) { if( $rent_check=='false') { $proratedrentflag=1; $month_calculation=$this->nonproratedmonthcalculation( $check_in_date, $check_out_date); $startdate_array= $month_calculation[0]; $enddate_array= $month_calculation[1]; $length= count($startdate_array); } else{ $proratedrentflag=2; $month_calculation=$this->proratedmonthcalculation($check_in_date,$check_out_date); $startdate_array=$month_calculation[0]; $enddate_array=$month_calculation[1]; $length=count($startdate_array); } } else { $length=1; $proratedrentflag=0; $cdate1=$check_in_date1; $cdate2=$check_out_date1; $sum1 = $das+$pc+floatval($A5); $sum = number_format($sum1,2,'.',''); } } else if( $formname=="EXTENSION")//extension.... { if((( $yearchk>0)||( $monthschk>0)||(( $monthchk>0)&&( $daychk>0)))&&( $rent_check=='true'))//greater than a month-rent check true { $proratedrentflag=2; $month_calculation=$this->proratedmonthcalculation( $check_in_date, $check_out_date); $startdate_array= $month_calculation[0]; $enddate_array= $month_calculation[1]; $length=count( $startdate_array); } else if((( $yearchk>0)||( $monthschk>0)||(( $monthchk>0)&&( $daychk>0)))&&( $rent_check=='false'))//greater than a month-rent check false { $proratedrentflag=1; $month_calculation=$this->nonproratedmonthcalculation( $check_in_date, $check_out_date); $startdate_array= $month_calculation[0]; $enddate_array= $month_calculation[1]; $length=count($startdate_array); } else if(((( $yearchk<0)&&( $monthschk<0)&&( $daychk>0)&&( $monthchk<0))||(( $yearchk<0)&&( $monthschk<0)&&( $daychk<0)&&( $monthchk>0)))&&( $rent_check=='true'))//less than or equal to a month { $length=1; $proratedrentflag=0; $cdate1= $check_in_date1; $cdate2= $check_out_date1; if((date("Y", strtotime($checkin_fetch))==date("Y", strtotime($checkout_fetch))) &&(date("m", strtotime($checkin_fetch))==date("m", strtotime($checkout_fetch)))) { $proratedrent=$this->Mdl_eilib_prorated_calc->wMonthProratedCalc($check_in_date,$check_out_date,$A5); $sum1 = $das+$pc+floatval($proratedrent); $sum = number_format($sum1,2,'.',''); } else if((date("Y", strtotime($checkin_fetch))!=date("Y", strtotime($checkout_fetch))) ||(date("m", strtotime($checkin_fetch))!=date("m", strtotime($checkout_fetch)))) { $proratedsmonth=$this->Mdl_eilib_prorated_calc->sMonthProratedCalc($check_in_date,$A5); $proratedemonth=$this->Mdl_eilib_prorated_calc->eMonthProratedCalc($check_out_date,$A5); $proratedrent = number_format(floatval($proratedsmonth)+floatval($proratedemonth),2,'.',''); $A5=$proratedrent; if($proratedrent!='0.00') { $sum1 = $das+$pc+floatval($proratedrent); $sum = number_format($sum1,2,'.',''); } else { $sum1 = $das+$pc+$ren; $sum = number_format($sum1,2,'.',''); } } } } if($proratedrentflag==2) /////////rent check true greater than month PRORATED { $sumamount=$das+$pc; $reminingmonths=0; for($i=0;$i<$length;$i++) { $startdate=$startdate_array[$i]; $enddate=$enddate_array[$i]; if(intval(date("d", strtotime($startdate)))!=1 && $i==0){$amount=$this->Mdl_eilib_prorated_calc->sMonthProratedCalc($check_in_date,$A5);}else{$amount=$A5;} if($i==$length-1) { $date = new DateTime(); $date->setDate(date("Y", strtotime($enddate)),(intval(date("m", strtotime($enddate)))+1),date("d", strtotime($enddate))); $finaldate=$date->format('Y-m-d'); if(date("d", strtotime($enddate))==date("d", strtotime($finaldate))-1) {$amount=$A5;}else{$amount=$this->Mdl_eilib_prorated_calc->eMonthProratedCalc($check_out_date,$A5);} } $checkdate1= date("d/M/Y",strtotime($startdate)); $checkdate2= date("d/M/Y",strtotime($enddate)); if($i==0) $arrCheckDateAmtConcate.= $amount.'^^'.$checkdate1.'^^'.$checkdate2; else $arrCheckDateAmtConcate.= '^~^'.$amount.'^^'.$checkdate1.'^^'.$checkdate2; if($i==0) { $singlemonth= number_format(floatval($sumamount)+floatval($amount),2,'.',''); } else { $reminingmonths=floatval($reminingmonths)+floatval($amount); $reminingmonths= number_format($reminingmonths,2,'.',''); } } } if($proratedrentflag==1) ////NONPRORATED { $sumamount=$das+$pc; $reminingmonths=0; for($i=0;$i<$length;$i++) { $startdate=$startdate_array[$i]; $enddate=$enddate_array[$i]; $amount=$A5; if($i==$length-1) { if(date('Y',strtotime($startdate))==date('Y',strtotime($enddate)) &&date('m',strtotime($startdate))==date('m',strtotime($enddate))) { $amount=$this->Mdl_eilib_prorated_calc->wMonthProratedCalc($startdate,$enddate,$A5); } else if(date('Y',strtotime($startdate))!=date('Y',strtotime($enddate)) ||date('m',strtotime($startdate))!=date('m',strtotime($enddate))) { $proratedsmonth=$this->Mdl_eilib_prorated_calc->sMonthProratedCalc($startdate,$A5); $proratedemonth=$this->Mdl_eilib_prorated_calc->eMonthProratedCalc($enddate,$A5); $amount=number_format(floatval($proratedsmonth)+floatval($proratedemonth),2,'.',''); } } $checkdate1= date("d/M/Y",strtotime($startdate)); $checkdate2=date("d/M/Y",strtotime($enddate)); if($i==0) $arrCheckDateAmtConcate.= $amount.'^^'.$checkdate1.'^^'.$checkdate2; else $arrCheckDateAmtConcate.= '^~^'.$amount.'^^'.$checkdate1.'^^'.$checkdate2; $sum = number_format($sumamount,2,'.',''); if($i==0) { $singlemonth= number_format(floatval($sumamount)+floatval($amount),2,'.',''); } else { $reminingmonths= number_format(floatval($reminingmonths)+floatval($amount),2,'.',''); } } } if($formname=="EXTENSION") { $replaceSum=$sum; } else { $pcanddep=floatval($das)+floatval($pc)+floatval($A5); $replaceSum= number_format($pcanddep,2,'.',''); } if($company_fetch==" ") { $companyTemp="company/"; } else { $companyTemp="company"; } if($proratedrentflag==0){ $arrCheckDateAmtConcate.= $replaceSum.'^^'.$cdate1.'^^'.$cdate2; $reminingmonths=$replaceSum; } $title="INVOICE"." -"." ".$unit." ". "-". " ".$tenant_fetch."_INV".$todaysDate.''.$Slno; $newfile= $this->printFile($service,$invoiceid,$parentId,$title); $file = new Google_Service_Drive_DriveFile(); $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); $service->files->patch($newfile, $file); $file = $service->files->get($newfile); $data = array('arrCheckDateAmtConcate'=>$arrCheckDateAmtConcate,'singlemonth'=>$singlemonth,'reminingmonths'=>$reminingmonths, 'companyTemp'=>$companyTemp, 'replaceSum'=>$replaceSum, 'todaydat'=>$todaydat,'todaydatestring'=>$todaydatestring,'A3'=>$A3,'A4'=>$A4,'das'=>$das,'pc'=>$pc,'A5'=>$A5,'sum'=>$sum,'cdate1'=>$cdate1,'cdate2'=>$cdate2,'todaysDate'=>$todaysDate,'Slno'=>$Slno,'tenant_fetch' => $tenant_fetch,'length'=>$length,'proratedrentflag'=>$proratedrentflag, 'nonPror_monthCal'=>$nonPror_monthCal,'flag'=>2,'prorated_monthCal' => $prorated_monthCal, 'proratedrent' => $proratedrent, 'proratedsmonth' => $proratedsmonth,'proratedemonth'=>$proratedemonth, 'unit' => $unit, 'customername' => $customername , 'companyname' =>$company_fetch, 'invoiceid' => $newfile,'invoicesno' => $invoicesno, 'invoicedate' => $invoicedate, 'rent' => $rent, 'process' => $process, 'deposit' => $deposit,'sdate'=>$sdate,'edate'=>$edate,'roomtype'=>$roomtype, 'Leaseperiod'=>$Leaseperiod,'Leaseperiod'=>$Leaseperiod,'rentcheck'=>$rentcheck,'docowner'=>$docowner,'formname'=>$formname, 'waived'=>$waived,'custid'=>$custid ); $url= $this->Mdl_eilib_common_function->getUrlAccessGasScript(); $ch = curl_init(); $data=http_build_query($data); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate"); $response = curl_exec($ch); curl_close($ch); if(strpos($response,"SCRIPT ERROR")===false){ $flagownership= $this->CUST_SetDocOwner($service,$response,$docowner,$sendmailid); if($flagownership==1) return [1,$newfile,$file->alternateLink,"INV".$todaysDate.$Slno]; else return [0,$newfile,$file->alternateLink,$this->Mdl_eilib_common_function->getErrorMessageList("581")[0]->EMC_DATA]; } else{ return [0,$newfile,$file->alternateLink,$response]; } } catch(Exception $e) { if(strpos($e->getMessage(),"404")===false) return [0,$newfile,"",$e->getMessage()]; else return [0,$newfile,"",$this->Mdl_eilib_common_function->getErrorMessageList("455")[0]->EMC_DATA]; } }
/** * Upload file * @param string $directoryId (parent id) * @param string $filename * @param string $content * @param string $mimetype * @return handle */ public function upload($directoryId, $filename, $content, $mimetype = 'text/plain') { $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($directoryId); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($filename); $file->setDescription($filename); $file->setMimeType('text/plain'); $file->setParents(array($parent)); $createdFile = $this->service->files->insert($file, array('data' => $content, 'mimeType' => $mimetype, 'uploadType' => 'media')); return $createdFile; }
private function upload_file($file, $parent_id, $try_again = true) { global $updraftplus; $opts = $this->get_opts(); $basename = basename($file); $service = $this->service; $client = $this->client; # See: https://github.com/google/google-api-php-client/blob/master/examples/fileupload.php (at time of writing, only shows how to upload in chunks, not how to resume) $client->setDefer(true); $local_size = filesize($file); $gdfile = new Google_Service_Drive_DriveFile(); $gdfile->title = $basename; $ref = new Google_Service_Drive_ParentReference(); $ref->setId($parent_id); $gdfile->setParents(array($ref)); $size = 0; $request = $service->files->insert($gdfile); $chunk_bytes = 1048576; $hash = md5($file); $transkey = 'gdresume_' . $hash; // This is unset upon completion, so if it is set then we are resuming $possible_location = $updraftplus->jobdata_get($transkey); if (is_array($possible_location)) { $headers = array('content-range' => "bytes */" . $local_size); $httpRequest = new Google_Http_Request($possible_location[0], 'PUT', $headers, ''); $response = $this->client->getIo()->makeRequest($httpRequest); $can_resume = false; if (308 == $response->getResponseHttpCode()) { $range = $response->getResponseHeader('range'); if (!empty($range) && preg_match('/bytes=0-(\\d+)$/', $range, $matches)) { $can_resume = true; $possible_location[1] = $matches[1] + 1; $updraftplus->log("{$basename}: upload already began; attempting to resume from byte " . $matches[1]); } } if (!$can_resume) { $updraftplus->log("{$basename}: upload already began; attempt to resume did not succeed (HTTP code: " . $response->getResponseHttpCode() . ")"); } } $media = new Google_Http_MediaFileUpload($client, $request, '.zip' == substr($basename, -4, 4) ? 'application/zip' : 'application/octet-stream', null, true, $chunk_bytes); $media->setFileSize($local_size); if (!empty($possible_location)) { $media->resumeUri = $possible_location[0]; $media->progress = $possible_location[1]; $size = $possible_location[1]; } if ($size >= $local_size) { return true; } $status = false; if (false == ($handle = fopen($file, 'rb'))) { $updraftplus->log("Google Drive: failed to open file: {$basename}"); $updraftplus->log("{$basename}: " . sprintf(__('%s Error: Failed to open local file', 'updraftplus'), 'Google Drive'), 'error'); return false; } if ($size > 0 && 0 != fseek($handle, $size)) { $updraftplus->log("Google Drive: failed to fseek file: {$basename}, {$size}"); $updraftplus->log("{$basename} (fseek): " . sprintf(__('%s Error: Failed to open local file', 'updraftplus'), 'Google Drive'), 'error'); return false; } $pointer = $size; try { while (!$status && !feof($handle)) { $chunk = fread($handle, $chunk_bytes); # Error handling?? $pointer += strlen($chunk); $status = $media->nextChunk($chunk); $updraftplus->jobdata_set($transkey, array($media->resumeUri, $media->getProgress())); $updraftplus->record_uploaded_chunk(round(100 * $pointer / $local_size, 1), $media->getProgress(), $file); } } catch (Google_Service_Exception $e) { $updraftplus->log("ERROR: Google Drive upload error (" . get_class($e) . "): " . $e->getMessage() . ' (line: ' . $e->getLine() . ', file: ' . $e->getFile() . ')'); $client->setDefer(false); fclose($handle); $updraftplus->jobdata_delete($transkey); if (false == $try_again) { throw $e; } # Reset this counter to prevent the something_useful_happened condition's possibility being sent into the far future and potentially missed if ($updraftplus->current_resumption > 9) { $updraftplus->jobdata_set('uploaded_lastreset', $updraftplus->current_resumption); } return $this->upload_file($file, $parent_id, false); } // The final value of $status will be the data from the API for the object // that has been uploaded. $result = false; if ($status != false) { $result = $status; } fclose($handle); $client->setDefer(false); $updraftplus->jobdata_delete($transkey); return true; }
/** * fopen() wrapper * * @param string $path Directory patrh * @param string $mode File open mode * @param integer $options Options NOT SUPPORT * * @return boolean */ public function stream_open($path, $mode, $options) { $this->filePosition = 0; $file = $this->getItemByPath($this->convertPathToFS($path)); if ($file && 'x' == substr($mode, 0, 1)) { $file = null; } elseif (!$file && 'r' != substr($mode, 0, 1)) { $dir = $this->getItemByPath(dirname($this->convertPathToFS($path)), static::TYPE_DIRECTORY); if ($dir) { $file = new \Google_Service_Drive_DriveFile(); $file->setTitle(basename($this->convertPathToFS($path))); $file->setMimeType($this->detectMimetype($path)); $ref = new \Google_Service_Drive_ParentReference(); $ref->setId($dir->getId()); $file->setParents(array($ref)); } } if ($file) { $this->file = $file; $this->filePath = $path; $this->fileMode = $mode; } return isset($file); }
/** * Uploads files to the Google drive. * @param $service the Google drive service. * @param string $filePath the directory location where to look for the files. * @param string $fileName the name of the file to be uploaded. * @param string $mimeType the mimeType of the file. * @param string $destinationFolder the directory on the Google drive. * @return string the expanded path. */ function gfUploadFile($client, $service, $filePath, $fileName, $mimeType, $destinationFolder) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($fileName); $file->setDescription($fileName); $file->setMimeType($fileName); if ($destinationFolder != "root") { $parent = new Google_Service_Drive_ParentReference(); $parent->setId(getParentDirectoryId($service, $destinationFolder)); $file->setParents(array($parent)); } $client->setDefer(true); $chunkSizeBytes = 1 * 1024 * 1024; $request = $service->files->insert($file); // Create a media file upload to represent our upload process. $media = new Google_Http_MediaFileUpload($client, $request, $mimeType, null, true, $chunkSizeBytes); $media->setFileSize(filesize($filePath . "/" . $fileName)); // Upload the various chunks. $status will be false until the process is // complete. $status = false; $handle = fopen($filePath . "/" . $fileName, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } // The final value of $status will be the data from the API for the object // that has been uploaded. $result = false; if ($status != false) { $result = $status; } fclose($handle); // Reset to the client to execute requests immediately in the future. $client->setDefer(false); return $result; }
/** * Drive Create File */ public function createFile($title, $parentId, $mimeType = 'text') { // Get the API client and construct the service object. $client = $this->getClient(); $service = new \Google_Service_Drive($client); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setMimeType($mimeType); $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents([$parent]); $data = "basics\nand stuff"; $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType)); # WP crap wp_die(); }
/** * Uploads backup file from server to Google Drive. * * @param array $args arguments passed to the function * [task_name] -> Task name for wich we are uploading * [task_result_key] -> Result key that we are uploading * [google_drive_token] -> user's Google drive token in json form * [google_drive_directory] -> folder on user's Google Drive account which backup file should be upload to * [google_drive_site_folder] -> subfolder with site name in google_drive_directory which backup file should be upload to * [backup_file] -> absolute path of backup file on local server * * @return bool|array true is successful, array with error message if not */ public function google_drive_backup($args) { mwp_register_autoload_google(); $googleClient = new Google_ApiClient(); $googleClient->setAccessToken($args['google_drive_token']); $googleDrive = new Google_Service_Drive($googleClient); mwp_logger()->info('Fetching Google Drive root folder ID'); try { $about = $googleDrive->about->get(); $rootFolderId = $about->getRootFolderId(); } catch (Exception $e) { mwp_logger()->error('Error while fetching Google Drive root folder ID', array('exception' => $e)); return array('error' => 'Error while fetching Google Drive root folder ID: ' . $e->getMessage()); } mwp_logger()->info('Loading Google Drive backup directory'); try { $rootFiles = $googleDrive->files->listFiles(array("q" => "title='" . addslashes($args['google_drive_directory']) . "' and '{$rootFolderId}' in parents and trashed = false")); } catch (Exception $e) { mwp_logger()->error('Error while loading Google Drive backup directory', array('exception' => $e)); return array('error' => 'Error while loading Google Drive backup directory: ' . $e->getMessage()); } if ($rootFiles->offsetExists(0)) { $backupFolder = $rootFiles->offsetGet(0); } else { try { mwp_logger()->info('Creating Google Drive backup directory'); $newBackupFolder = new Google_Service_Drive_DriveFile(); $newBackupFolder->setTitle($args['google_drive_directory']); $newBackupFolder->setMimeType('application/vnd.google-apps.folder'); if ($rootFolderId) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($rootFolderId); $newBackupFolder->setParents(array($parent)); } $backupFolder = $googleDrive->files->insert($newBackupFolder); } catch (Exception $e) { mwp_logger()->info('Error while creating Google Drive backup directory', array('exception' => $e)); return array('error' => 'Error while creating Google Drive backup directory: ' . $e->getMessage()); } } if ($args['google_drive_site_folder']) { try { mwp_logger()->info('Fetching Google Drive site directory'); $siteFolderTitle = $this->site_name; $backupFolderId = $backupFolder->getId(); $driveFiles = $googleDrive->files->listFiles(array("q" => "title='" . addslashes($siteFolderTitle) . "' and '{$backupFolderId}' in parents and trashed = false")); } catch (Exception $e) { mwp_logger()->info('Error while fetching Google Drive site directory', array('exception' => $e)); return array('error' => 'Error while fetching Google Drive site directory: ' . $e->getMessage()); } if ($driveFiles->offsetExists(0)) { $siteFolder = $driveFiles->offsetGet(0); } else { try { mwp_logger()->info('Creating Google Drive site directory'); $_backup_folder = new Google_Service_Drive_DriveFile(); $_backup_folder->setTitle($siteFolderTitle); $_backup_folder->setMimeType('application/vnd.google-apps.folder'); if (isset($backupFolder)) { $_backup_folder->setParents(array($backupFolder)); } $siteFolder = $googleDrive->files->insert($_backup_folder, array()); } catch (Exception $e) { mwp_logger()->info('Error while creating Google Drive site directory', array('exception' => $e)); return array('error' => 'Error while creating Google Drive site directory: ' . $e->getMessage()); } } } else { $siteFolder = $backupFolder; } $file_path = explode('/', $args['backup_file']); $backupFile = new Google_Service_Drive_DriveFile(); $backupFile->setTitle(end($file_path)); $backupFile->setDescription('Backup file of site: ' . $this->site_name . '.'); if ($siteFolder != null) { $backupFile->setParents(array($siteFolder)); } $googleClient->setDefer(true); // Deferred client returns request object. /** @var Google_Http_Request $request */ $request = $googleDrive->files->insert($backupFile); $chunkSize = 1024 * 1024 * 4; $media = new Google_Http_MediaFileUpload($googleClient, $request, 'application/zip', null, true, $chunkSize); $fileSize = filesize($args['backup_file']); $media->setFileSize($fileSize); mwp_logger()->info('Uploading backup file to Google Drive; file size is {backup_size}', array('backup_size' => mwp_format_bytes($fileSize))); // Upload the various chunks. $status will be false until the process is // complete. $status = false; $handle = fopen($args['backup_file'], 'rb'); $started = microtime(true); $lastNotification = $started; $lastProgress = 0; $threshold = 1; $uploaded = 0; $started = microtime(true); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSize); $newChunkSize = strlen($chunk); if (($elapsed = microtime(true) - $lastNotification) > $threshold) { $lastNotification = microtime(true); mwp_logger()->info('Upload progress: {progress}% (speed: {speed}/s)', array('progress' => round($uploaded / $fileSize * 100, 2), 'speed' => mwp_format_bytes(($uploaded - $lastProgress) / $elapsed))); $lastProgress = $uploaded; echo " "; flush(); } $uploaded += $newChunkSize; $status = $media->nextChunk($chunk); } fclose($handle); if (!$status instanceof Google_Service_Drive_DriveFile) { mwp_logger()->error('Upload to Google Drive failed', array('status' => $status)); return array('error' => 'Upload to Google Drive was not successful.'); } $this->tasks[$args['task_name']]['task_results'][$args['task_result_key']]['google_drive']['file_id'] = $status->getId(); mwp_logger()->info('Upload to Google Drive completed; average speed is {speed}/s', array('speed' => mwp_format_bytes(round($fileSize / (microtime(true) - $started))))); return true; }
/** * Insert new file. * * @param Google_Service_Drive $service Drive API service instance. * @param string $title Title of the file to insert, including the extension. * @param string $description Description of the file to insert. * @param string $parentId Parent folder's ID. * @param string $mimeType MIME type of the file to insert. * @param string $filename Filename of the file to insert. * @return Google_Service_Drive_DriveFile The file that was inserted. NULL is * returned if an API error occurred. */ function insertFile($service, $title, $description, $parentId, $mimeType, $filename, $properties = []) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); $file->setProperties($properties); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($filename); $createdFile = $service->files->insert($file, array( 'data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'media', 'convert' => true, )); // Uncomment the following line to print the File ID // print 'File ID: %s' % $createdFile->getId(); return $createdFile; } catch (Exception $e) { catchGoogleExceptions($e); } }
function createFolder(&$service, $title, $description, $parentId, &$configObj) { for ($n = 0; $n < 5; ++$n) { try { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType("application/vnd.google-apps.folder"); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } $createdFile = $service->files->insert($file, array()); return $createdFile; } catch (Google_Exception $e) { if ($e->getCode() == 403 || $e->getCode() == 503) { $logline = date('Y-m-d H:i:s') . " Error: " . $e->getMessage() . "\n"; $logline = $logline . date('Y-m-d H:i:s') . "Retrying... \n"; fwrite($configObj->logFile, $logline); // Apply exponential backoff. usleep((1 << $n) * 1000000 + rand(0, 1000000)); } } catch (Exception $e) { $logline = date('Y-m-d H:i:s') . "Unable to create folder.\n"; $logline = $logline . "Reason: " . $e->getCode() . " : " . $e->getMessage() . "\n"; fwrite($configObj->logFile, $logline); //If unable to create folder because of unrecognized error, return nothing return null; } } }
/** * Checks if a file exists * * @param string $file path to file and filename * @param string $url the live URL to the file * @param bool $is_update perform an update instead of creating a new file * * @since 1.0 * * @return bool */ public function file_upload($file, $url, $is_update = false) { $this->_file_uploaded = false; // get the google drive service if (!isset($this->_google_drive_service)) { $this->_google_drive_service = new Google_Service_Drive($this->_google_drive_cdn->get_google_client()); } // get the google drive service instance $service = $this->_google_drive_service; if (!$service instanceof Google_Service_Drive) { return $url; } // get the folder id $folder_id = WPB_Google_Drive_Cdn_Settings::get_setting('folder_id', 'wpbgdc_folders'); // create the folder name $file_folder_to_str = str_replace(WP_CONTENT_DIR, '', str_replace(basename($file), '', $file)); $file_folder_to_str = str_replace('/', '_', $file_folder_to_str); $file_folder_to_str = sanitize_key($file_folder_to_str); // create the file basename $file_basename = $file_folder_to_str . basename($file); // get the google drive URL $google_drive_url = WPB_Google_Drive_Cdn_Settings::get_setting('folder_link', 'wpbgdc_folders'); try { // search for the file. $files = $service->files->listFiles(array('q' => "title='" . $file_basename . "' and '" . $folder_id . "' in parents")); } catch (Exception $e) { // if there is an error fetching the file, return the normal url return $url; } // checks if the file is a CSS file $is_css_file = substr($file, -4, 4) == '.css'; // search in the list of files for the current file foreach ($files->items as $g_file) { if (!$g_file instanceof Google_Service_Drive_DriveFile) { continue; } // file exists if ($g_file->getTitle() == $file_basename) { // get the date of the current file $file_date = filemtime($file); /** * check if we should update the file * this is the case when either * the date of the file on Google Drive is lower than the local file OR * when the etag is not correct (this is only used for css files at the moment) */ if (strtotime($g_file->getModifiedDate()) < $file_date or $is_css_file && $g_file->getEtag() != $this->get_etag_by_live_url($url)) { $additionalParams = array(); if ($is_css_file) { $additionalParams['data'] = $this->invoke_css_file($file, $url); $additionalParams['mimeType'] = 'text/css'; } else { $additionalParams['data'] = file_get_contents($file); } try { $g_file = $service->files->update($g_file->getId(), $g_file, $additionalParams); } catch (Exception $e) { $this->_google_drive_cdn->set_error($e->getMessage() . '(wpbgdc: file_upload 1; File: ' . $url . ')', false); } $this->_file_uploaded = true; } // update the file cache entry as well $this->set_cached_url($url, $google_drive_url . $g_file->getTitle(), $g_file->getId(), $g_file->getEtag()); // create the URL out of the Drive URL and return it. return $google_drive_url . $g_file->getTitle(); } } if ($is_css_file) { $mime_type = 'text/css'; } else { $mime_type = wp_check_filetype($file); $mime_type = $mime_type['type']; } $parent = new Google_Service_Drive_ParentReference(); $parent->setId($folder_id); // upload the file $new_file = new Google_Service_Drive_DriveFile(); $new_file->setTitle($file_basename); $new_file->setMimeType($mime_type); $new_file->setParents(array($parent)); $new_file->setFileSize(filesize($file)); $additionalParams = array('mimeType' => $mime_type, 'uploadType' => 'media'); if ($is_css_file) { $additionalParams['data'] = $this->invoke_css_file($file, $url); } else { $additionalParams['data'] = file_get_contents($file); } try { $createdFile = $service->files->insert($new_file, $additionalParams); } catch (Exception $e) { $this->_google_drive_cdn->set_error($e->getMessage() . '(wpbgdc: file_upload 2; File: ' . $url . ')', false); return $url; } $file_drive_url = $google_drive_url . $createdFile->getTitle(); $this->set_cached_url($url, $file_drive_url, $createdFile->getId(), $createdFile->getEtag()); $this->_file_uploaded = true; return $file_drive_url; }
public static function createFolder($settings, $parentID, $folderName) { if ('' == $parentID) { $parentID = 'root'; } $settings = self::_normalizeSettings($settings); if (false === ($settings = self::_connect($settings))) { $error = 'Error #2378327: Unable to connect with Google Drive. See log for details.'; echo $error; pb_backupbuddy::status('error', $error); return false; } //Insert a folder $driveFile = new Google_Service_Drive_DriveFile(); $driveFile->setTitle($folderName); //$driveFile->setParents( array( $parentID ) ); $driveFile->setMimeType('application/vnd.google-apps.folder'); // Set the parent folder. if ('root' != $parentID) { $parentsCollectionData = new Google_Service_Drive_ParentReference(); $parentsCollectionData->setId($parentID); $driveFile->setParents(array($parentsCollectionData)); } try { $insertRequest = self::$_drive->files->insert($driveFile); return array($insertRequest->id, $insertRequest->title); } catch (Exception $e) { global $pb_backupbuddy_destination_errors; $pb_backupbuddy_destination_errors[] = $e->getMessage(); $error = $e->getMessage(); echo $error; pb_backupbuddy::status('error', $error); return false; } }
public function insert_public_folder($service) { $parentId = get_option("flowdrive_basefolder"); $file = new \Google_Service_Drive_DriveFile(); $file->setTitle('flowdrive'); $file->setMimeType('application/vnd.google-apps.folder'); // Set base folder if ($parentId) { $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents([$parent]); } $createdFile = $service->files->insert($file, ['mimeType' => 'application/vnd.google-apps.folder']); $permission = new \Google_Service_Drive_Permission(); $permission->setValue(''); $permission->setType('anyone'); $permission->setRole('reader'); $service->permissions->insert($createdFile->getId(), $permission); return $createdFile->getId(); }
public function touch($path, $mtime = null) { $file = $this->getDriveFile($path); $result = false; if ($file) { if (isset($mtime)) { // This is just RFC3339, but frustratingly, GDrive's API *requires* // the fractions portion be present, while no handy PHP constant // for RFC3339 or ISO8601 includes it. So we do it ourselves. $file->setModifiedDate(date('Y-m-d\\TH:i:s.uP', $mtime)); $result = $this->service->files->patch($file->getId(), $file, array('setModifiedDate' => true)); } else { $result = $this->service->files->touch($file->getId()); } } else { $parentFolder = $this->getDriveFile(dirname($path)); if ($parentFolder) { $file = new \Google_Service_Drive_DriveFile(); $file->setTitle(basename($path)); $parent = new \Google_Service_Drive_ParentReference(); $parent->setId($parentFolder->getId()); $file->setParents(array($parent)); $result = $this->service->files->insert($file); } } if ($result) { $this->setDriveFile($path, $result); } return (bool) $result; }
function insertFile($service, $title, $description, $parentId,$mimeType,$uploadfilename) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data =file_get_contents($uploadfilename); $createdFile = $service->files->insert($file, array( 'data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'media', )); $fileid = $createdFile->getId(); $fileflag=1; } catch (Exception $e) { $fileflag=0; } $finalarry=[$fileid,$fileflag]; return $finalarry; }
/** * Insert new file in the Application Data folder. * * @param Google_DriveService $service Drive API service instance. * @param string $title Title of the file to insert, including the extension. * @param string $description Description of the file to insert. * @param string $mimeType MIME type of the file to insert. * @param string $filename Filename of the file to insert. * @return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred. */ function insertFile($service, $title, $description, $mimeType, $filename, $folderName, $folderDesc) { $file = new Google_Service_Drive_DriveFile(); $new_mime_type = 'application/vnd.google-apps.document'; // Set the metadata $file->setTitle($title); $file->setDescription($description); $file->setMimeType($new_mime_type); // Setup the folder you want the file in, if it is wanted in a folder if (isset($folderName)) { if (!empty($folderName)) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId(getFolderExistsCreate($service, $folderName, $folderDesc)); $file->setParents(array($parent)); } } try { // Get the contents of the file uploaded $data = file_get_contents($filename); // Try to upload the file, you can add the parameters e.g. if you want to convert a .doc to editable google format, add 'convert' = 'true' $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType, 'uploadType' => 'multipart', 'convert' => 'true')); // Return a bunch of data including the link to the file we just uploaded return $createdFile; } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
function copy_spreadsheet($morsle, $title, $template, $collectionid = null) { $service = new Google_Service_Drive($morsle->client); $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); // Set the parent folder. if ($collectionid !== null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($collectionid); $file->setParents(array($parent)); } $result2 = $service->files->copy($template, $file); return $result2->id; }
/** * createFolder * * Erstellt einen neuen Ordner innerhalb des virtuellen Datenspeichers * * @param string $folder Pfad des neuen Ordners inkusive Ordnername innerhalb des virtuellen Datenspeichers */ function createFolder($folder) { if ($folder == "") { return false; } elseif (substr($folder, 0, 1) == "/") { $path = $this->ext_root . $folder; } else { $path = $this->ext_root . "/" . $folder; } $newFolderMetadata = $this->getMetadataByPath($path); $folderMetadata = $this->getMetadataByPath(dirname($path)); //Ordner nur Anlegen wenn übergordneter Ordner exisiert und er selbst noch nicht exisiert if ($folderMetadata && !$newFolderMetadata) { $parentId = $folderMetadata["id"]; $file = new Google_Service_Drive_DriveFile(); $file->setTitle(basename($path)); $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); $file->setMimetype("application/vnd.google-apps.folder"); return $this->gdrClient->files->insert($file); } return null; }
$children = $service->children->listChildren($folderid); // $root_filearray=$children->getItems(); // foreach ($root_filearray as $child) { // if($service->files->get($child->getId())->getExplicitlyTrashed()==1)continue; // $rootfold_title=$service->files->get($child->getId())->title; // if($login_empidarray[$i]!=$rootfold_title)continue; // $emp_folderid=$service->files->get($child->getId())->id; // echo $emp_folderid; // break; // } // if($emp_folderid=="") // { $newFolder = new Google_Service_Drive_DriveFile(); $newFolder->setMimeType('application/vnd.google-apps.folder'); $newFolder->setTitle($login_empidarray[$i]); if ($folderid != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($folderid); $newFolder->setParents(array($parent)); } try { $folderData = $service->files->insert($newFolder); } catch (Google_Service_Exception $e) { echo 'Error while creating <br>Message: '.$e->getMessage(); die(); } // } // else // continue; }
private function _copyFolderRecursive(UseyourDrive_Node $templatefolder, UseyourDrive_Node $newfolder) { if ($templatefolder !== null && $templatefolder !== false && $templatefolder->hasItem() && $newfolder !== null && $newfolder !== false && $newfolder->hasItem()) { $template_entry = $templatefolder->getItem(); $newfolder_entry = $newfolder->getItem(); if ($templatefolder->hasChildren()) { foreach ($templatefolder->getChildren() as $cached_child) { $child = $cached_child->getItem(); if ($child->getMimeType() === 'application/vnd.google-apps.folder') { /* Create child folder in user folder */ $newchildfolder = new Google_Service_Drive_DriveFile(); $newchildfolder->setTitle($child->getTitle()); $newchildfolder->setMimeType('application/vnd.google-apps.folder'); $newParent = new Google_Service_Drive_ParentReference(); $newParent->setId($newfolder_entry->getId()); $newchildfolder->setParents(array($newParent)); try { $a = 1; $newchildentry = $this->googleDriveService->files->insert($newchildfolder, array("userIp" => $this->userip)); } catch (Exception $ex) { continue; } $cachednewchildentry = $this->cache->addToCache($newchildentry); /* Copy contents of child folder to new create child user folder */ $cached_child_folder = $this->getFolder(false, $child->getId(), false, false); if ($cached_child_folder !== false && $cached_child_folder['folder'] !== false) { $this->_copyFolderRecursive($cached_child_folder['folder'], $cachednewchildentry); } } else { /* Copy file to new folder */ $newfile = new Google_Service_Drive_DriveFile(); $newfile->setTitle($child->getTitle()); $newParent = new Google_Service_Drive_ParentReference(); $newParent->setId($newfolder_entry->getId()); $newfile->setParents(array($newParent)); try { $a = 1; $newchildentry = $this->googleDriveService->files->copy($child->getId(), $newfile, array("userIp" => $this->userip)); } catch (Exception $ex) { continue; } $cachednewchildentry = $this->cache->addToCache($newchildentry); } } } } }
function UploadEmployeeFiles($formname, $loginid_result) { global $con, $ClientId, $ClientSecret, $RedirectUri, $DriveScopes, $CalenderScopes, $Refresh_Token, $emp_uldid; $loginid = $loginid_result; $emp_uploadfilelist = array(); $login_empid = getEmpfolderName($loginid); // echo $login_empid;exit; $select_folderid = mysqli_query($con, "SELECT * FROM USER_RIGHTS_CONFIGURATION WHERE URC_ID=13"); if ($row = mysqli_fetch_array($select_folderid)) { $folderid = $row["URC_DATA"]; } $drive = new Google_Client(); $Client = get_servicedata(); $ClientId = $Client[0]; $ClientSecret = $Client[1]; $RedirectUri = $Client[2]; $DriveScopes = $Client[3]; $CalenderScopes = $Client[4]; $Refresh_Token = $Client[5]; $drive->setClientId($ClientId); $drive->setClientSecret($ClientSecret); $drive->setRedirectUri($RedirectUri); $drive->setScopes(array($DriveScopes, $CalenderScopes)); $drive->setAccessType('online'); $refresh_token = $Refresh_Token; $drive->refreshToken($refresh_token); $service = new Google_Service_Drive($drive); $logincre_foldername = $login_empid; $emp_folderid = ""; $emp_uploadfilenamelist = array(); $emp_uploadfileidlist = array(); $children = $service->children->listChildren($folderid); $root_filearray = $children->getItems(); foreach ($root_filearray as $child) { if ($service->files->get($child->getId())->getExplicitlyTrashed() == 1) { continue; } $rootfold_title = $service->files->get($child->getId())->title; $split_folderid = explode(" ", $rootfold_title); if (strcasecmp($emp_uldid, $split_folderid[count($split_folderid) - 1]) != 0) { continue; } $emp_folderid = $service->files->get($child->getId())->id; if ($rootfold_title != $login_empid) { // //rename folder for loging updation start renamefile($service, $logincre_foldername, $emp_folderid); } //end $emp_uploadfilenamelist = array(); $children1 = $service->children->listChildren($child->getId()); $child_filearray = $children1->getItems(); sort($child_filearray); foreach ($child_filearray as $child1) { if ($service->files->get($child1->getId())->getExplicitlyTrashed() == 1) { continue; } $emp_uploadfilenamelist[] = $service->files->get($child1->getId())->title; } break; } sort($emp_uploadfilenamelist); $emp_uploadfileidlist = array(); $emp_uploadfilelinklist = array(); for ($f = 0; $f < count($emp_uploadfilenamelist); $f++) { $children1 = $service->children->listChildren($emp_folderid); $filearray1 = $children1->getItems(); foreach ($filearray1 as $child1) { if ($service->files->get($child1->getId())->getExplicitlyTrashed() == 1) { continue; } if ($service->files->get($child1->getId())->title == $emp_uploadfilenamelist[$f]) { $emp_uploadfileidlist[] = $service->files->get($child1->getId())->id; $emp_uploadfilelinklist[] = $service->files->get($child1->getId())->alternateLink; } } } if ($emp_folderid == "" && $formname == "login_creation") { $newFolder = new Google_Service_Drive_DriveFile(); $newFolder->setMimeType('application/vnd.google-apps.folder'); $newFolder->setTitle($logincre_foldername); if ($folderid != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($folderid); $newFolder->setParents(array($parent)); } try { $folderData = $service->files->insert($newFolder); } catch (Google_Service_Exception $e) { echo 'Error while creating <br>Message: ' . $e->getMessage(); die; } $emp_folderid = $folderData->id; } if ($formname == "login_fetch") { if ($emp_folderid == "") { echo "Error:Folder id Not present"; exit; } $emp_uploadfiles = array($emp_uploadfileidlist, $emp_uploadfilenamelist, $emp_uploadfilelinklist); return $emp_uploadfiles; } return $emp_folderid; }