Files
crm-ms1/t.php
2026-05-27 11:48:31 -04:00

162 lines
5.6 KiB
PHP
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require __DIR__ . '/vendor/autoload.php';
session_start();
function getClient()
{
$client = new Google_Client();
$client->setAuthConfig('credentials.json');
$client->addScope([
Google_Service_Drive::DRIVE,
'https://www.googleapis.com/auth/documents'
]);
$client->setRedirectUri('https://ms1crmdev.progiweb.net/t.php');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Authentification OAuth
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
if (isset($token['error'])) {
echo "Erreur Google: " . htmlspecialchars($token['error_description'] ?? $token['error']);
exit;
}
$_SESSION['access_token'] = $token;
header('Location: ' . filter_var($client->getRedirectUri(), FILTER_SANITIZE_URL));
exit;
}
if (isset($_SESSION['access_token'])
&& is_array($_SESSION['access_token'])
&& isset($_SESSION['access_token']['access_token'])
) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
exit;
}
if ($client->isAccessTokenExpired()) {
unset($_SESSION['access_token']);
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
exit;
}
return $client;
}
// ========== TEST ==========
// 1. La première fois, laisse $docIdTest = ""; pour créer le doc et afficher son ID
// 2. Ensuite, copie cet ID ici, dans $docIdTest, pour mettre à jour ce doc existant uniquement
$docIdTest = "106klQ1hXpQkq5VJwmWFQ74kvx6bg1KX1XZtS9Dv3s34"; // <-- Colle ici l'ID après la première création pour la mise à jour
if (isset($_POST['create_shortcut'])) {
$client = getClient();
$driveService = new Google_Service_Drive($client);
$folderId = '1BJPxQ2XPWqBRYxINgI-9TKJ_iPz7Dltb';
$titre = "Raccourci infos course";
$description= "zz2Consultez les résultats de lévénement. Pour toute question, contactez notre équipe.";
$lienTexte = "Lien vers les résultats du 24h Tremblant";
$lienURL = "https://ms1timing.com/index.php?code=results&id=631";
$contactTel = "Téléphone : 1-855-999-5555";
$texteDoc = $titre . "\n\n" . $description . "\n\n" . $lienTexte . "\n\n" . $contactTel;
$titreLen = strlen($titre);
$descLen = strlen($description);
$lienLen = strlen($lienTexte);
$lienStart = $titreLen + 2 + $descLen + 2;
$lienEnd = $lienStart + $lienLen;
$docsService = new Google_Service_Docs($client);
if (empty($docIdTest)) {
// Création du doc la première fois
$fileMetadata = new Google_Service_Drive_DriveFile([
'name' => $titre,
'mimeType' => 'application/vnd.google-apps.document',
'parents' => [$folderId],
]);
$file = $driveService->files->create($fileMetadata, [
'supportsAllDrives' => true,
]);
$docId = $file->id;
// Affiche l'ID à stocker pour la prochaine fois
echo "DOCUMENT CRÉÉ :<br>";
echo "Colle cet ID dans \$docIdTest pour les prochaines mises à jour :<br>";
echo "<b>" . htmlspecialchars($docId) . "</b><br><br>";
// Continue la création et remplissage du doc
} else {
$docId = $docIdTest;
}
// Insère ou remplace le contenu
try {
// Tente d'effacer tout le contenu existant (si le doc existait déjà)
$doc = $docsService->documents->get($docId);
$contentLength = 0;
if (isset($doc->body->content) && is_array($doc->body->content)) {
foreach ($doc->body->content as $el) {
if (isset($el->endIndex)) {
$contentLength = max($contentLength, $el->endIndex);
}
}
}
$requests = [];
// On efface le contenu SEULEMENT s'il y a quelque chose à effacer (>2)
if ($contentLength > 2) {
$requests[] = [
'deleteContentRange' => [
'range' => [
'startIndex' => 1,
'endIndex' => $contentLength - 1
]
]
];
}
$requests[] = [
'insertText' => [
'location' => ['index' => 1],
'text' => $texteDoc
]
];
$requests[] = [
'updateTextStyle' => [
'range' => [
'startIndex' => $lienStart,
'endIndex' => $lienEnd
],
'textStyle' => [
'link' => ['url' => $lienURL]
],
'fields' => 'link'
]
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest([
'requests' => $requests
]);
$docsService->documents->batchUpdate($docId, $batchUpdateRequest);
// Affiche le lien du Google Doc modifié ou créé
$docUrl = 'https://docs.google.com/document/d/' . $docId . '/edit';
echo "Raccourci Google Doc créé ou mis à jour!<br>";
echo "<a href='$docUrl' target='_blank'>Ouvrir le raccourci dans Google Drive</a>";
exit;
} catch (Exception $e) {
echo "Erreur lors de la mise à jour du document : " . htmlspecialchars($e->getMessage());
exit;
}
}
?>
<!-- HTML du bouton -->
<form method="POST">
<button type="submit" name="create_shortcut">Créer le raccourci Google Drive</button>
</form>