示例#1
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;
 }
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>";
}
 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;
     }
 }
 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;
 }
示例#5
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'];
 }
示例#6
0
 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....
     }
 }
示例#7
0
文件: index.php 项目: VLADYRON/dredit
    } 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);
    }
});
/**
 * Modifies an existing file given in the request body and responds
 * with the file id. Requires login.
示例#8
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;
}
示例#9
0
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();
    //print_r( $file);
}
// end of gdurl
echo "<br> <font color =\"red\" size = \"5\" > If the page is not redirected automatically then please click <a href=\"" . $headURL . "\">here</a> to open the document </font>";
示例#10
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.');
     }
 }
示例#11
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;
    }
示例#12
0
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();
    //print_r( $file);
}
// end of gdurl
echo "<br> <font color =\"red\" size = \"5\" > If the page is not redirected automatically then please click <a href=\"" . $headURL . "\">here</a> to open the document </font>";
示例#13
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);
         }
     }
 }
    // 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 */
示例#15
0
/**
 * Insert new file.
 *
 * @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 $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_DriveFile The file that was inserted. NULL is returned if an API error occurred.
 */
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 Google_ParentReference();
        $parent->setId($parentId);
        $file->setParents(array($parent));
    }
    try {
        if ($mimeType != 'application/vnd.google-apps.folder') {
            $data = file_get_contents($filename);
            $createdFile = $service->files->insert($file, array('data' => $data, 'mimeType' => $mimeType));
        } else {
            $createdFile = $service->files->insert($file, array('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();
    }
}
示例#16
0
 public function createFolder($parent, $folderName)
 {
     if (is_array($folderName)) {
         $newFolder = null;
         $parentId = $parent;
         foreach ($folderName as $name) {
             $newFolder = $this->createFolder($parentId, $name);
             if (empty($newFolder) || !is_object($newFolder) || empty($newFolder->id)) {
                 $this->_throwExeption($this->_helper->__("Error during create the folder '%s'", $name));
             }
             $parentId = $newFolder->id;
         }
         return $newFolder;
     }
     $objFolder = new Google_DriveFile();
     $objFolder->setTitle($folderName);
     $objFolder->setMimeType(self::MIME_TYPE_GOOGLE_FOLDER);
     $objParent = new Google_ParentReference();
     $objParent->setId($parent);
     $objFolder->setParents(array($objParent));
     return $this->getService()->files->insert($objFolder);
 }
示例#17
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'));
 }
示例#18
0
 public function writeBack($tmpFile)
 {
     if (isset(self::$tempFiles[$tmpFile])) {
         $path = self::$tempFiles[$tmpFile];
         $parentFolder = $this->getDriveFile(dirname($path));
         if ($parentFolder) {
             // TODO Research resumable upload
             $mimetype = \OC_Helper::getMimeType($tmpFile);
             $data = file_get_contents($tmpFile);
             $params = array('data' => $data, 'mimeType' => $mimetype);
             $result = false;
             if ($this->file_exists($path)) {
                 $file = $this->getDriveFile($path);
                 $result = $this->service->files->update($file->getId(), $file, $params);
             } else {
                 $file = new \Google_DriveFile();
                 $file->setTitle(basename($path));
                 $file->setMimeType($mimetype);
                 $parent = new \Google_ParentReference();
                 $parent->setId($parentFolder->getId());
                 $file->setParents(array($parent));
                 $result = $this->service->files->insert($file, $params);
             }
             if ($result) {
                 $this->setDriveFile($path, $result);
             }
         }
         unlink($tmpFile);
     }
 }
示例#19
-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'];
 }