old_g_letter.php 5.8 KB

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