function insertFile($service, $title, $description, $parentId, $mimeType, $filename)
 {
     $file = new Google_DriveFile();
     $file->setTitle($title);
     $file->setDescription($description);
     $file->setMimeType($mimeType);
     // Set the parent folder.
     if ($parentId != null) {
         $parent = new ParentReference();
         $parent->setId($parentId);
         $file->setParents(array($parent));
     }
     try {
         $data = file_get_contents($filename);
         $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType));
         // 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();
     }
 }
Beispiel #2
2
 /**
  * Uploads backup file from server to Google Drive.
  *
  * @param 	array 	$args	arguments passed to the function
  * [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
  */
 function google_drive_backup($args)
 {
     extract($args);
     global $mmb_plugin_dir;
     require_once "{$mmb_plugin_dir}/lib/google-api-client/Google_Client.php";
     require_once "{$mmb_plugin_dir}/lib/google-api-client/contrib/Google_DriveService.php";
     $gdrive_client = new Google_Client();
     $gdrive_client->setUseObjects(true);
     $gdrive_client->setAccessToken($google_drive_token);
     $gdrive_service = new Google_DriveService($gdrive_client);
     try {
         $about = $gdrive_service->about->get();
         $root_folder_id = $about->getRootFolderId();
     } catch (Exception $e) {
         return array('error' => $e->getMessage());
     }
     try {
         $list_files = $gdrive_service->files->listFiles(array("q" => "title='{$google_drive_directory}' and '{$root_folder_id}' in parents and trashed = false"));
         $files = $list_files->getItems();
     } catch (Exception $e) {
         return array('error' => $e->getMessage());
     }
     if (isset($files[0])) {
         $managewp_folder = $files[0];
     }
     if (!isset($managewp_folder)) {
         try {
             $_managewp_folder = new Google_DriveFile();
             $_managewp_folder->setTitle($google_drive_directory);
             $_managewp_folder->setMimeType('application/vnd.google-apps.folder');
             if ($root_folder_id != null) {
                 $parent = new Google_ParentReference();
                 $parent->setId($root_folder_id);
                 $_managewp_folder->setParents(array($parent));
             }
             $managewp_folder = $gdrive_service->files->insert($_managewp_folder, array());
         } catch (Exception $e) {
             return array('error' => $e->getMessage());
         }
     }
     if ($google_drive_site_folder) {
         try {
             $subfolder_title = $this->site_name;
             $managewp_folder_id = $managewp_folder->getId();
             $list_files = $gdrive_service->files->listFiles(array("q" => "title='{$subfolder_title}' and '{$managewp_folder_id}' in parents and trashed = false"));
             $files = $list_files->getItems();
         } catch (Exception $e) {
             return array('error' => $e->getMessage());
         }
         if (isset($files[0])) {
             $backup_folder = $files[0];
         } else {
             try {
                 $_backup_folder = new Google_DriveFile();
                 $_backup_folder->setTitle($subfolder_title);
                 $_backup_folder->setMimeType('application/vnd.google-apps.folder');
                 if (isset($managewp_folder)) {
                     $_backup_folder->setParents(array($managewp_folder));
                 }
                 $backup_folder = $gdrive_service->files->insert($_backup_folder, array());
             } catch (Exception $e) {
                 return array('error' => $e->getMessage());
             }
         }
     } else {
         $backup_folder = $managewp_folder;
     }
     $file_path = explode('/', $backup_file);
     $new_file = new Google_DriveFile();
     $new_file->setTitle(end($file_path));
     $new_file->setDescription('Backup file of site: ' . $this->site_name . '.');
     if ($backup_folder != null) {
         $new_file->setParents(array($backup_folder));
     }
     $tries = 1;
     while ($tries <= 2) {
         try {
             $data = file_get_contents($backup_file);
             $createdFile = $gdrive_service->files->insert($new_file, array('data' => $data));
             break;
         } catch (Exception $e) {
             if ($e->getCode() >= 500 && $e->getCode() <= 504 && $mmb_gdrive_upload_tries <= 2) {
                 sleep(2);
                 $tries++;
             } else {
                 return array('error' => $e->getMessage());
             }
         }
     }
     return true;
 }
 public function createFolder($drive, $filename)
 {
     try {
         $about = $drive->about->get();
         // print "Root folder ID: " . $about->getRootFolderId();
         if (!$this->is_folder_exist($drive, $about->getRootFolderId(), $filename)) {
             $file = new Google_DriveFile();
             $file->setMimeType('application/vnd.google-apps.folder');
             $file->setTitle($filename);
             $createdFile = $drive->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder'));
             //    print "<br>Created folder ID: " . $createdFile->id;
             if (isset($createdFile->id) && !empty($createdFile->id)) {
                 Phpfox::getService('backuprestore.backuprestore')->saveSetting('app_folder', $createdFile->id);
             }
             return $createdFile->id;
         } else {
             if ($folderid = Phpfox::getService('backuprestore.backuprestore')->getBTDBSettingByName('app_folder')) {
                 //         print "<br>  saved folder ID: " . $folderid['setting_value'];
                 return $folderid['setting_value'];
             }
         }
     } catch (Exception $e) {
         throw $e;
     }
 }
 /**
  *	Run the backup
  */
 public function backup($files)
 {
     $fail = false;
     $this->_client->setAccessToken($this->_plugin->setting(self::token_setting));
     foreach ($files as $src => $filename) {
         $file = new \Google_DriveFile();
         $file->setTitle($filename);
         $file->setDescription('GetSimple site backup');
         $data = file_get_contents($src);
         try {
             $created_file = $this->_service->files->insert($file, array('data' => $data));
         } catch (Exception $e) {
             die($e->getMessage());
             break;
         }
     }
     return !$fail;
 }
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('1076903159369-5nv7tblb6nnlks5qbl588qhhoff894r0.apps.googleusercontent.com');
$client->setClientSecret('oRCdkRIqRQ53SlTyKIelJLMV');
$client->setRedirectUri('');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
if (isset($_GET['code'])) {
    $authCode = trim($_GET['code']);
    // Exchange authorization code for access token
    $accessToken = $client->authenticate($authCode);
    $client->setAccessToken($accessToken);
    //Insert a file
    $file = new Google_DriveFile();
    $file->setTitle('My document - ' . date('m-d-Y', time()));
    $file->setDescription('A test document');
    $file->setMimeType('text/plain');
    $data = file_get_contents('backupdb.sql');
    $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => 'text/plain'));
    if ($createdFile) {
        echo "<script>alert('Database exported into Google Drive successfully');</script>";
    } else {
        echo "<script>alert('Error! while uploading file');</script>";
    }
} else {
    echo "<script>window.location.href='" . $authUrl . "';</script>";
}
 function uploadFile($filePath = "", $fileName, $folderId = null)
 {
     if ($fileName == null) {
         $fileName = basename($filePath);
     }
     $data = "";
     $file = new Google_DriveFile();
     $file->setTitle($fileName);
     if ($filePath) {
         $file->setMimeType('');
         $data = file_get_contents($filePath);
     } else {
         $file->setMimeType('application/vnd.google-apps.folder');
     }
     if ($folderId != null) {
         $folders = explode(",", $folderId);
         $parents = array();
         foreach ($folders as $folder) {
             $parent = new Google_ParentReference();
             $parent->setId($folder);
             array_push($parents, $parent);
         }
         $file->setParents($parents);
     }
     $service = new Google_DriveService($this->gClient);
     $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => ''));
     return $createdFile;
 }
 public static function wp_db_backup_completed(&$args)
 {
     $authCode = get_option('wpdb_dest_google_authCode');
     $clientId = get_option('wpdb_dest_google_client_key');
     $clientSecret = get_option('wpdb_dest_google_secret_key');
     if (!empty($authCode) && !empty($clientId) && !empty($clientSecret)) {
         set_time_limit(0);
         require_once "google-api-php-client/src/Google_Client.php";
         require_once "google-api-php-client/src/contrib/Google_DriveService.php";
         $client = new Google_Client();
         // Get your credentials from the APIs Console
         $client->setClientId($clientId);
         $client->setClientSecret($clientSecret);
         $client->setRedirectUri(site_url() . '/wp-admin/tools.php?page=wp-database-backup&action=auth');
         $client->setScopes(array("https://www.googleapis.com/auth/drive"));
         $service = new Google_DriveService($client);
         // Exchange authorisation code for access token
         if (!file_exists("token.json")) {
             // Save token for future use
             $accessToken = $client->authenticate($authCode);
             file_put_contents("token.json", $accessToken);
         } else {
             $accessToken = file_get_contents("token.json");
         }
         $client->setAccessToken($accessToken);
         // Upload file to Google Drive
         $file = new Google_DriveFile();
         $file->setTitle($args[0]);
         $file->setDescription("WP Database Backup : database backup file-" . site_url());
         $file->setMimeType("application/gzip");
         $data = file_get_contents($args[1]);
         $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => "application/gzip"));
         $args[2] = $args[2] . '<br> Upload Database Backup on google drive';
         // Process response here....
     }
 }
Beispiel #8
0
 public function createFile($name, $mime, $description, $content, Google_ParentReference $fileParent = null)
 {
     $file = new Google_DriveFile();
     $file->setTitle($name);
     $file->setDescription($description);
     $file->setMimeType($mime);
     if ($fileParent) {
         $file->setParents(array($fileParent));
     }
     $createdFile = $this->_service->files->insert($file, array('data' => $content, 'mimeType' => $mime));
     return $createdFile['id'];
 }
Beispiel #9
0
        $response = $client->getIo()->authenticatedRequest($request);
        $file->content = $response->getResponseBody();
        renderJson($app, $file);
    } catch (Exception $ex) {
        renderEx($app, $ex);
    }
});
/**
 * Creates a new file with the metadata and contents
 * in the request body. Requires login.
 */
$app->post('/svc', function () use($app, $client, $service) {
    checkUserAuthentication($app);
    $inputFile = json_decode($app->request()->getBody());
    try {
        $file = new Google_DriveFile();
        $file->setTitle($inputFile->title);
        $file->setDescription($inputFile->description);
        $file->setMimeType($mimeType);
        // Set the parent folder.
        if ($inputFile->parentId != null) {
            $parentsCollectionData = new Google_DriveFileParentsCollection();
            $parentsCollectionData->setId($inputFile->parentId);
            $file->setParentsCollection(array($parentsCollectionData));
        }
        $createdFile = $service->files->insert($file, array('data' => $inputFile->content, 'mimeType' => $mimeType));
        renderJson($app, $createdFile->id);
    } catch (Exception $ex) {
        renderEx($app, $ex);
    }
});
Beispiel #10
0
    $fileId = 1;
    //$row['fid'];
    $file = new Google_DriveFile();
    $file = $service->files->get($fileId);
    $data = downloadFile($service, $file);
    $name = $file->getTitle();
    make($data, $name);
    mysql_query("UPDATE files SET fname='" . $name . "' WHERE sr='1'") or die('error updating');
    echo '<script type="text/javascript">';
    echo 'window.location.href = "http://localhost/Dropbox-master/examples/putFile.php";';
    echo '</script>';
} elseif ($flow == 'up') {
    //**************************************************  UPLOAD  ****************************************************************************
    $name = 'WorldCup2014.txt';
    //Insert a file
    $file = new Google_DriveFile();
    $file->setTitle($name);
    //$file->setDescription('A test document');
    //$file->setMimeType('text/plain');
    $data = file_get_contents($name);
    $createdFile = $service->files->insert($file, array('data' => $data));
    print_r($createdFile);
    /*
    unlink($name); //Our privacy policy means we do not keep user's data 
    session_destroy();
    
    echo '<script type="text/javascript">';
    echo 'window.location.href = "http://localhost/C2CSync";';
    echo '</script>';*/
} else {
    $fileId = '0B8OGNVz7DYmxcjAzTkp1cW56RnM';
Beispiel #11
0
function bdn_do_budget_item()
{
    if (empty($_GET['action']) || $_GET['action'] != 'do_budget_item') {
        return;
    }
    //Nonce, always
    if (empty($_POST['budget_item_nonce']) || !wp_verify_nonce($_POST['budget_item_nonce'], 'budget-nonce')) {
        return;
    }
    //If we're modifying a doc, get it as an array
    //Else create an empty array
    if (!empty($_POST['budget']['id']) && (int) $_POST['budget']['id'] != 0) {
        $post_id = (int) $_POST['budget']['id'];
        $post = get_post($post_id, ARRAY_A);
        //Check and see if there's an existing visuals request
        $visuals_request = get_post_meta($post_id, '_visuals_request', true);
        $new = false;
    } else {
        $post = array();
        $new = true;
        $visuals_request = false;
    }
    //Save this so we can check if anything has changed
    $orig = $post;
    $post['post_type'] = 'doc';
    $post['post_status'] = 'publish';
    $post['post_title'] = $_POST['budget']['slug'];
    $post['post_excerpt'] = $_POST['budget']['description'];
    $post['post_author'] = (int) $_POST['budget']['author'];
    //This will update if $post[ 'ID' ] is set, else will create a new post and return its ID
    if ($post != $orig) {
        $post_id = wp_insert_post($post);
    }
    //Set the importance and desk
    wp_set_object_terms($post_id, (int) $_POST['budget']['desk'], 'desk');
    wp_set_object_terms($post_id, (int) $_POST['budget']['importance'], 'importance');
    //If it's a new budget item, give it the default status (Story idea submitted)
    if ($new) {
        wp_set_object_terms($post_id, DEFAULT_STATUS, 'status');
    }
    //Get the file time
    $file_time = strtotime($_POST['budget']['time']);
    //And save off the day as a term
    wp_set_object_terms($post_id, date('Y-m-d', $file_time), 'day');
    //We're keeping a full record of all the different file times, so get what we have so far and the latest file time
    $file_times = json_decode(get_post_meta($post_id, '_budget_file_time', true), true);
    if (!is_array($file_times)) {
        $file_times = array();
    }
    $last_file_time = end($file_times);
    //If the submitted file time does not equal the latest file time, add to the array
    if (!empty($file_times) || empty($last_file_time) || empty($last_file_time['value']) || $last_file_time['value'] != $file_time) {
        $file_times[date_i18n('U')] = array('user' => get_current_user_id(), 'value' => date('Y-m-d H:i', $file_time));
    }
    //Save the latest file time (for sorting purposes) and the array
    $the_file_time = end($file_times);
    update_post_meta($post_id, '_the_file_time', $the_file_time['value']);
    update_post_meta($post_id, '_budget_file_time', json_encode($file_times));
    //Save the budget lenght
    update_post_meta($post_id, '_budget_length', (int) $_POST['budget']['length']);
    //Visuals requests! Hooray!
    //First scenario: The budget line already has a visuals request
    //and we're just editing the existing one
    if ((int) $visuals_request > 0 && $_POST['budget']['visuals']['request'] == 'request') {
        //Get the post and modify what needs to be modified
        $visuals = get_post($visuals_request, true);
        $visuals['post_excerpt'] = $_POST['budget']['visuals']['details'];
        $visuals['post_title'] = $_POST['budget']['visuals']['time'];
        //Editors' visual requests go in as published,
        //reporters' go in as drafts (default)
        //But don't override the existing status
        if (current_user_can('edit_others_posts')) {
            $visuals['post_status'] = 'publish';
        }
        wp_update_post($visuals);
        //The visuals request gets the same date as the budget line
        wp_set_object_terms($visuals['ID'], date('Y-m-d', $file_time), 'day');
        //Second scenario: The budget line already has a visuals request
        //but we're canceling it.
    } elseif ((int) $visuals_request > 0 && $_POST['budget']['visuals']['request'] != 'request') {
        //Get the post and set the status to canceled (but don't delete)
        $visuals = get_post($visuals_request, true);
        $visuals['post_status'] = 'canceled';
        wp_update_post($visuals);
        //Update with the new visuals status
        update_post_meta($post_id, '_visuals_request', $_POST['budget']['visuals']['request']);
        //Third scenario: There is a new visuals request
    } elseif ((int) $visuals_request == 0 && $_POST['budget']['visuals']['request'] == 'request') {
        //Build the array to insert a new object
        $visuals = array('post_type' => 'visual', 'post_excerpt' => $_POST['budget']['visuals']['details'], 'post_title' => $_POST['budget']['visuals']['time'], 'post_parent' => $post_id);
        //If it's an editor, publish it
        if (current_user_can('edit_others_posts')) {
            $visuals['post_status'] = 'publish';
        }
        $visuals_id = wp_insert_post($visuals);
        wp_set_object_terms($visuals_id, date('Y-m-d', $file_time), 'day');
        update_post_meta($post_id, '_visuals_request', $visuals_id);
        //Last scenario: There's some other form of the request
    } else {
        update_post_meta($post_id, '_visuals_request', $_POST['budget']['visuals']['request']);
    }
    //Go either to the doc or just reload the page
    $loc = !empty($_POST['budget']['go']['doc']) ? get_permalink($post_id) : remove_query_arg('action');
    //If this isn't new, just redirect
    if (!$new && get_post_meta($post_id, '_gdocID', true)) {
        wp_redirect($loc);
    } else {
        //Check and see if there's a drive object stored globally
        global $driveService;
        //If there's not, we should set one up
        if (!is_object($driveService)) {
            $driveService = bdn_is_user_auth();
        }
        //Create a new Google Drive File
        //@TODO This should open up in the newsroom site
        $file = new Google_DriveFile();
        $file->setTitle($post['post_title']);
        $file->setMimeType('application/vnd.google-apps.document');
        //Let's see what happens
        //We can fake attach a Google Doc by inserting a new DOM element with the ID of the doc we're trying to attach
        if (!empty($_POST['budget']['doc'])) {
            $createdFile = array('id' => $_POST['budget']['doc']);
        } else {
            //Exponential backoff. If we get an error, try again after 2 seconds, then 4 seconds, then 8 seconds, etc.
            //We get a lot of 500 errors, so this catches many of them
            $tries = 0;
            for ($i = 0; $i < 10; $i++) {
                if (!empty($createdFile['id'])) {
                    continue;
                }
                $tries++;
                sleep($i * 2);
                try {
                    $params = array();
                    if ($i > 2) {
                        $params['token'] = '';
                    }
                    $createdFile = $driveService->files->insert($file, $params);
                } catch (Exception $e) {
                    if (strpos($e->getMessage(), 'Error refreshing the OAuth2 token') !== false) {
                        delete_user_meta(get_current_user_id(), '_google_access_token');
                    }
                    //@TODO: Check if it's an error we should be retrying for
                    error_log('DRIVE API ERROR: ' . $e->getMessage() . ' : ' . json_encode($e));
                    $createdFile = false;
                }
            }
        }
        //Just so we know, how many tries did this take?
        header('Tries: ' . $tries);
        //error_log( 'DRIVE TRIES: ' . $tries );
        //Save off the ID of the Doc
        update_post_meta($post_id, '_gdocID', $createdFile['id']);
        bdn_set_doc_permissions($createdFile['id'], $post);
        //Redirect either to the doc or back to where we are now
        wp_redirect($loc);
    }
    //Always kill the program when you're done
    exit;
}
$row = mysql_fetch_array($result);
$gdurl = $row['gppturl'];
// used at 2 place here and in update query
$vidName = $row['name'];
if ($gdurl != null or $gdurl != "") {
    // Set the URL to which it has to be redirected.
    $headURL = $gdurl;
} else {
    //Build the Drive Service object authorized with your Service Account
    $auth = new Google_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH));
    $client = new Google_Client();
    $client->setUseObjects(true);
    $client->setAssertionCredentials($auth);
    $service = new Google_DriveService($client);
    //Create the file
    $file = new Google_DriveFile();
    $file->setTitle($vidName);
    //$file->setDescription("Please feel free to write to this document and collaborate");
    // set the default description of the document
    $file->setMimeType('application/vnd.google-apps.presentation');
    $file = $service->files->insert($file);
    //Give everyone permission to read and write the file
    $permission = new Google_Permission();
    $permission->setRole('writer');
    $permission->setType('anyone');
    $permission->setValue('me');
    $permission->setwithLink(true);
    $service->permissions->insert($file->getId(), $permission);
    $headURL = $file->getalternateLink();
    mysql_query("UPDATE videonodes set gppturl='{$headURL}' WHERE id='{$vid}'") or die(mysql_error());
    //echo $file->getalternateLink();
Beispiel #13
0
 /**
  * Upload a file.
  */
 public function actionUpload()
 {
     if (isset($_FILES['upload'])) {
         if (isset($_POST['drive']) && $_POST['drive']) {
             // google drive
             $auth = new GoogleAuthenticator();
             if ($auth->getAccessToken()) {
                 $service = $auth->getDriveService();
             }
             $createdFile = null;
             if (isset($service, $_SESSION['access_token'], $_FILES['upload'])) {
                 try {
                     $file = new Google_DriveFile();
                     $file->setTitle($_FILES['upload']['name']);
                     $file->setDescription('Uploaded by X2Engine');
                     $file->setMimeType($_FILES['upload']['type']);
                     if (empty($_FILES['upload']['tmp_name'])) {
                         $err = false;
                         switch ($_FILES['newfile']['error']) {
                             case UPLOAD_ERR_INI_SIZE:
                             case UPLOAD_ERR_FORM_SIZE:
                                 $err .= 'File size exceeds limit of ' . get_max_upload() . ' bytes.';
                                 break;
                             case UPLOAD_ERR_PARTIAL:
                                 $err .= 'File upload was not completed.';
                                 break;
                             case UPLOAD_ERR_NO_FILE:
                                 $err .= 'Zero-length file uploaded.';
                                 break;
                             default:
                                 $err .= 'Internal error ' . $_FILES['newfile']['error'];
                                 break;
                         }
                         if ((bool) $message) {
                             throw new CException($message);
                         }
                     }
                     $data = file_get_contents($_FILES['upload']['tmp_name']);
                     $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $_FILES['upload']['type']));
                     if (is_array($createdFile)) {
                         $model = new Media();
                         $model->fileName = $createdFile['id'];
                         $model->name = $createdFile['title'];
                         if (isset($_POST['associationId'])) {
                             $model->associationId = $_POST['associationId'];
                         }
                         if (isset($_POST['associationType'])) {
                             $model->associationType = $_POST['associationType'];
                         }
                         if (isset($_POST['private'])) {
                             $model->private = $_POST['private'];
                         }
                         $model->uploadedBy = Yii::app()->user->getName();
                         $model->mimetype = $createdFile['mimeType'];
                         $model->filesize = $createdFile['fileSize'];
                         $model->drive = 1;
                         $model->save();
                         if ($model->associationType == 'feed') {
                             $event = new Events();
                             $event->user = Yii::app()->user->getName();
                             if (isset($_POST['attachmentText']) && !empty($_POST['attachmentText'])) {
                                 $event->text = $_POST['attachmentText'];
                             } else {
                                 $event->text = Yii::t('app', 'Attached file: ');
                             }
                             $event->type = 'media';
                             $event->timestamp = time();
                             $event->lastUpdated = time();
                             $event->associationId = $model->id;
                             $event->associationType = 'Media';
                             $event->save();
                             $this->redirect(array('/profile/view', 'id' => Yii::app()->user->getId()));
                         } elseif ($model->associationType == 'docs') {
                             $this->redirect(array('/docs/docs/index'));
                         } elseif (!empty($model->associationType) && !empty($model->associationId)) {
                             $note = new Actions();
                             $note->createDate = time();
                             $note->dueDate = time();
                             $note->completeDate = time();
                             $note->complete = 'Yes';
                             $note->visibility = '1';
                             $note->completedBy = Yii::app()->user->getName();
                             if ($model->private) {
                                 $note->assignedTo = Yii::app()->user->getName();
                                 $note->visibility = '0';
                             } else {
                                 $note->assignedTo = 'Anyone';
                             }
                             $note->type = 'attachment';
                             $note->associationId = $_POST['associationId'];
                             $note->associationType = $_POST['associationType'];
                             $association = $this->getAssociation($note->associationType, $note->associationId);
                             if ($association != null) {
                                 $note->associationName = $association->name;
                             }
                             $note->actionDescription = $model->fileName . ':' . $model->id;
                             if ($note->save()) {
                                 $this->redirect(array($model->associationType . '/' . $model->associationId));
                             }
                         } else {
                             $this->redirect('/media/media/view', array('id' => $model->id));
                         }
                     } else {
                         throw new CHttpException('400', 'Invalid request.');
                     }
                 } catch (Google_AuthException $e) {
                     $auth->flushCredentials();
                     $auth->setErrors($e->getMessage());
                     $service = null;
                     $createdFile = null;
                 }
             } else {
                 if (isset($_SERVER['HTTP_REFERER'])) {
                     $this->redirect($_SERVER['HTTP_REFERER']);
                 } else {
                     throw new CHttpException('400', 'Invalid request');
                 }
             }
         } else {
             // non-google drive upload
             $model = new Media();
             $temp = CUploadedFile::getInstanceByName('upload');
             // file uploaded through form
             $tempName = $temp->getTempName();
             if (isset($temp) && !empty($tempName)) {
                 $name = $temp->getName();
                 $name = str_replace(' ', '_', $name);
                 $check = Media::model()->findAllByAttributes(array('fileName' => $name));
                 // rename file if there name conflicts by suffixing "(n)"
                 if (count($check) != 0) {
                     $count = 1;
                     $newName = $name;
                     $arr = explode('.', $name);
                     $name = $arr[0];
                     while (count($check) != 0) {
                         $newName = $name . '(' . $count . ').' . $temp->getExtensionName();
                         $check = Media::model()->findAllByAttributes(array('fileName' => $newName));
                         $count++;
                     }
                     $name = $newName;
                 }
                 $username = Yii::app()->user->name;
                 // copy file to user's media uploads directory
                 if (FileUtil::ccopy($tempName, "uploads/media/{$username}/{$name}")) {
                     if (isset($_POST['associationId'])) {
                         $model->associationId = $_POST['associationId'];
                     }
                     if (isset($_POST['associationType'])) {
                         $model->associationType = $_POST['associationType'];
                     }
                     if (isset($_POST['private'])) {
                         $model->private = $_POST['private'];
                     }
                     $model->uploadedBy = Yii::app()->user->getName();
                     $model->createDate = time();
                     $model->lastUpdated = time();
                     $model->fileName = $name;
                     if (!$model->save()) {
                         $errors = $model->getErrors();
                         $error = ArrayUtil::pop(ArrayUtil::pop($errors));
                         Yii::app()->user->setFlash('top-error', Yii::t('app', 'Attachment failed. ' . $error));
                         $this->redirect(array($model->associationType . '/' . $model->associationType . '/view', 'id' => $model->associationId));
                         Yii::app()->end();
                     }
                     // handle different upload types
                     switch ($model->associationType) {
                         case 'feed':
                             $this->handleFeedTypeUpload($model, $name);
                             break;
                         case 'docs':
                             $this->redirect(array('/docs/docs/index'));
                             break;
                         case 'loginSound':
                         case 'notificationSound':
                             $this->redirect(array('/profile/settings', 'id' => Yii::app()->user->getId()));
                             break;
                         case 'bg':
                         case 'bg-private':
                             $this->redirect(array('/profile/settings', 'id' => Yii::app()->user->getId(), 'bgId' => $model->id));
                             break;
                         default:
                             $this->handleDefaultUpload($model, $name);
                             break;
                     }
                 }
             } else {
                 if (isset($_SERVER['HTTP_REFERER'])) {
                     $this->redirect($_SERVER['HTTP_REFERER']);
                 } else {
                     throw new CHttpException('400', 'Invalid request');
                 }
             }
         }
     } else {
         throw new CHttpException('400', 'Invalid request.');
     }
 }
Beispiel #14
0
 public function uploadfile()
 {
     if ($_FILES['upld_file'] && $this->input->post('folderid')) {
         try {
             $client = $this->google_client;
             $client->setAccessToken($this->session->userdata('accessToken'));
             $service = new Google_DriveService($client);
             $folderdetailArray = $this->usermodel->getallfolders($this->input->post('folderid'), 'getbyId');
             //pr($folderdetailArray);
             /*$file = new Google_DriveFile();
             		$file->setTitle($_FILES['upld_file']['name']);
             		$file->setDescription('This is a '.$_FILES['upld_file']['type'].' document');
             		$file->setMimeType($_FILES['upld_file']['type']);
             		$service->files->insert(
             		    $file,
             		    array(
             			'data' => file_get_contents($_FILES['upld_file']['tmp_name']),
             			'mimeType' => $_FILES['upld_file']['type']
             		    )
             		);*/
             $title = $_FILES['upld_file']['name'];
             $description = 'This is a ' . $_FILES['upld_file']['type'] . ' document';
             $parentId = $folderdetailArray[0]['googlefolderId'];
             $mimeType = $_FILES['upld_file']['type'];
             $filename = $_FILES['upld_file']['name'];
             $filepath = $_FILES['upld_file']['tmp_name'];
             $file = new Google_DriveFile();
             $file->setTitle($title);
             $file->setDescription($description);
             $file->setMimeType($mimeType);
             if ($parentId != null) {
                 $parent = new Google_ParentReference();
                 $parent->setId($parentId);
                 $file->setParents(array($parent));
             }
             $service->files->insert($file, array('data' => file_get_contents($filepath), 'mimeType' => $mimeType));
             //pr($service);
             /*Recent file insert function call*/
             $array = array('title' => $title, 'doc_id' => '', 'doc_type' => $mimeType, 'folder_id' => $parentId, 'folder_name' => '', 'user_id' => $this->session->userdata('userid'), 'action_description' => 'File uploading');
             $this->usermodel->saverecentfiles($array);
             //insertFile($service, $title, $description, $parentId, $mimeType, $filename,$filepath);
             $this->session->set_flashdata('message', '<div class="alert-success">' . $this->lang->line('file_upload_sucesss') . '</div>');
             redirect('users/fileListing/' . $parentId);
         } catch (Exception $e) {
             pre($e);
             exit;
             $this->session->set_flashdata('message', '<div class="alert-error">' . $this->lang->line('file_upload_sucesss') . '</div>');
             redirect('users/fileListing/' . $parentId);
         }
     }
 }
    header('location:' . $url);
    exit;
} elseif (!isset($_SESSION['accessToken'])) {
    $client->authenticate();
}
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
    if ($file != '.' && $file != '..') {
        $files[] = $file;
    }
}
$dir->close();
if (!empty($_POST)) {
    $client->setAccessToken($_SESSION['accessToken']);
    $service = new Google_DriveService($client);
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $file = new Google_DriveFile();
    foreach ($files as $file_name) {
        $file_path = 'files/' . $file_name;
        $mime_type = finfo_file($finfo, $file_path);
        $file->setTitle($file_name);
        $file->setDescription('This is a ' . $mime_type . ' document');
        $file->setMimeType($mime_type);
        $service->files->insert($file, array('data' => file_get_contents($file_path), 'mimeType' => $mime_type));
    }
    finfo_close($finfo);
    header('location:' . $url);
    exit;
}
include 'index.phtml';
Beispiel #16
0
    public function send_package() {
        if (!$this->client) {
            throw new portfolio_plugin_exception('noauthtoken', 'portfolio_googledocs');
        }
        // Portfolio_exporter::rewaken_object does not 'wake' client properly
        // ...auth is null after unserialize, therefore initialize again!!!
        if (!$this->client->getAuth()) {
            $this->initialize_oauth();
            // Get access token from session and set it to client.
            if (!$this->get_access_token()) {
                throw new portfolio_plugin_exception('noauthtoken', 'portfolio_googledocs');
            }
        }

        foreach ($this->exporter->get_tempfiles() as $file) {
            try {
                // Create drivefile object and fill it with data.
                $drivefile = new Google_DriveFile();
                $drivefile->setTitle($file->get_filename());
                $drivefile->setMimeType($file->get_mimetype());

                $filecontent = $file->get_content();
                $createdfile = $this->service->files->insert($drivefile,
                                                            array('data' => $filecontent,
                                                                  'mimeType' => $file->get_mimetype(),
                                                                  'uploadType' => 'multipart'));
            } catch ( Exception $e ) {
                throw new portfolio_plugin_exception('sendfailed', 'portfolio_gdocs', $file->get_filename());
            }
        }
        return true;
    }
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$gdurl = $row['gdurl'];
$vidName = $row['name'];
if ($gdurl != null or $gdurl != "") {
    // Set the URL to which it has to be redirected.
    $headURL = $gdurl;
} else {
    //Build the Drive Service object authorized with your Service Account
    $auth = new Google_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH));
    $client = new Google_Client();
    $client->setUseObjects(true);
    $client->setAssertionCredentials($auth);
    $service = new Google_DriveService($client);
    //Create the file
    $file = new Google_DriveFile();
    $file->setTitle($vidName);
    //$file->setDescription("Please feel free to write to this document and collaborate");
    // set the default description of the document
    $file->setMimeType('application/vnd.google-apps.document');
    $file = $service->files->insert($file);
    //Give everyone permission to read and write the file
    $permission = new Google_Permission();
    $permission->setRole('writer');
    $permission->setType('anyone');
    $permission->setValue('me');
    $permission->setwithLink(true);
    $service->permissions->insert($file->getId(), $permission);
    $headURL = $file->getalternateLink();
    mysql_query("UPDATE videonodes set gdurl='{$headURL}' WHERE id='{$vid}'") or die(mysql_error());
    //echo $file->getalternateLink();
    // Save token for future use
    $accessToken = $client->authenticate($authCode);
    file_put_contents("token.json", $accessToken);
} else {
    $accessToken = file_get_contents("token.json");
}
$client->setAccessToken($accessToken);
// Upload file to Google Drive
$file = new Google_DriveFile();
$file->setTitle($fprefix . $uid . ".tar.gz");
$file->setDescription("Server backup file");
$file->setMimeType("application/gzip");
$data = file_get_contents($homedir . $fprefix . $uid . ".tar.gz");
$createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => "application/gzip"));
// Process response here....
print_r($createdFile);
// Upload database to Google Drive
$file = new Google_DriveFile();
$file->setTitle($dprefix . $uid . ".sql.gz");
$file->setDescription("Database backup file");
$file->setMimeType("application/gzip");
$data = file_get_contents($homedir . $dprefix . $uid . ".sql.gz");
$createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => "application/gzip"));
// Process response here....
print_r($createdFile);
/* CLEANUP */
// Delete created files
unlink($homedir . $fprefix . $uid . ".tar.gz");
unlink($homedir . $dprefix . $uid . ".sql.gz");
/* References:
   https://developers.google.com/drive/quickstart-php */
Beispiel #19
0
 public function putFileChunk($name, $file)
 {
     $file = realpath($file);
     if (!file_exists($file)) {
         $this->_throwExeption($this->_helper->__('File "%s" doesn\'t exist', strval($file)));
     }
     $handle = fopen($file, "rb");
     $filename = basename($name);
     $chunkSize = $this->getChunkSize();
     $fileObject = new Google_DriveFile();
     $fileObject->setTitle($filename);
     if (!($mimeType = $this->getRequestMimeType())) {
         if (substr(".tar.gz", -7)) {
             $mimeType = self::MIME_TYPE_TGZ;
         } else {
             if (substr(".gz", -3)) {
                 $mimeType = self::MIME_TYPE_GZIP;
             } else {
                 $mimeType = self::MIME_TYPE_GOOGLE_FILES;
             }
         }
         $this->setRequestMimeType($mimeType);
     }
     if (!($parentId = $this->getRequestParentId())) {
         $parentId = $this->getBackupFolder();
         $this->setRequestParentId($parentId);
     }
     if ($parentId != null) {
         $parent = new Google_ParentReference();
         $parent->setId($parentId);
         $fileObject->setParents(array($parent));
     }
     $media = new Google_MediaFileUpload($mimeType, null, true, $chunkSize);
     if (!($fileSize = $this->getRequestFileSize())) {
         $fileSize = $this->filesize($file);
     }
     $media->setFileSize($fileSize);
     $byte = $startByte = (double) $this->getRequestBytes();
     if ($byte > 0) {
         $this->fseek($handle, $byte);
         $media->resumeUri = $this->getRequestUrl();
         $media->progress = $byte;
     }
     /**
      * @var Google_HttpRequest $httpRequest
      * @see Google_FilesServiceResource::insert
      */
     $httpRequest = $this->getService(false)->files->insert($fileObject, array('mimeType' => $mimeType, 'mediaUpload' => $media));
     while (!feof($handle)) {
         if ($this->timeIsUp()) {
             $this->setRequestBytes($byte);
             $this->setRequestUrl($media->resumeUri);
             $nextChunk = true;
             break;
         }
         $chunk = fread($handle, $chunkSize);
         $uploadStatus = $media->nextChunk($httpRequest, $chunk);
         $byte += $chunkSize;
     }
     fclose($handle);
     $locale = Mage::app()->getLocale()->getLocale();
     if (isset($nextChunk)) {
         $this->_addBackupProcessMessage($this->_helper->__('Bytes from %1$s to %2$s were added (total: %3$s)', Zend_Locale_Format::toNumber($startByte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($byte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale))));
         return false;
     }
     $this->_addBackupProcessMessage($this->_helper->__('Bytes from %1$s to %2$s were added (total: %3$s)', Zend_Locale_Format::toNumber($startByte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale))));
     if (!isset($uploadStatus) || !is_array($uploadStatus) || empty($uploadStatus['id'])) {
         $this->_throwExeption($this->_helper->__('Error chunk upload response'));
     }
     $fileCloudPath = $this->getConfigValue(self::APP_PATH);
     $returnPath = $fileCloudPath . '/' . $filename;
     $this->_addAdditionalInfo($uploadStatus['id'], $returnPath);
     $this->clearRequestParams();
     return $returnPath;
 }
Beispiel #20
0
function moveFile($service, $fileId, $parentId)
{
    try {
        $file = new Google_DriveFile();
        $file->setParent($parentId);
        $updatedFile = $service->files->patch($fileId, $file, array('fields' => 'parents'));
        return $updatedFile;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
Beispiel #21
0
 public function createFolder($title, $parentId = null)
 {
     $client = $this->getClient();
     $service = new Google_DriveService($client);
     $file = new Google_DriveFile();
     $file->setTitle($title);
     $file->setMimeType('application/vnd.google-apps.folder');
     if (null !== $parentId) {
         $parent = new Google_ParentReference();
         $parent->setId($parentId);
         $file->setParents(array($parent));
     }
     return $service->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder'));
 }
Beispiel #22
0
 public function touch($path, $mtime = null)
 {
     $file = $this->getDriveFile($path);
     $result = false;
     if ($file) {
         if (isset($mtime)) {
             $file->setModifiedDate($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_DriveFile();
             $file->setTitle(basename($path));
             $parent = new \Google_ParentReference();
             $parent->setId($parentFolder->getId());
             $file->setParents(array($parent));
             $result = $this->service->files->insert($file);
         }
     }
     if ($result) {
         $this->setDriveFile($path, $result);
     }
     return (bool) $result;
 }
Beispiel #23
-1
 public function createFolder($name)
 {
     $file = new Google_DriveFile();
     $file->setTitle($name);
     $file->setMimeType('application/vnd.google-apps.folder');
     $createdFolder = $this->_service->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder'));
     return $createdFolder['id'];
 }