old_g_letter.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. <?php
  2. /* *************************************************** */
  3. // Google Docs Creator
  4. // Gets a Tempalate copies it and inserts data,
  5. // Then saves into the specified folder as a Doc and as a PDF
  6. // In future it will email the pdf to customer email
  7. // (c) 2023 Benjamin Harris ben@tazz.com.au
  8. /* *************************************************** */
  9. //phpinfo();
  10. error_reporting(E_ALL);
  11. ini_set('display_errors', 1);
  12. //error_reporting(E_ERROR | E_PARSE);
  13. //
  14. require_once 'vendor/autoload.php';
  15. session_start();
  16. date_default_timezone_set("Australia/Hobart");
  17. $today = date("Y-m-d");
  18. $datetime = date("D dS M y @ h:i a");
  19. //Variables to insert into Google Doc
  20. $date = date("D dS M y");
  21. $first_name = 'John';
  22. $last_name = 'Doe';
  23. $name = $first_name . ' ' . $last_name;
  24. $company = 'ABC Company';
  25. $postal_address = '123 Some Street, Some Town, Some State, Some PC';
  26. $drg = '301003';
  27. $building_description = 'Commercial Extension';
  28. $site_address = '456 black Street, Black Town, Black State, Black PC';
  29. $street = explode(",", $site_address);
  30. $site_address_street = substr($street[0], 0);
  31. $agent = 'Benjamin Harris';
  32. $agent_company = 'Agent Company';
  33. $file_name = $drg . ' - ' . $name . ' - LOA - ' . $today;
  34. // Set up Google API Client
  35. $client = new Google\Client();
  36. $client->setAuthConfig('oauth-credentials.json');
  37. $client->setScopes([Google_Service_Drive::DRIVE, Google_Service_Docs::DOCUMENTS]);
  38. $service = new Google\Service\Drive($client);
  39. // Authorize with Google
  40. if (isset($_GET['code'])) {
  41. $token = $client->fetchAccessTokenWithAuthCode($_GET['code'], $_SESSION['code_verifier']);
  42. $client->setAccessToken($token);
  43. // store in the session also
  44. $_SESSION['upload_token'] = $token;
  45. // redirect back to the example
  46. header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  47. }
  48. // set the access token as part of the client
  49. if (!empty($_SESSION['upload_token'])) {
  50. $client->setAccessToken($_SESSION['upload_token']);
  51. if ($client->isAccessTokenExpired()) {
  52. if ($client->getRefreshToken()) {
  53. $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
  54. $_SESSION['upload_token'] = $client->getAccessToken();
  55. } else {
  56. unset($_SESSION['upload_token']);
  57. }
  58. }
  59. } else {
  60. $_SESSION['code_verifier'] = $client->getOAuth2Service()->generateCodeVerifier();
  61. $authUrl = $client->createAuthUrl();
  62. }
  63. // Create Google Drive and Google Docs service
  64. $driveService = new Google\Service\Drive($client);
  65. $docsService = new Google\Service\Docs($client);
  66. // Following may be required to future proof, here you can specify the title of the document instead of the document id
  67. /*
  68. // Specify the title (name) of your Google Doc
  69. $docTitle = 'Your Google Doc Title';
  70. // List files in your Google Drive
  71. $files = $driveService->files->listFiles([
  72. 'q' => "name='$docTitle' and mimeType='application/vnd.google-apps.document'",
  73. ]);
  74. if (count($files->getFiles()) > 0) {
  75. // Get the first matching document
  76. $documentId = $files->getFiles()[0]->getId();
  77. } else {
  78. echo 'Google Doc not found.';
  79. die;
  80. }
  81. */
  82. // Replace with your Google Doc's Template file ID
  83. $documentId = '1RaPRLceht4bElaIqwFVWBaH92428PJciu9sCZ5lQimU';
  84. // Copy the template into a new file — replacements happen on the copy, not the template
  85. $driveFile = new Google\Service\Drive\DriveFile(['name' => $file_name]);
  86. $driveFile = $driveService->files->copy($documentId, $driveFile);
  87. // Replace template placeholders using the Docs batchUpdate API.
  88. // getBody()->getContent() returns an array of objects, not a string — str_replace cannot be used here.
  89. $replacements = [
  90. '<<DATE>>' => $date,
  91. '<<NAME>>' => $name,
  92. '<<FIRST_NAME>>' => $first_name,
  93. '<<COMPANY>>' => $company,
  94. '<<POSTAL_ADDRESS>>' => $postal_address,
  95. '<<DRG>>' => $drg,
  96. '<<BUILDING_DESCRTIPTION>>' => $building_description,
  97. '<<SITE_ADDRESS>>' => $site_address,
  98. '<<AGENT>>' => $agent,
  99. '<<AGENT_COMPANY>>' => $agent_company,
  100. ];
  101. $requests = [];
  102. foreach ($replacements as $placeholder => $value) {
  103. $requests[] = new Google\Service\Docs\Request([
  104. 'replaceAllText' => [
  105. 'containsText' => ['text' => $placeholder, 'matchCase' => true],
  106. 'replaceText' => $value,
  107. ],
  108. ]);
  109. }
  110. $docsService->documents->batchUpdate(
  111. $driveFile->getId(),
  112. new Google\Service\Docs\BatchUpdateDocumentRequest(['requests' => $requests])
  113. );
  114. // Find the Specified Folder to save documents in,
  115. // Specify the title (name) of your Google Doc
  116. $folderTitle = $drg . ' - ' . $site_address_street;
  117. // List files in your Google Drive
  118. $files = $driveService->files->listFiles([
  119. 'q' => "name='$folderTitle' and mimeType='application/vnd.google-apps.folder'",
  120. ]);
  121. if (count($files->getFiles()) > 0) {
  122. // Get the first matching document
  123. $folderId = $files->getFiles()[0]->getId();
  124. } else {
  125. echo 'Google folder not found.';
  126. // Create the folder if it doesnt exist,
  127. // folder needs to be created inside folder called [03]Projects 2023 which is "[0Y] Projects YYYY"
  128. // $parent_folder = '[0' . substr(date(y), -1) . '] Projects' . date(Y);
  129. }
  130. // Move the copied file to a specific folder
  131. $driveService->files->update($driveFile->getId(), null, [
  132. 'addParents' => '1ZwFTZ-YzFwYs1mN772WSET570E9ec-7O',
  133. 'removeParents' => $driveFile->getParents()[0],
  134. ]);
  135. // Create PDF
  136. $pdfFile = new Google_Service_Drive_DriveFile(['name' => $file_name . '.pdf']);
  137. $pdfFile = $driveService->files->copy($driveFile->getId(), $pdfFile, ['mimeType' => 'application/pdf']);
  138. echo 'Letter copied, variables replaced, and saved in the client folder.';