Exemplo n.º 1
11
} else {
    $service = new Google_Service_Gmail($client);
    $messages = listMessages($service, 'me');
    $con = count($messages);
    //echo $con.'<br/>';
    $ar = [];
    $cnt = 0;
    for ($q = 0; $q < 200; $q += 100) {
        $messageList = array();
        for ($m = $q, $x = 0; $m < $q + 100, $x < 100; $m++, $x++) {
            $messageList[$x] = $messages[$m];
        }
        //$messages= $service->users_messages->listUsersMessages('me', array('labelIds'=>array("IMPORTANT"),'maxResults' => 100,'q'=>$str),$opt_param);
        //$messageList = $messages->getMessages();
        $client->setUseBatch(true);
        $batch = new Google_Http_Batch($client);
        foreach ($messageList as $msg_obj) {
            //echo $msg_obj->id.'<br/>';
            $request = $service->users_messages->get('me', $msg_obj->id, array('format' => 'metadata', 'metadataHeaders' => array('Date', 'To', 'From')));
            $batch->add($request, "mail-" . $msg_obj->id);
        }
        //var_dump($batch);
        echo '<br/>';
        $bMess = $batch->execute();
        //var_dump($bMess);
        foreach ($bMess as $bmn) {
            $headers = $bmn->getPayload()->getHeaders();
            $w = count($headers);
            //print $w.'<br/>';
            for ($qq = 0; $qq < $w; $qq++) {
                if ($headers[$qq]['name'] == "From") {
Exemplo n.º 2
0
 public function testInvalidBatchRequest()
 {
     $client = $this->getClient();
     $batch = new Google_Http_Batch($client);
     $this->plus = new Google_Service_Plus($client);
     $client->setUseBatch(true);
     $batch->add($this->plus->people->get('123456789987654321'), 'key1');
     $batch->add($this->plus->people->get('+LarryPage'), 'key2');
     $result = $batch->execute();
     $this->assertTrue(isset($result['response-key2']));
     $this->assertInstanceOf('Google_Service_Exception', $result['response-key1']);
 }
 public function testBatchRequest()
 {
     $client = $this->getClient();
     $batch = new Google_Http_Batch($client);
     $this->plus = new Google_Service_Plus($client);
     $client->setUseBatch(true);
     $batch->add($this->plus->people->get('+LarryPage'), 'key1');
     $batch->add($this->plus->people->get('+LarryPage'), 'key2');
     $batch->add($this->plus->people->get('+LarryPage'), 'key3');
     $result = $batch->execute();
     $this->assertTrue(isset($result['response-key1']));
     $this->assertTrue(isset($result['response-key2']));
     $this->assertTrue(isset($result['response-key3']));
 }
Exemplo n.º 4
0
 /**
  * Runs analytics query calls in batch mode
  * It accepts an array of queries as specified by the parameters of the Analytics::query function
  * With an additional optional parameter named key, which is used to identify the results for a specific object
  *
  * Returns an array with object keys as response-KEY where KEY is the key you specified or a random key returned
  * from analytics.
  * @param array $queries
  * @return array|null
  */
 public function batchQueries(array $queries)
 {
     /*
      * Set the client to use batch mode
      * When batch mode is activated calls to Analytics::query will return
      * the request object instead of the resulting data
      */
     $this->client->setUseBatch(true);
     $batch = new \Google_Http_Batch($this->client);
     foreach ($queries as $query) {
         // pull the key from the array if specified so we can later identify our result
         $key = array_pull($query, 'key');
         // call the original query method to get the request object
         $req = call_user_func_array(__NAMESPACE__ . '\\Analytics::query', $query);
         $batch->add($req, $key);
     }
     $results = $batch->execute();
     // Set the client back to normal mode
     $this->client->setUseBatch(false);
     return $results;
 }
Exemplo n.º 5
0
    public function testExecuteBodySerialization()
    {
        $io = $this->getMockBuilder('Google_IO_Abstract')->disableOriginalConstructor()->setMethods(array('makeRequest', 'needsQuirk', 'executeRequest', 'setOptions', 'setTimeout', 'getTimeout'))->getMock();
        $req = null;
        $io->expects($this->once())->method("makeRequest")->will($this->returnCallback(function ($request) use(&$req) {
            $req = $request;
            return $request;
        }));
        $this->client->expects($this->once())->method("getIo")->will($this->returnValue($io));
        $batch = new Google_Http_Batch($this->client, "BOUNDARY_TEXT", 'https://www.example.com/', 'bat');
        $req1 = new Google_Http_Request("https://www.example.com/req1");
        $req2 = new Google_Http_Request("https://www.example.com/req2", 'POST', array(), 'POSTBODY');
        $batch->add($req1, '1');
        $batch->add($req2, '2');
        $this->assertNull($batch->execute());
        $this->assertInstanceOf("Google_Http_Request", $req);
        $format = <<<'EOF'
--BOUNDARY_TEXT
Content-Type: application/http
Content-Transfer-Encoding: binary
MIME-Version: 1.0
Content-ID: 1

GET /req1? HTTP/1.1


--BOUNDARY_TEXT
Content-Type: application/http
Content-Transfer-Encoding: binary
MIME-Version: 1.0
Content-ID: 2

POST /req2? HTTP/1.1

POSTBODY

--BOUNDARY_TEXT--
EOF;
        $this->assertEquals($format, $req->getPostBody());
    }
Exemplo n.º 6
0
 $client->setDeveloperKey($apiKey);
 $service = new Google_Service_Books($client);
 /************************************************
     To actually make the batch call we need to 
     enable batching on the client - this will apply 
     globally until we set it to false. This causes
     call to the service methods to return the query
     rather than immediately executing.
    ************************************************/
 $client->setUseBatch(true);
 /************************************************
    We then create a batch, and add each query we 
    want to execute with keys of our choice - these
    keys will be reflected in the returned array.
   ************************************************/
 $batch = new Google_Http_Batch($client);
 $optParams = array('filter' => 'free-ebooks');
 $req1 = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
 $batch->add($req1, "thoreau");
 $req2 = $service->volumes->listVolumes('George Bernard Shaw', $optParams);
 $batch->add($req2, "shaw");
 /************************************************
     Executing the batch will send all requests off
     at once.
    ************************************************/
 $results = $batch->execute();
 echo "<h3>Results Of Call 1:</h3>";
 foreach ($results['response-thoreau'] as $item) {
     echo $item['volumeInfo']['title'], "<br /> \n";
 }
 echo "<h3>Results Of Call 2:</h3>";
Exemplo n.º 7
0
 function addUserFolders($userfoldernames)
 {
     $rootfolder = $this->options['root'];
     $this->client->setUseBatch(true);
     $batch = new Google_Http_Batch($this->client);
     /* Find folders */
     foreach ($userfoldernames as $key => $userfoldername) {
         if ($rootfolder === $this->options['base']) {
             $params = array('q' => "'root' in parents and title='" . $userfoldername . "' and mimeType='application/vnd.google-apps.folder' and trashed = false", "userIp" => $this->userip);
         } else {
             $params = array('q' => "'" . $rootfolder . "' in parents and title='" . $userfoldername . "' and mimeType='application/vnd.google-apps.folder' and trashed = false", "userIp" => $this->userip);
         }
         $batch->add($this->googleDriveService->files->listFiles($params), 'find-' . $key);
     }
     try {
         usleep(250000);
         // Don't fire multiple queries fast
         $batch_result = $batch->execute();
     } catch (Exception $ex) {
         return false;
     }
     /* Create folders */
     $batch = new Google_Http_Batch($this->client);
     $newfolders = false;
     foreach ($userfoldernames as $key => $userfoldername) {
         if (isset($batch_result['response-find-' . $key])) {
             $fileslist = $batch_result['response-find-' . $key];
             $files = $fileslist->getItems();
             if (count($files) === 0) {
                 $newfolder = new Google_Service_Drive_DriveFile();
                 $newfolder->setTitle($userfoldername);
                 $newfolder->setMimeType('application/vnd.google-apps.folder');
                 $newParent = new Google_Service_Drive_ParentReference();
                 $newParent->setId($rootfolder);
                 $newfolder->setParents(array($newParent));
                 $newfolders = true;
                 $batch->add($this->googleDriveService->files->insert($newfolder, array("userIp" => $this->userip)), 'create-' . $key);
             }
         } else {
             $newfolder = new Google_Service_Drive_DriveFile();
             $newfolder->setTitle($userfoldername);
             $newfolder->setMimeType('application/vnd.google-apps.folder');
             $newParent = new Google_Service_Drive_ParentReference();
             $newParent->setId($rootfolder);
             $newfolder->setParents(array($newParent));
             $newfolders = true;
             $batch->add($this->googleDriveService->files->insert($newfolder, array("userIp" => $this->userip)), 'create-' . $key);
         }
     }
     if ($newfolders) {
         $parententry = $this->cache->removeFromCache($rootfolder);
         try {
             usleep(250000);
             // Don't fire multiple queries fast
             $batch_result = $batch->execute();
         } catch (Exception $ex) {
             return false;
         }
     }
 }
Exemplo n.º 8
0
 /**
  * Retrieves events by the specified IDs.
  *
  * @param array $apiIds
  * @param bool  $withRecurrences
  * @param array $recurParams
  *
  * @return array
  */
 public function specificEvents(array $apiIds = [], $withRecurrences = false, $recurParams = [])
 {
     $this->client->setUseBatch(true);
     $batch = new \Google_Http_Batch($this->client);
     $response = [];
     /*
      * For each google API id, add each event
      * request into a batch, then execute it
      */
     if (count($apiIds) > 0) {
         foreach ($apiIds as $apiId) {
             $request = $this->event($apiId);
             $batch->add($request);
             /*
              * Request the recurrences of the events if set to true
              */
             if ($withRecurrences) {
                 $request = $this->recurrences($apiId, $recurParams);
                 $batch->add($request);
             }
         }
         $response = $batch->execute();
     }
     $events = [];
     /*
      * For each retrieved google event, convert the google object into
      * an event object
      */
     if (count($response) > 0) {
         foreach ($response as $googleEvent) {
             /*
              * If recurrences are included, we need to remove the first recurrence
              * of the event since the parent is included in the array
              */
             if ($googleEvent instanceof \Google_Service_Calendar_Events) {
                 $isFirst = true;
                 foreach ($googleEvent as $recurrence) {
                     /*
                      * Make sure we skip the first recurrence
                      */
                     if ($isFirst) {
                         $isFirst = false;
                         continue;
                     }
                     $events[] = $this->createEventObject($recurrence);
                 }
             } elseif ($googleEvent instanceof \Google_Service_Calendar_Event) {
                 $events[] = $this->createEventObject($googleEvent);
             } elseif ($googleEvent instanceof Event) {
                 $events[] = $googleEvent;
             }
         }
     }
     return $events;
 }
Exemplo n.º 9
0
 /** Batch version of function to delete user calendar permissions
  *  Uses Batch Execution in addition to google's Access Control List (Acl)
  *  @param $calendarId: calendar that the users currently have access to
  *  @param $ruleIds: should be an array of user emails and their access levels, 
  *  for example '*****@*****.**'=>'reader'. We want to delete these permissions.
  *  Calls 'delete_user_permission' function
  */
 function batch_delete_user_permissions($calendarId, $ruleIds = array())
 {
     $this->client->setUseBatch(true);
     //enable batch use
     $batch = new Google_Http_Batch($this->client);
     //Http batch object
     foreach ($ruleIds as $user => $sharePermissions) {
         try {
             $createdRule = $this->delete_user_permission($calendarId, $user);
             $batch->add($createdRule, $user);
         } catch (Exception $e) {
             print "An error occurred: " . $e->getMessage();
         }
     }
     $batch->execute();
     $this->client->setUseBatch(false);
     return true;
 }
Exemplo n.º 10
0
         } else {
             $notice = '<div class="alert alert-danger">Oops...something went wrong, try again later</div>';
         }
     }
 }
 /**
  * Get the list of message ids and filter only messages in inbox under the primary category tab
  * Also limit the result to 5 and return only the message ids
  */
 $list = $service->users_messages->listUsersMessages('me', ['maxResults' => 5, 'fields' => 'messages/id', 'q' => 'in:inbox category:primary']);
 $messageList = $list->getMessages();
 /**
  * Enable Batch Request to ease up on our HTTP Requests
  */
 $client->setUseBatch(true);
 $batch = new Google_Http_Batch($client);
 /**
  * Prepare batch request for getting user messages
  */
 foreach ($messageList as $mlist) {
     $batch->add($service->users_messages->get('me', $mlist->id, ['format' => 'raw']), $mlist->id);
 }
 /**
  * Execute the Batch Request
  */
 $batchMessages = $batch->execute();
 $inboxMessage = [];
 /**
  * Create a new Mime Mail Parser Instance ready to decode raw message content
  */
 $mimeDecode = new PhpMimeMailParser\Parser();
             $pc[$qq] = $cb;
             $cb = $pn[$q];
             $pn[$q] = $pn[$qq];
             $pn[$qq] = $cb;
         }
     }
 }
 print "Email: " . $pn[0] . "<br/>";
 print "Start date: " . date("d-M-Y", strtotime("-3 Months")) . "<br/>";
 print "End date: " . date("d-M-Y") . "<br/>";
 print "Email:     #Conv.<br/>";
 for ($q = 1; $q <= $ct; $q++) {
     print $pn[$q] . " " . $pc[$q] . "<br/>";
 }
 $client->setUseBatch(true);
 $batch = new Google_Http_Batch($client);
 foreach ($messages as $message) {
     $batch->add($service->users_messages->get('me', $message->id, ['format' => 'metadata']), $message->id);
     //		print 'Message with ID: ' . $message->getId() . '<br/>';
 }
 //  $bMess=$batch->execute();
 //    var_dump($bMess);
 /*	foreach($bMess as $bmn)
 	  {
 
 		$messageId = $bmn->id;
 		$headers = $bmn->payload->headers;
 		for($q=0;$q<25;$q++)
 		{
 			if(isset($headers[$q]))
 			{
Exemplo n.º 12
0
 public function list()
 {
     /*
     $optParams = array(
         //'maxResults' => 3,
         //'q' => 'mimeType = \'application/vnd.google-apps.folder\''
         'q' => 'mimeType = \'application/vnd.google-apps.folder\' and \'0AN_u7fy511WaUk9PVA\' in parents'
         //'q' => 'title contains \'Leasing\''
     );
     */
     $optParams = [];
     $request = $this->service->files->listFiles($optParams);
     $foo = new \Google_Http_Batch($this->client);
     $foo->add($request);
     $response = $foo->execute();
     $results = array_pop($response);
     if ($results instanceof \Google_Service_Exception) {
         var_dump($results);
         throw new \Exception('Google Service returned Exception');
     } else {
         if (count($results->getItems()) == 0) {
             print "No files found.\n";
         } else {
             /** @var Google_Service_Drive_DriveFile $file */
             foreach ($results->getItems() as $file) {
                 printf("%s:: %s %s (%s)\n", get_class($file), $file->getTitle(), $file->getKind(), $file->getId());
             }
         }
     }
 }
Exemplo n.º 13
0
 /**
  * @param IBigQueryWriteable[][] $groupedRows The rows to insert grouped by table name
  *
  * @return string[]|\Google_Service_Exception[] An array of errors encountered during the insert, indexed
  *                  by table name
  */
 public function writeBatched(array $groupedRows)
 {
     // Remove empty datasets
     foreach ($groupedRows as $tableName => $rows) {
         if (count($rows) < 1) {
             unset($groupedRows[$tableName]);
         }
     }
     // Bail out if there is nothing to write
     if (count($groupedRows) < 1) {
         return [];
     }
     $startTime = floor(microtime(true) * 1000);
     $client = $this->getClient();
     $service = $this->getService();
     $dataSet = $this->getDataSet();
     $client->setUseBatch(true);
     $batch = new \Google_Http_Batch($client);
     try {
         $totalRows = $writtenRows = 0;
         $requests = [];
         foreach ($groupedRows as $tableName => $rows) {
             /** @var IBigQueryWriteable[] $rows */
             $request = new \Google_Service_Bigquery_TableDataInsertAllRequest();
             $request->setKind('bigquery#tableDataInsertAllRequest');
             $numRows = count($rows);
             $totalRows += $numRows;
             $bqRows = [];
             foreach ($rows as $queuedRow) {
                 $row = new \Google_Service_Bigquery_TableDataInsertAllRequestRows();
                 $row->setJson($this->_serializeForBigQuery($queuedRow));
                 $row->setInsertId($queuedRow->getBigQueryInsertId());
                 $bqRows[] = $row;
             }
             $request->setRows($bqRows);
             $options = [];
             /** @var \Google_Http_Request $insertReq */
             $insertReq = $service->tabledata->insertAll($this->bigQueryProject(), $dataSet, $tableName, $request, $options);
             $requests[$tableName] = $insertReq;
             $batch->add($insertReq, $tableName);
         }
         $responses = $batch->execute();
     } finally {
         $client->setUseBatch(false);
     }
     $errors = [];
     foreach (array_keys($groupedRows) as $tableName) {
         if (isset($responses['response-' . $tableName])) {
             $response = $responses['response-' . $tableName];
             if ($response instanceof \Google_Service_Exception) {
                 $errors[$tableName] = $response->getMessage();
             } else {
                 if ($response instanceof \Google_Service_Bigquery_TableDataInsertAllResponse) {
                     $insertErrors = $response->getInsertErrors();
                     if (!empty($insertErrors)) {
                         $msg = $this->_makeErrorsMsg($insertErrors);
                         $this->_debug('Errors inserting into table ' . $dataSet . '.' . $tableName . ': ' . $msg);
                         $errors[$tableName] = $msg;
                     } else {
                         $writtenRows += count($groupedRows[$tableName]);
                     }
                 } else {
                     $errors[$tableName] = 'Unknown response type: ' . get_class($response);
                 }
             }
         } else {
             $errors[$tableName] = 'No response from BigQuery';
         }
     }
     $duration = floor(microtime(true) * 1000) - $startTime;
     $this->_debug('Wrote ' . $writtenRows . ' of ' . $totalRows . ' rows to ' . count($groupedRows) . ' table(s) in ' . $duration . ' ms with ' . count($errors) . ' error(s)');
     return $errors;
 }
Exemplo n.º 14
0
/**
 * Upload WooCommerce products to the Google Merchant Center
 * @param WC_Product[] $wc_products
 * @param Google_Client $client
 * @param string $merchant_id
 * @return array Product batch results
 */
function woogle_upload_wc_products($wc_products, $client, $merchant_id)
{
    // Shopping Content Service
    require_once plugin_dir_path(woogle_get_plugin_file()) . 'vendor/google-api-php-client/src/Google/Service/ShoppingContent.php';
    $service = new Google_Service_ShoppingContent($client);
    // Batch
    $client->setUseBatch(true);
    require_once plugin_dir_path(woogle_get_plugin_file()) . 'vendor/google-api-php-client/src/Google/Http/Batch.php';
    $product_batch = new Google_Http_Batch($client);
    // Loop through products
    foreach ($wc_products as $post) {
        // Get WC Product
        $wc_product = $post instanceof WC_Product ? $post : wc_get_product($post);
        // Get Google Product
        if ($wc_product->is_type('variable')) {
            $variations = $wc_product->get_available_variations();
            foreach ($variations as $variation) {
                $wc_product_variable = wc_get_product($variation['variation_id']);
                $product = woogle_build_product($wc_product_variable);
                // Add request to batch
                $request = $service->products->insert($merchant_id, $product);
                $product_batch->add($request, $variation['variation_id']);
            }
        } else {
            $product = woogle_build_product($wc_product);
            // Add request to batch
            $request = $service->products->insert($merchant_id, $product);
            $product_batch->add($request, $wc_product->id);
        }
        // Product updated
        $update_count++;
    }
    // Execute batch
    $product_batch_results = $product_batch->execute();
    return $product_batch_results;
}