Advertisement
Guest User

Untitled

a guest
May 26th, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.86 KB | None | 0 0
  1. <?php
  2.  
  3. session_start();
  4.  
  5. //incluir la liberería de php de Google API
  6. require_once '../google-api-php-client-2.1.3/vendor/autoload.php';
  7.  
  8. //deifnir los permisos requeridos
  9. $scopes = array('https://www.googleapis.com/auth/drive');
  10.  
  11. //crear el objeto cliente
  12. $cliente = new Google_Client();
  13. $cliente->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/gestor/acceso.php');
  14. $cliente->setAuthConfig("client_secret.json");
  15. $cliente->addScope($scopes);
  16. $cliente->setAccessType('offline');
  17.  
  18. if (isset($_SESSION['token_de_acceso']) && $_SESSION['token_de_acceso']) {
  19.  
  20. $servidor = "localhost";
  21. $usuario = "root";
  22. $contraseña = "";
  23.  
  24. //crear conexión
  25. $con = new mysqli($servidor, $usuario, $contraseña);
  26.  
  27. //revisar la conexión
  28. if ($con->connect_error) {
  29. die("Fallo en la conexión: " . $con->connect_error);
  30. }
  31.  
  32. //crear base de datos si no existe
  33. $sql = "CREATE DATABASE IF NOT EXISTS gestor";
  34. if ($con->query($sql) === TRUE) {
  35. echo "Base de datos creada con éxito<br><br>";
  36. } else {
  37. echo "Fallo creando base de datos: " . $con->error . "<br><br>";
  38. }
  39.  
  40. mysqli_select_db($con,"gestor");
  41.  
  42. //crear tabla en la base de datos si no existe
  43. $sql = "CREATE TABLE IF NOT EXISTS token (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, token_de_acceso VARCHAR(2000))";
  44. if ($con->query($sql) === TRUE) {
  45. echo "Tabla creada con éxito<br><br>";
  46. } else {
  47. echo "Fallo creando la tabla: " . $con->error . "<br><br>";
  48. }
  49.  
  50. //guardar el token de acceso en forma de un JSON string
  51. $token_de_acceso = json_encode($_SESSION['token_de_acceso']);
  52. $sql = "INSERT INTO token (token_de_acceso) VALUES ('$token_de_acceso')";
  53. if ($con->query($sql) === TRUE) {
  54. echo "Token guardado con éxito<br><br>";
  55. } else {
  56. echo "Error guardado token: " . $sql . "<br>" . $con->error . "<br><br>";
  57. }
  58.  
  59. $con->close();
  60. header("Location: index.php");
  61.  
  62. } else {
  63.  
  64. if (!isset($_GET['code'])) {
  65.  
  66. $url_de_auth = $cliente->createAuthUrl();
  67. header('Location: ' . filter_var($url_de_auth, FILTER_SANITIZE_URL));
  68.  
  69. } else {
  70.  
  71. $cliente->authenticate($_GET['code']);
  72. $_SESSION['token_de_acceso'] = $cliente->getAccessToken();
  73. $uri_de_redireccion = 'http://' . $_SERVER['HTTP_HOST'] . '/gestor/acceso.php';
  74. header('Location: ' . filter_var($uri_de_redireccion, FILTER_SANITIZE_URL));
  75.  
  76. }
  77.  
  78. }
  79.  
  80. <?php session_start();
  81.  
  82. function inicarCliente(){
  83.  
  84. //incluir la liberería de php de Google API
  85. require_once "../google-api-php-client-2.1.3/vendor/autoload.php";
  86.  
  87. //definir los permisos necesarios
  88. $scopes = array("https://www.googleapis.com/auth/drive");
  89.  
  90. //crear el objeto de cliente de Google
  91. $cliente = new Google_Client();
  92. $cliente->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/gestor/acceso.php');
  93. $cliente->setAuthConfig("client_secret.json");
  94. $cliente->addScope($scopes);
  95. $cliente->setAccessType('offline');
  96.  
  97. return $cliente;
  98.  
  99. }
  100.  
  101. function refrescarToken($cliente, $tokenDeAccesso){
  102.  
  103. $tokenExpirado = $cliente->isAccessTokenExpired();
  104. if($tokenExpirado){
  105. $cliente->refreshToken($tokenDeAccesso["refresh_token"]);
  106. }
  107.  
  108. $_SESSION["token_de_acceso"] = $cliente->getAccessToken();
  109. }
  110.  
  111. ?>
  112.  
  113. <?php
  114.  
  115. include "autenticar.php";
  116.  
  117. $idDeDoc = $_POST["idDeDoc"];
  118. $tituloDeDoc = $_POST["tituloDeDoc"];
  119. $tipoDeDoc = $_POST["tipoDeDoc"];
  120.  
  121. function descargarArchivo($idDeDoc, $tipoDeDoc, $tituloDeDoc){
  122.  
  123. $tokenDeAccesso = $_SESSION["token_de_acceso"];
  124.  
  125. $cliente = inicarCliente();
  126. refrescarToken($cliente, $tokenDeAccesso);
  127.  
  128. $tokenDeAccesso = $_SESSION['token_de_acceso'];
  129.  
  130. $cliente->setAccessToken($tokenDeAccesso);
  131. $servicio = new Google_Service_Drive($cliente);
  132.  
  133. if($tipoDeDoc == "application/vnd.google-apps.document") {
  134.  
  135. $ext = ".docx";
  136. $format = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
  137. $googleDoc = true;
  138.  
  139. } else if($tipoDeDoc == "application/vnd.google-apps.spreadsheet"){
  140.  
  141. $ext = ".xlsx";
  142. $format = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  143. $googleDoc = true;
  144.  
  145. } else if($tipoDeDoc == "application/vnd.google-apps.presentation"){
  146.  
  147. $ext = ".pptx";
  148. $format = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
  149. $googleDoc = true;
  150.  
  151. } else {
  152.  
  153. $ext = ".".explode("/", $tipoDeDoc)[1];
  154. $googleDoc = false;
  155.  
  156. }
  157.  
  158. if($googleDoc){
  159. $archivo = $servicio->files->export($idDeDoc, $format, array('alt' => 'media'));
  160. } else {
  161. $archivo = $servicio->files->get($idDeDoc, array('alt' => 'media'));
  162. }
  163.  
  164. $exportacion = fopen($tituloDeDoc.$ext, "w+");
  165. fwrite($exportacion, $archivo->getBody());
  166. fclose($exportacion);
  167.  
  168. return dirname($tituloDeDoc.$ext)."/".$tituloDeDoc.$ext;
  169. }
  170.  
  171. echo descargarArchivo($idDeDoc, $tipoDeDoc, $tituloDeDoc);
  172.  
  173. ?>
  174.  
  175. <!DOCTYPE html>
  176. <html>
  177. <head>
  178. <title>Gestor Drive</title>
  179. <style type="text/css">
  180.  
  181. body{
  182. text-align: center;
  183. }
  184.  
  185. .listaArchivos {
  186. margin: 15px 0px;
  187. width: 320px;
  188. height: 25px;
  189. }
  190.  
  191. #descargar{
  192. margin: 7px 0px;
  193. }
  194.  
  195. #editarArchvio{
  196. width: 950px;
  197. height: 630px;
  198. }
  199.  
  200. #circuloEspera,
  201. #circuloEsperaDos {
  202. display: none;
  203. height: 36px;
  204. width: 36px;
  205. margin: 0 auto;
  206. }
  207.  
  208. #subirArchivo {
  209. margin: 35px 0px;
  210. }
  211.  
  212. #popup {
  213. position: absolute;
  214. width: 100%;
  215. height: 100%;
  216. background-color: rgba(0,0,0,0.5);
  217. top: 0;
  218. left: 0;
  219. display: none;
  220. }
  221.  
  222. #contenido-popup {
  223. background-color: white;
  224. width: 450px;
  225. height: 240px;
  226. margin: 0 auto;
  227. transform: translateY(100%);
  228. position: relative;
  229. }
  230.  
  231. .btn {
  232. padding: 6px;
  233. border-radius: 3px;
  234. background-color: whitesmoke;
  235. box-shadow: 0px 0px 1px 1px gray;
  236. }
  237.  
  238. #nombreDeArchivo{
  239. height: 20px;
  240. }
  241.  
  242. </style>
  243. </head>
  244. <body>
  245.  
  246. <h1>Gestor de Archivos Google Drive</h1>
  247.  
  248. <div class="menu">
  249.  
  250. <select class="listaArchivos" id="listaDeArchivos" disabled>
  251. <option>Seleccionar archivo...</option>
  252. </select>
  253.  
  254. <br>
  255.  
  256. <button id="descargar" disabled>Descargar</button>
  257. <img id="circuloEspera" src="https://s5.postimg.cc/r3dog8vg7/loading.gif">
  258.  
  259. </div>
  260.  
  261. <div class="marco">
  262.  
  263. <iframe src="" id="editarArchvio" frameborder="1"></iframe>
  264.  
  265. </div>
  266.  
  267. <button id="subirArchivo">Subir Archivo</button>
  268.  
  269. <div id="popup">
  270. <div id="contenido-popup">
  271. <br>
  272. <h3>SUBIR NUEVO ARCHIVO</h3>
  273. <br>
  274. <label for="nuevoArchivoInput" class="btn">Seleccionar Archivo</label><br>
  275. <input type="file" name="archivo" id="nuevoArchivoInput" style="visibility:hidden;"><br>
  276. <div id="nombreDeArchivo"></div><img id="circuloEsperaDos" src="https://s5.postimg.cc/r3dog8vg7/loading.gif"><br><br>
  277. <button id="nuevoArchivo">Subir Nuevo Archivo</button>
  278. </div>
  279. </div>
  280.  
  281. <script type="text/javascript" src="scripts.js"></script>
  282. </body>
  283. </html>
  284.  
  285. <?php
  286.  
  287. session_start();
  288.  
  289. $servidor = "localhost";
  290. $usuario = "root";
  291. $contraseña = "";
  292. $baseDeDatos = "gestor";
  293.  
  294. //crear conexión
  295. $con = new mysqli($servidor, $usuario, $contraseña, $baseDeDatos);
  296.  
  297. //revisar la conexión
  298. if ($con->connect_error) {
  299. if($con->connect_error == "Unknown database 'gestor'") {
  300. header("Location: acceso.php");
  301. }
  302. die("Fallo en la conexión: " . $con->connect_error);
  303. }
  304.  
  305. //obtener token de accesso
  306. $sql = "SELECT * FROM token";
  307. $result = $con->query($sql);
  308.  
  309. if ($result->num_rows > 0) {
  310. // obtener datos de cada fila
  311. while($row = $result->fetch_assoc()) {
  312. $token = $row["token_de_acceso"];
  313. break;
  314. }
  315. } else {
  316. echo "0 resultados";
  317. header("Location: acceso.php");
  318. }
  319.  
  320. //cerrar conexión
  321. $con->close();
  322.  
  323. //guardar el token de acceso en la sesión y redirigir a gestor.html
  324. $_SESSION["token_de_acceso"] = json_decode($token, true);
  325. header("Location: gestor.html");
  326.  
  327. ?>
  328.  
  329. <?php
  330.  
  331. include "autenticar.php";
  332.  
  333. function obtenerListaDeArchivos(){
  334.  
  335. $tokenDeAccesso = $_SESSION["token_de_acceso"];
  336.  
  337. $cliente = inicarCliente();
  338. refrescarToken($cliente, $tokenDeAccesso);
  339.  
  340. $tokenDeAccesso = $_SESSION['token_de_acceso'];
  341.  
  342. $opcionesDeHtml = "<option value=''>Seleccionar archivo...</option>";
  343.  
  344. $cliente->setAccessToken($tokenDeAccesso);
  345. $servicio = new Google_Service_Drive($cliente);
  346.  
  347. $tokenDePagina = null;
  348. $paramsOpcionales = array(
  349. "pageSize" => 100,
  350. "pageToken" => $tokenDePagina,
  351. "q" => "'Id de folder aqui' in parents and trashed != true" // normalmente es algo como 1HeqmJX-1Lsy89CXljmUY-BjubbjfkpsSm
  352. );
  353.  
  354. try {
  355.  
  356. do {
  357.  
  358. $optParams["pageToken"] = $tokenDePagina;
  359. $archivos = $servicio->files->listFiles($paramsOpcionales);
  360. $tokenDePagina = $archivos->nextPageToken;
  361.  
  362. foreach ($archivos as $archivo ) {
  363. $opcionesDeHtml .= "<option value='".$archivo->id.",".$archivo->mimeType."'>".$archivo->name."</option>";
  364. }
  365.  
  366. } while($tokenDePagina);
  367.  
  368. } catch(Exception $e) {
  369.  
  370. $msjDeError = $e->getMessage();
  371.  
  372. if(strpos($msjDeError, "Internal Error") !== false) {
  373. sleep(2);
  374. $archivos = $servicio->files->listFiles($paramsOpcionales);
  375. $tokenDePagina = $driveFiles->nextPageToken;
  376. foreach ($drivefiles as $file ) {
  377. $opcionesDeHtml .= "<option value='".$archivo->id."'>".$archivo->name."</option>";
  378. }
  379. } else {
  380. print $msjDeError;
  381. }
  382. }
  383.  
  384. return $opcionesDeHtml;
  385.  
  386. }
  387.  
  388. echo obtenerListaDeArchivos();
  389.  
  390. ?>
  391.  
  392. function listarArchivos(){
  393.  
  394. var solicitud = new XMLHttpRequest();
  395. solicitud.onreadystatechange = function() {
  396. if (this.readyState == 4 && this.status == 200) {
  397. document.getElementById("listaDeArchivos").innerHTML = this.responseText;
  398. document.getElementById("listaDeArchivos").disabled = false;
  399. }
  400. };
  401. solicitud.open("GET", "listar.php", true);
  402. solicitud.send();
  403.  
  404. }
  405.  
  406. function editarArchivo(){
  407.  
  408. var elDoc = document.getElementById("listaDeArchivos").value;
  409. var idDeDoc = elDoc.split(",")[0];
  410. var tipoDeDoc = elDoc.split(",")[1];
  411. if(idDeDoc){
  412. document.getElementById("descargar").disabled = false;
  413. } else{
  414. document.getElementById("descargar").disabled = true;
  415. }
  416.  
  417. var altura = (window.innerHeight / 3);
  418. altura = altura * 2;
  419.  
  420. var url;
  421. if(tipoDeDoc === "application/vnd.google-apps.document"){
  422.  
  423. url = "https://docs.google.com/document/d/"+idDeDoc+"?rm=demo";
  424.  
  425. } else if(tipoDeDoc === "application/vnd.google-apps.spreadsheet"){
  426.  
  427. url = "https://docs.google.com/spreadsheets/d/"+idDeDoc+"?rm=demo";
  428.  
  429. } else if(tipoDeDoc === "application/vnd.google-apps.presentation"){
  430.  
  431. url = "https://docs.google.com/presentation/d/"+idDeDoc+"?rm=demo";
  432.  
  433. } else {
  434.  
  435. url = "https://drive.google.com/file/d/"+idDeDoc+"/preview";
  436.  
  437. }
  438. document.getElementById("editarArchvio").setAttribute("src", url);
  439. }
  440.  
  441. function descargarArchivo(){
  442.  
  443. document.getElementById("descargar").style.display = "none";
  444. document.getElementById("circuloEspera").style.display = "initial";
  445.  
  446. var elDoc = document.getElementById("listaDeArchivos").value;
  447. var idDeDoc = elDoc.split(",")[0];
  448. var tipoDeDoc = elDoc.split(",")[1];
  449. var tituloDeDoc = document.getElementById("listaDeArchivos").options[document.getElementById("listaDeArchivos").selectedIndex].text;
  450.  
  451. var solicitud = new XMLHttpRequest();
  452. solicitud.onreadystatechange = function() {
  453. if (this.readyState == 4 && this.status == 200) {
  454.  
  455. console.log(this.responseText);
  456. document.getElementById("descargar").style.display = "initial";
  457. document.getElementById("circuloEspera").style.display = "none";
  458.  
  459. var a = document.createElement('a');
  460. a.href = this.responseText;
  461. a.download = (this.responseText).substr(2);
  462. document.body.appendChild(a);
  463. a.click();
  464. document.body.removeChild(a);
  465. }
  466. };
  467. solicitud.open("POST", "descargar.php", true);
  468. solicitud.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  469. solicitud.send("idDeDoc="+idDeDoc+"&tipoDeDoc="+tipoDeDoc+"&tituloDeDoc="+tituloDeDoc);
  470.  
  471. }
  472.  
  473. function subirArchivo(){
  474.  
  475. document.getElementById("nombreDeArchivo").style.display = "none";
  476. document.getElementById("circuloEsperaDos").style.display = "block";
  477.  
  478. var elDoc = document.getElementById("nuevoArchivoInput");
  479. var path = elDoc.value.split("\");
  480. var tituloDeDoc = path[path.length -1];
  481.  
  482. var formData = new FormData();
  483. formData.append("archivoParaSubir", elDoc.files[0]);
  484. formData.append("tituloDeDoc", tituloDeDoc);
  485.  
  486. var solicitud = new XMLHttpRequest();
  487. solicitud.onreadystatechange = function() {
  488. if (this.readyState == 4 && this.status == 200) {
  489.  
  490. console.log(this.responseText);
  491. document.getElementById("nombreDeArchivo").style.display = "block";
  492. document.getElementById("nombreDeArchivo").innerHTML = "Archvio subido";
  493. document.getElementById("circuloEsperaDos").style.display = "none";
  494. listarArchivos();
  495. }
  496. };
  497. solicitud.open("POST", "subir.php", true);
  498. solicitud.send(formData);
  499. }
  500.  
  501. document.addEventListener("DOMContentLoaded", function(event) {
  502.  
  503. listarArchivos();
  504.  
  505. document.getElementById("listaDeArchivos").addEventListener("change", function(){
  506. editarArchivo();
  507. });
  508.  
  509. document.getElementById("descargar").addEventListener("click", function(){
  510. descargarArchivo();
  511. });
  512.  
  513. document.getElementById("subirArchivo").addEventListener("click", function(){
  514. document.getElementById("popup").style.display = "block";
  515. });
  516.  
  517. document.getElementById("popup").addEventListener("click", function(e){
  518. if(e.target === document.getElementById("popup")){
  519. document.getElementById("popup").style.display = "none";
  520. }
  521. });
  522.  
  523. document.getElementById("nuevoArchivoInput").addEventListener("change", function(){
  524. var path = (this.value).split("\");
  525. document.getElementById("nombreDeArchivo").innerHTML = path[path.length - 1];
  526. });
  527.  
  528. document.getElementById("nuevoArchivo").addEventListener("click", function(){
  529. subirArchivo();
  530. });
  531.  
  532. });
  533.  
  534. <?php
  535.  
  536. include "autenticar.php";
  537.  
  538. $archivoParaSubir = $_FILES["archivoParaSubir"];
  539. $tituloDeDoc = $_POST["tituloDeDoc"];
  540. $tituloDeDocPartes = explode(".", $tituloDeDoc);
  541. array_pop($tituloDeDocPartes);
  542. $tituloDeDoc = implode(".", $tituloDeDocPartes);
  543.  
  544.  
  545. function subirArchivo($archivoParaSubir, $tituloDeDoc){
  546.  
  547. $tokenDeAccesso = $_SESSION["token_de_acceso"];
  548.  
  549. $cliente = inicarCliente();
  550. refrescarToken($cliente, $tokenDeAccesso);
  551.  
  552. $tokenDeAccesso = $_SESSION['token_de_acceso'];
  553.  
  554. $cliente->setAccessToken($tokenDeAccesso);
  555. $servicio = new Google_Service_Drive($cliente);
  556.  
  557. $info = new finfo(FILEINFO_MIME);
  558. $tipoDeDoc = $info->file($archivoParaSubir["tmp_name"]);
  559. $mimeType = explode(";", $tipoDeDoc)[0];
  560.  
  561. $metaDatos = new Google_Service_Drive_DriveFile(array('name' => $tituloDeDoc, "parents" => ["1HeqmBX-1Lsym9CXljmUY-BjufvfkpsSm"]));
  562. switch ($mimeType) {
  563.  
  564. case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
  565. case "application/vnd.openxmlformats-officedocument.wordprocessingml.template":
  566. case "application/vnd.ms-word.document.macroEnabled.12":
  567. case "application/vnd.ms-word.template.macroEnabled.12":
  568. case "application/msword":
  569. $metaDatos->setMimeType("application/vnd.google-apps.document");
  570. break;
  571.  
  572. case "application/vnd.openxmlformats-officedocument.spreadsheetml.template":
  573. case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
  574. case "application/vnd.ms-excel.sheet.binary.macroEnabled.12":
  575. case "application/vnd.ms-excel.template.macroEnabled.12":
  576. case "application/vnd.ms-excel.sheet.macroEnabled.12":
  577. case "application/vnd.ms-excel.addin.macroEnabled.12":
  578. case "application/vnd.ms-excel":
  579. $metaDatos->setMimeType("application/vnd.google-apps.spreadsheet");
  580. break;
  581.  
  582. case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
  583. case "application/vnd.openxmlformats-officedocument.presentationml.slideshow":
  584. case "application/vnd.openxmlformats-officedocument.presentationml.template":
  585. case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
  586. case "application/vnd.ms-powerpoint.slideshow.macroEnabled.12":
  587. case "application/vnd.ms-powerpoint.template.macroEnabled.12":
  588. case "application/vnd.ms-powerpoint.addin.macroEnabled.12":
  589. case "application/vnd.ms-powerpoint":
  590. $metaDatos->setMimeType("application/vnd.google-apps.presentation");
  591. break;
  592.  
  593. default:
  594. break;
  595. }
  596.  
  597. $contenido = file_get_contents($archivoParaSubir["tmp_name"]);
  598. $archivo = $servicio->files->create($metaDatos, array(
  599. "data" => $contenido,
  600. "mimeType" => $mimeType,
  601. "uploadType" => "multipart",
  602. "fields" => "id")
  603. );
  604.  
  605. $permiso = new Google_Service_Drive_Permission(array(
  606. 'type' => 'anyone',
  607. 'role' => 'writer',
  608. ));
  609. $compartir = $servicio->permissions->create(
  610. $archivo->id, $permiso, array('fields' => 'id'));
  611.  
  612. return $archivo->id;
  613. }
  614.  
  615. echo subirArchivo($archivoParaSubir, $tituloDeDoc);
  616.  
  617. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement