old_g_letter.php 5.7 KB

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