245 lines
8.8 KiB
PHP
245 lines
8.8 KiB
PHP
<?php
|
||
require_once realpath(__DIR__ . '/../../vendor/autoload.php');
|
||
|
||
use Google\Client as Google_Client;
|
||
use Google\Service\Drive as Google_Service_Drive;
|
||
use Google\Service\Docs as Google_Service_Docs;
|
||
use Google\Service\Docs\Request as Google_Service_Docs_Request;
|
||
use Google\Service\Docs\BatchUpdateDocumentRequest as Google_Service_Docs_BatchUpdateDocumentRequest;
|
||
use Google\Service\Drive\DriveFile as Google_Service_Drive_DriveFile;
|
||
|
||
class GoogleDocs_model_avant extends CI_Model
|
||
{
|
||
|
||
public function __construct()
|
||
{
|
||
parent::__construct();
|
||
}
|
||
|
||
|
||
private $user_id;
|
||
|
||
public function set_user_id($id)
|
||
{
|
||
$this->user_id = $id;
|
||
}
|
||
public function getClient() {
|
||
require_once APPPATH . '../vendor/autoload.php';
|
||
|
||
$client = new \Google_Client();
|
||
$client->setApplicationName('Google Drive API - MS1');
|
||
$client->setScopes([
|
||
Google_Service_Drive::DRIVE_FILE,
|
||
Google_Service_Drive::DRIVE_METADATA_READONLY
|
||
]);
|
||
$client->setAuthConfig(APPPATH . 'credentials/credentials.json');
|
||
$client->setAccessType('offline');
|
||
$client->setPrompt('select_account consent');
|
||
$client->setRedirectUri(base_url('index.php/GoogleDrive/test_google'));
|
||
|
||
$tokenDir = APPPATH . 'credentials/tokens/';
|
||
if (!is_dir($tokenDir)) {
|
||
mkdir($tokenDir, 0700, true);
|
||
}
|
||
|
||
|
||
$user_id =$this->user_id; // à adapter selon ton système d’authentification
|
||
$tokenPath = $tokenDir . 'token_' . $user_id . '.json';
|
||
|
||
// 1. Si token.json existe, on le charge
|
||
if (file_exists($tokenPath)) {
|
||
$accessToken = json_decode(file_get_contents($tokenPath), true);
|
||
$client->setAccessToken($accessToken);
|
||
|
||
// 2. Si expiré, on tente de le refresh automatiquement
|
||
if ($client->isAccessTokenExpired()) {
|
||
if ($client->getRefreshToken()) {
|
||
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
|
||
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
|
||
} else {
|
||
unlink($tokenPath);
|
||
redirect($client->createAuthUrl());
|
||
exit;
|
||
}
|
||
}
|
||
|
||
} else {
|
||
// 3. Pas de token -> redirection OAuth
|
||
if (isset($_GET['code'])) {
|
||
$accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
|
||
|
||
if (!isset($accessToken['error'])) {
|
||
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
|
||
} else {
|
||
echo 'Erreur OAuth : ' . print_r($accessToken, true);
|
||
exit;
|
||
}
|
||
} else {
|
||
redirect($client->createAuthUrl());
|
||
exit;
|
||
}
|
||
}
|
||
|
||
return $client;
|
||
}
|
||
|
||
public function creer_document($proj_id)
|
||
{
|
||
$this->load->model('Projets_model');
|
||
$mem_proj = $this->Projets_model->mod_getRecord($proj_id);
|
||
|
||
if($mem_proj->proj_google_rep_id==""){
|
||
return;
|
||
}
|
||
$this->load->model('Clients_model');
|
||
$contacts2 = $this->Clients_model->mod_getRecords_contacts( $mem_proj->proj_client_id);
|
||
|
||
|
||
|
||
$mem_link = base_url() . "index.php/projets/form/" . $mem_proj->proj_id;
|
||
$this->set_user_id($this->session->userdata('id'));
|
||
$client = $this->getClient();
|
||
|
||
if (!($client instanceof Google_Client)) {
|
||
echo "Erreur : Le client Google n'est pas valide ou vous n'êtes plus connecté.";
|
||
return;
|
||
}
|
||
|
||
try {
|
||
$driveService = new Google_Service_Drive($client);
|
||
$docsService = new Google_Service_Docs($client);
|
||
|
||
$nomFichier = 'Infos Course '.$this->session->username;
|
||
$parentId = $mem_proj->proj_google_rep_id;
|
||
$dateHeure = date('Y-m-d H:i');
|
||
|
||
// Récupère le driveId du répertoire (Drive partagé)
|
||
$folderInfo = $driveService->files->get($parentId, [
|
||
'fields' => 'driveId',
|
||
'supportsAllDrives' => true
|
||
]);
|
||
$driveId = $folderInfo->getDriveId();
|
||
|
||
// Données à insérer
|
||
$data = [
|
||
['Nom du projet', $mem_proj->proj_nom],
|
||
['Date', $mem_proj->proj_date_debut],
|
||
['Client', $mem_proj->compagnie],
|
||
['Notes', $mem_proj->proj_notes],
|
||
['Lien', "<a href='{$mem_link}'>$mem_link</a>"],
|
||
['Représentant', $mem_proj->rep_prenom],
|
||
['Date de création', $dateHeure],
|
||
];
|
||
|
||
// Ajout dynamique des autres contacts
|
||
$i = 1;
|
||
foreach ($contacts2 as $c) {
|
||
$nomComplet = trim($c['con_prenom'] . ' ' . $c['con_nom']);
|
||
$email = $c['con_courriel'] ?? '';
|
||
$tel = $c['con_telephone2'] ?? '';
|
||
$rol_nom = $c['rol_nom'] ?? '';
|
||
// Tu peux aussi appeler jira_get_tickets_by_email($email) ici si tu veux inclure les tickets
|
||
|
||
$ligne = $nomComplet;
|
||
if ($email) $ligne .= '' . $email;
|
||
if ($tel) $ligne .= ' - ' . $tel;
|
||
if ($rol_nom) $ligne .= ' - ' . $rol_nom;
|
||
$data[] = [ $nomComplet, $ligne];
|
||
$i++;
|
||
$tickets = jira_get_tickets_by_email($email);
|
||
if (!empty($tickets['ouverts'])):
|
||
$ligne='';
|
||
foreach ($tickets['ouverts'] as $t):
|
||
|
||
$ligne .= '<li><a href="'.$t['url'].'" target="_blank">'.$t['key'].'</a>
|
||
— '. htmlspecialchars($t['summary']) .'('. $t['status'].')
|
||
</li>';
|
||
endforeach;
|
||
|
||
|
||
$data[] = ['Tickets ouvert ' , $ligne];
|
||
|
||
|
||
endif;
|
||
}
|
||
|
||
|
||
// Recherche d’un document existant dans le dossier
|
||
$response = $driveService->files->listFiles([
|
||
'q' => sprintf(
|
||
"name = '%s' and mimeType='application/vnd.google-apps.document' and '%s' in parents and trashed = false",
|
||
addslashes($nomFichier),
|
||
$parentId
|
||
),
|
||
'spaces' => 'drive',
|
||
'driveId' => $driveId,
|
||
'corpora' => 'drive',
|
||
'includeItemsFromAllDrives' => true,
|
||
'supportsAllDrives' => true,
|
||
'fields' => 'files(id)'
|
||
]);
|
||
|
||
// Supprime l'ancien fichier s'il existe
|
||
if (count($response->getFiles()) > 0) {
|
||
$existingFileId = $response->getFiles()[0]->getId();
|
||
$driveService->files->delete($existingFileId, ['supportsAllDrives' => true]);
|
||
}
|
||
|
||
// Contenu HTML à insérer
|
||
$html = '<html><body>';
|
||
$html .= '<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">';
|
||
foreach ($data as $row) {
|
||
$html .= "<tr><td style='width: 30%;'><strong>{$row[0]}</strong></td><td>{$row[1]}</td></tr>";
|
||
}
|
||
$html .= '</table>';
|
||
$html .= '</body></html>';
|
||
|
||
// Fichier temporaire HTML
|
||
$tempFile = tempnam(sys_get_temp_dir(), 'google_doc_html_') . '.html';
|
||
file_put_contents($tempFile, $html);
|
||
|
||
// Création du fichier dans le Drive partagé
|
||
$fileMetadata = new Google_Service_Drive_DriveFile([
|
||
'name' => $nomFichier,
|
||
'mimeType' => 'application/vnd.google-apps.document',
|
||
'parents' => [$parentId]
|
||
]);
|
||
|
||
$content = file_get_contents($tempFile);
|
||
$file = $driveService->files->create($fileMetadata, [
|
||
'data' => $content,
|
||
'mimeType' => 'text/html',
|
||
'uploadType' => 'multipart',
|
||
'fields' => 'id',
|
||
'supportsAllDrives' => true
|
||
]);
|
||
|
||
unlink($tempFile);
|
||
|
||
echo "Document mis à jour avec succès. ID : " . $file->id;
|
||
|
||
} catch (Exception $e) {
|
||
echo "Erreur : " . $e->getMessage();
|
||
//exit;
|
||
}
|
||
}
|
||
|
||
private function get_local_drive_path($folderId, Google_Service_Drive $driveService, $driveLetter = 'G', $basePath = 'My Drive\\Projets') {
|
||
try {
|
||
$folder = $driveService->files->get($folderId, [
|
||
'fields' => 'name',
|
||
'supportsAllDrives' => true // 👈 ici aussi
|
||
]);
|
||
$folderName = $folder->getName();
|
||
|
||
return $driveLetter . ':\\' . $basePath . '\\' . $folderName;
|
||
|
||
} catch (Exception $e) {
|
||
log_message('error', 'Erreur get_local_drive_path(): ' . $e->getMessage());
|
||
return null;
|
||
}
|
||
}
|
||
|
||
|
||
}
|