Browse Source

Organizando el directorio de MILFS para poderlo convertir en un submodulo

master
kleper 1 year ago
parent
commit
d2945ffc5a
100 changed files with 16920 additions and 103 deletions
  1. +0
    -103
      API.md
  2. +510
    -0
      addon/brigada/.goutputstream-WQKM8X
  3. +91
    -0
      addon/brigada/funciones/funciones.php
  4. +36
    -0
      addon/brigada/funciones/twitter/autoload.php
  5. BIN
      addon/brigada/funciones/twitter/c.png
  6. +6
    -0
      addon/brigada/funciones/twitter/config.php
  7. +31
    -0
      addon/brigada/funciones/twitter/datos.php
  8. +65
    -0
      addon/brigada/funciones/twitter/hola.php
  9. +64
    -0
      addon/brigada/funciones/twitter/src/Config.php
  10. +36
    -0
      addon/brigada/funciones/twitter/src/Consumer.php
  11. +39
    -0
      addon/brigada/funciones/twitter/src/HmacSha1.php
  12. +254
    -0
      addon/brigada/funciones/twitter/src/Request.php
  13. +107
    -0
      addon/brigada/funciones/twitter/src/Response.php
  14. +66
    -0
      addon/brigada/funciones/twitter/src/SignatureMethod.php
  15. +38
    -0
      addon/brigada/funciones/twitter/src/Token.php
  16. +448
    -0
      addon/brigada/funciones/twitter/src/TwitterOAuth.php
  17. +10
    -0
      addon/brigada/funciones/twitter/src/TwitterOAuthException.php
  18. +115
    -0
      addon/brigada/funciones/twitter/src/Util.php
  19. +26
    -0
      addon/brigada/funciones/twitter/src/Util/JsonDecoder.php
  20. +3952
    -0
      addon/brigada/funciones/twitter/src/cacert.pem
  21. +31
    -0
      addon/brigada/funciones/twitter/tuitear.php
  22. +177
    -0
      addon/brigada/grabar.php
  23. BIN
      addon/brigada/images/logos/150.png
  24. BIN
      addon/brigada/images/logos/250.png
  25. BIN
      addon/brigada/images/logos/c.png
  26. +0
    -0
      addon/brigada/index.html
  27. +13
    -0
      addon/brigada/js/demo.js
  28. +143
    -0
      addon/brigada/js/load-image-meta.js
  29. +166
    -0
      addon/brigada/js/load-image-orientation.js
  30. +1
    -0
      addon/brigada/js/load-image.all.min.js
  31. +305
    -0
      addon/brigada/js/load-image.js
  32. +363
    -0
      addon/brigada/logis.php
  33. +207
    -0
      addon/brigada/logis.php.php
  34. +207
    -0
      addon/brigada/logis_completo.php
  35. +436
    -0
      addon/brigadistas/brigadistas.php
  36. +84
    -0
      addon/brigadistas/funciones/funciones.php
  37. BIN
      addon/brigadistas/images/logos/a.png
  38. BIN
      addon/brigadistas/images/logos/b.png
  39. BIN
      addon/brigadistas/images/logos/c.png
  40. +0
    -0
      addon/brigadistas/index.php
  41. +0
    -0
      addon/dummy/config.php
  42. +0
    -0
      addon/dummy/index.php
  43. +6
    -0
      addon/funciones.php
  44. +510
    -0
      addon/logis/.goutputstream-WQKM8X
  45. +91
    -0
      addon/logis/funciones/funciones.php
  46. +36
    -0
      addon/logis/funciones/twitter/autoload.php
  47. BIN
      addon/logis/funciones/twitter/c.png
  48. +6
    -0
      addon/logis/funciones/twitter/config.php
  49. +31
    -0
      addon/logis/funciones/twitter/datos.php
  50. +65
    -0
      addon/logis/funciones/twitter/hola.php
  51. +64
    -0
      addon/logis/funciones/twitter/src/Config.php
  52. +36
    -0
      addon/logis/funciones/twitter/src/Consumer.php
  53. +39
    -0
      addon/logis/funciones/twitter/src/HmacSha1.php
  54. +254
    -0
      addon/logis/funciones/twitter/src/Request.php
  55. +107
    -0
      addon/logis/funciones/twitter/src/Response.php
  56. +66
    -0
      addon/logis/funciones/twitter/src/SignatureMethod.php
  57. +38
    -0
      addon/logis/funciones/twitter/src/Token.php
  58. +448
    -0
      addon/logis/funciones/twitter/src/TwitterOAuth.php
  59. +10
    -0
      addon/logis/funciones/twitter/src/TwitterOAuthException.php
  60. +115
    -0
      addon/logis/funciones/twitter/src/Util.php
  61. +26
    -0
      addon/logis/funciones/twitter/src/Util/JsonDecoder.php
  62. +3952
    -0
      addon/logis/funciones/twitter/src/cacert.pem
  63. +31
    -0
      addon/logis/funciones/twitter/tuitear.php
  64. +177
    -0
      addon/logis/grabar.php
  65. BIN
      addon/logis/images/logos/150.png
  66. BIN
      addon/logis/images/logos/250.png
  67. BIN
      addon/logis/images/logos/c.png
  68. +0
    -0
      addon/logis/index.html
  69. +13
    -0
      addon/logis/js/demo.js
  70. +143
    -0
      addon/logis/js/load-image-meta.js
  71. +166
    -0
      addon/logis/js/load-image-orientation.js
  72. +1
    -0
      addon/logis/js/load-image.all.min.js
  73. +305
    -0
      addon/logis/js/load-image.js
  74. +365
    -0
      addon/logis/logis.php
  75. +207
    -0
      addon/logis/logis.php.php
  76. +207
    -0
      addon/logis/logis_completo.php
  77. +145
    -0
      addon/machitroll/funciones/funciones.php
  78. BIN
      addon/machitroll/images/incurable/100.png
  79. BIN
      addon/machitroll/images/incurable/200.png
  80. BIN
      addon/machitroll/images/incurable/300.png
  81. BIN
      addon/machitroll/images/incurable/400.png
  82. BIN
      addon/machitroll/images/incurable/500.png
  83. BIN
      addon/machitroll/images/rescatable/100.png
  84. BIN
      addon/machitroll/images/rescatable/200.png
  85. BIN
      addon/machitroll/images/rescatable/300.png
  86. BIN
      addon/machitroll/images/rescatable/400.png
  87. BIN
      addon/machitroll/images/rescatable/500.png
  88. +0
    -0
      addon/machitroll/index.php
  89. +487
    -0
      addon/machitroll/machitroll.php
  90. +24
    -0
      addon/marcador/funciones/funciones.php
  91. BIN
      addon/marcador/images/054843d530f3c83fcdbd55e688d874ec.png
  92. BIN
      addon/marcador/images/fb198e8742561eb1a9d8da9d95fddeae.png
  93. BIN
      addon/marcador/images/fca0a98bc665e9f026d5ea4331046893.png
  94. +0
    -0
      addon/marcador/index.php
  95. +412
    -0
      addon/marcador/marcador.php
  96. +108
    -0
      addon/tuitealo/funciones/funciones.php
  97. +0
    -0
      addon/tuitealo/index.php
  98. +66
    -0
      addon/tuitealo/tuitealo.php
  99. +40
    -0
      api.php
  100. +96
    -0
      archivos/index.php

+ 0
- 103
API.md View File

@@ -1,103 +0,0 @@
# API de MILFS

El api consulta a nivel local todos los datos si se ha logueado en el
sistema a nivel remoto o sin logueo los datos de los formularios que
se han marcado como de contenido publico.

http://localhost/milfs/api.php
Consulta cuales formularios hay en la instancia.

http://localhost/milfs/api.php?id=3
Consulta todo el contenido que se ha introducido en un formulario
pasándole el id como parametro.

http://localhost/milfs/api.php?identificador=04718326a4922f93d9f7b5f6f682d111


Para que se muestren las imagenes por medio de la api.php en las versiones antes del 20150218
se debe hacer la siguiente entrada en el mysql

INSERT INTO `form_campos` (`id`, `id_especialista`, `id_empresa`, `campo_nombre`, `campo_descripcion`, `campo_tipo`, `campo_area`, `orden`, `activo`, `identificador`, `bloqueo`, `tipo_contenido`) VALUES
(0, 0, 1, 'imagen', 'Campo especial para la imagen', 15, 0, 0, 1, 'imagen', 0, '');


Consulta todos los datos que se han llenado en cada formulario pasando
el identificador como parametro, cabe anotar que cuando se edita un
formulario se guarda la versión anterior de este campo por lo que si
se quiere conocer el estado actual de un formulario que ha sido
editado, debería filtrarse por timestamp para conocer su ultima
versión o vesiones anteriores.


http://datos.labmde.org/api.php?dato=52772
Consulta la info sobre un dato en concreto pasando el id del dato
como parametro.

Para entender el manejo de la api se debe tener en cuenta lo siguiente:

Cuando se crea un formulario MILF le asigna un ID unico a cada formulario que aparece en el JSON como: "form_id": pero esto solo es util si se quiere hacer referencia al fomulario especifico llamando la API sin ningun parametro, asi:

http://datos.labmde.org/api.php

Si se quiere leer los datos en un formulario especifico la api se llama de la siguiente forma:

http://datos.labmde.org/api.php?id=19

De esta forma la API nos entrega todos los datos, para hacer ejercicios de visualizacion de datos lo recomendable es utilizar los ID de los campos, especificado en el JSON asi: "id_campo"
Cada campo asociado a un formulario se le asigna un ID unico.

# Manejo de Imagenes

Milf permite almacenar imagenes para los formularios, las imagenes quedan almacenadas en el sistema de archivos del servidor, y genera de forma automatica 3 tamaños (150px 300px y 600px) y tambien almacena la imagen en el tamaño original.

Lo siguiente es un ejemplo de como la **API** entrega un dato tipo **IMAGEN**:
~~~

{
"0": 53326,
"id_dato": 53326,
"1": 21,
"id_formulario": 21,
"2": "Viaje a pie",
"formulario": "Viaje a pie",
"3": "imagen",
"campo_nombre": "imagen",
"4": 0,
"id_campo": 0,
"5": "7b2deb5cb4580984c8acd71c09e0f1f1.jpg",
"contenido": "7b2deb5cb4580984c8acd71c09e0f1f1.jpg",
"6": 1432608321,
"timestamp": 1432608321,
"7": "4b0d9a636567465bed3ada5a2e6f2fa6",
"identificador": "4b0d9a636567465bed3ada5a2e6f2fa6",
"8": 0,
"orden": 0
},

~~~

Ahora para usar la imagen se debe completar la URL, como se ve en los siguientes ejemplos:

**Para usar la imagen de 600px**

http://datos.labmde.org/milfs/images/secure/?file=600/7b2deb5cb4580984c8acd71c09e0f1f1.jpg

**Para usar la imagen de 300px**

http://datos.labmde.org/milfs/images/secure/?file=300/7b2deb5cb4580984c8acd71c09e0f1f1.jpg

**Para usar la imagen de 150px**

http://datos.labmde.org/milfs/images/secure/?file=150/7b2deb5cb4580984c8acd71c09e0f1f1.jpg

**Para usar la imagen FULL o Original**

http://datos.labmde.org/milfs/images/secure/?file=full/7b2deb5cb4580984c8acd71c09e0f1f1.jpg

**Nota:** Es importante que observe que el JSON entrega el dato de la siguiente forma:
~~~
"5": "7b2deb5cb4580984c8acd71c09e0f1f1.jpg",
~~~

Cada imagen queda codificada de la siguiente forma: 7b2deb5cb4580984c8acd71c09e0f1f1.jpg que sera el nombre de la imagen asignada por el sistema.


+ 510
- 0
addon/brigada/.goutputstream-WQKM8X View File

@@ -0,0 +1,510 @@
<?php
//include("funciones/funciones.php");
$id_formulario = "58";
$ancho = "500";

$tags = array();
$tags[] = "milfs/addon/logis/images/logos/c.png";

foreach ($tags as &$valor) {
$imagen .= "<td onclick=\" document.getElementById('marca').src='$valor' ; marcar('top-left') \" ><a href='#medio' class='' >
<img class='img ' src='$valor'>
</a></td>";
}

$imagen = "
<div class='table-responsive'>
<table class='table table table-condensed text-center '>
<tr >
$imagen
</tr>
</table>
</div>";

?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div>
<style type="text/css">
.fa{
font-size:60px important!;
}
#imagen_origina{
width: <?echo $ancho ?>px;
}
body{
background-color:white !important;

}


.pin {
text-align: center;
/*border: solid 1px red;*/
opacity: 0.5;
}
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
width: 80%;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 10;
padding: 0;
font-size: 50px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
.ing-touch{
border: solid 1px red;
width:20% !important;
}

</style>

<div class='container' style='backgroun-color:white;' >
<div class='fileUpload btn btn-primary center-block'>
<span><h1><i class="fa fa-camera"></i></h1></span>
<input class='upload' type="file" id="file-input" /></span>
<div id="original" ></div>
</div>

<!-- <p><input type="file" id="file-input"></p> -->
<div id="actions" style="display:none;">
<img class="center-block" src= "<?php echo $tags[0]; ?>" style='display:none' id="marca" name="marca">
<img class="center-block" style='' id="image_output" name="image_output">
<img class="center-block" style='' id="otra_imagen" name="otra_imagen">


<div id="result" class="result">
<p></p>
</div>
<a name="arriba"></a>
<div style="position:relative">
<div style="position:absolute; width:100%; height:100%;" >
<table style="width:100%; height:100%;" class="">
<tr >
<td class="pin" ><a href="#arriba" onclick=" javascript: marcar('top-left')"><img class="ing-touch img img-circle img-responsive center-block " style="width:20%;" src="milfs/images/oscuro40.png"></a></td>
<td class="pin"><a href="#arriba" onclick=" javascript: marcar('top-center')"><img class="ing-touch img img-circle img-responsive center-block " style="width:20%;" src="milfs/images/oscuro40.png"></a></td>
<td class="pin"><a href="#arriba" onclick=" javascript: marcar('top-rigth')"><img class="ing-touch img img-circle img-responsive center-block " style="width:50%;" src="milfs/images/oscuro40.png"></a></td>
</tr>
<tr>
<td class="pin"><a name="medio"></a><a href="#arriba" onclick=" javascript: marcar('middle-left')"><img class="ing-touch img img-circle img-responsive center-block " style="width:50%;" src="milfs/images/oscuro40.png"></a></td>
<td class="pin" ><a href="#medio" onclick=" javascript: marcar('middle-center')"><img class="ing-touch img img-circle img-responsive center-block " style="width:50%;" src="milfs/images/oscuro40.png"></a></td>
<td class="pin"><a href="#medio" onclick=" javascript: marcar('middle-rigth')"><img class="ing-touch img img-circle img-responsive center-block " style="width:50%;" src="milfs/images/oscuro40.png"></td>
</tr>
<tr>
<td class="pin"><a href="#medio" onclick=" javascript: marcar('bottom-left')"><img class="ing-touch img img-circle img-responsive center-block " style="width:50%;" src="milfs/images/oscuro40.png"></a></td>
<td class="pin"><a href="#medio" onclick=" javascript: marcar('bottom-center')"><img class="ing-touch img img-circle img-responsive center-block " style="width:50%;" src="milfs/images/oscuro40.png"></a></td>
<td class="pin"><a href="#medio" onclick=" javascript: marcar('bottom-rigth')"><img class="ing-touch img img-circle img-responsive center-block " style="width:50%;" src="milfs/images/oscuro40.png"></a></td>
</tr>

</table>
</div>
<canvas id="micanvas" style="position:absolute" >
Tu navegador no soporta canvas.
</canvas>

</div>
<div class="row " style="position:relative">

<form id='formulario_brigadistas' name='formulario_brigadistas' >
<input class='form-control' type='' id="debugConsole" name="debugConsole" >
<input type='' id="identificador" name="identificador" >
<input type='hidden' id="formulario_id" name="formulario_id" value="<?php echo $id_formulario; ?>">
<input type='hidden' id="imagen" name="imagen" value="">
<?php $formulario = formulario_areas("$id_formulario",'campos','','');
echo $formulario; ?>
</form>
</div>
<div id='aviso'>Aviso</div>
<div class="row">
<div class="col-md-12">
<!-- this.disabled= true; xajax_wait('aviso','Grabando... un momento por favor...'); -->
<button class='fileUpload btn btn-success btn-block' onclick=" xajax_brigadistas_grabar(xajax.getFormValues('formulario_brigadistas'))">
<span><i class="fa fa-save"></i> <span class='fa'> Grabalo! </span></span>
</button>

</div>
</div>
</div>
</div>
<script language="javascript">
$(function () {
'use strict';

var result = $('#result'),
exifNode = $('#exif'),
thumbNode = $('#thumbnail'),
actionsNode = $('#actions'),
currentFile,
replaceResults = function (img) {
var content;
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Loading image file failed</span>');
} else {
content = $('<img />').append(img)
//.attr('download', currentFile.name)
.attr('src', img.src || img.toDataURL())
.attr('width', '<?echo $ancho ?>px')
.attr('style', 'width:100%')
.attr('id', 'imagen_original');

}
//document.getElementById('image_output').src = img.src;
result.children().replaceWith(content);
if (img.getContext) {
actionsNode.show();
window.setTimeout("marcar('middle-center');", 500);
}
},
displayImage = function (file, options) {
currentFile = file;
if (!loadImage(
file,
replaceResults,
options
)) {
result.children().replaceWith(
$('<span>Your browser does not support the URL or FileReader API.</span>')
);
}
},
displayExifData = function (exif) {
var thumbnail = exif.get('Thumbnail'),
tags = exif.getAll(),
table = exifNode.find('table').empty(),
row = $('<tr></tr>'),
cell = $('<td></td>'),
prop;
if (thumbnail) {
thumbNode.empty();
loadImage(thumbnail, function (img) {
thumbNode.append(img).show();
}, {orientation: exif.get('Orientation')});
}
for (prop in tags) {
if (tags.hasOwnProperty(prop)) {
table.append(
row.clone()
.append(cell.clone().text(prop))
.append(cell.clone().text(tags[prop]))
);
}
}
exifNode.show();
},
dropChangeHandler = function (e) {
e.preventDefault();
e = e.originalEvent;
var target = e.dataTransfer || e.target,
file = target && target.files && target.files[0],
options = {
maxWidth: result.width(),
canvas: true
};
if (!file) {
return;
}
exifNode.hide();
thumbNode.hide();
loadImage.parseMetaData(file, function (data) {
if (data.exif) {
options.orientation = data.exif.get('Orientation');
displayExifData(data.exif);
}
displayImage(file, options);
});
},
coordinates;
// Hide URL/FileReader API requirement message in capable browsers:
if (window.createObjectURL || window.URL || window.webkitURL || window.FileReader) {
result.children().hide();
}
$(document)
.on('dragover', function (e) {
e.preventDefault();
e = e.originalEvent;
e.dataTransfer.dropEffect = 'copy';
})
.on('drop', dropChangeHandler);
$('#file-input').on('change', dropChangeHandler);
$('#edit').on('click', function (event) {
event.preventDefault();
var imgNode = result.find('img, canvas'),
img = imgNode[0];
imgNode.Jcrop({
setSelect: [40, 40, img.width - 40, img.height - 40],
onSelect: function (coords) {
coordinates = coords;
},
onRelease: function () {
coordinates = null;
}
}).parent().on('click', function (event) {
event.preventDefault();
});
});
$('#crop').on('click', function (event) {
event.preventDefault();
var img = result.find('img, canvas')[0];
if (img && coordinates) {
replaceResults(loadImage.scale(img, {
left: coordinates.x,
top: coordinates.y,
sourceWidth: coordinates.w,
sourceHeight: coordinates.h,
minWidth: result.width()
}));
coordinates = null;
}
});

});

</script>
<script language="javascript">
function cargaContextoCanvas(idCanvas){
var elemento = document.getElementById(idCanvas);
if(elemento && elemento.getContext){
var contexto = elemento.getContext('2d');
if(contexto){
return contexto;
}
}
return FALSE;
}


function marcar(ubicacion){
//if (ubicacion == 'arriba'){ var x = '0';var y = '0';}
//if (ubicacion == 'abajo'){ var x = '10';var y = '50';}




//Recibimos el elemento canvas
var ctx = cargaContextoCanvas('micanvas');

if(ctx){
//Creo una imagen conun objeto Image de Javascript
var img = new Image();
var img2 = new Image();
//img.src = document.getElementById("image_output2").src;
//readAsDataURL(
img.src = document.getElementById("imagen_original").src;
document.getElementById("imagen_original").style.display="none";
//img2.src = 'images/logos/a.png';
img2.src = document.getElementById("marca").src;
if (ubicacion =='') {
ubicacion ='middle-center';
}
x = 0,
y = 0;
if(ubicacion.indexOf("top")!=-1)
y = 10;
else if(ubicacion.indexOf("middle")!=-1)
y = (micanvas.height - img2.height)/2;
else
y = micanvas.height-img2.height-10;
if(ubicacion.indexOf("left")!=-1)
x = 10;
else if(ubicacion.indexOf("center")!=-1)
x = (micanvas.width - img2.width) /2;
else
x = micanvas.width-img2.width-10;
var proporcion = ( img.height / img.width );
var ancho = <?echo $ancho ?>;
micanvas.width =ancho;
micanvas.height = (micanvas.width * proporcion);
micanvas.setAttribute('width', ancho);
micanvas.setAttribute('height', micanvas.height);
micanvas.setAttribute('style',"width:100%");

img.onload = function(){
ctx.drawImage(img, 0, 0,micanvas.width,micanvas.height);
ctx.drawImage(img2, x, y);
var debugConsole= document.getElementById("debugConsole");
var testCanvas = document.getElementById("micanvas");
var canvasData = testCanvas.toDataURL("image/png");
var postData = "canvasData="+canvasData;
debugConsole.value=canvasData;
var identificador = Math.random();
document.getElementById('identificador').value= identificador;
}
}
}


$(function () {
'use strict';

var result = $('#result'),
exifNode = $('#exif'),
thumbNode = $('#thumbnail'),
actionsNode = $('#actions'),
currentFile,
replaceResults = function (img) {
var content;
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Loading image file failed</span>');
} else {
content = $('<img />').append(img)
//.attr('download', currentFile.name)
.attr('src', img.src || img.toDataURL())
.attr('width', '<?echo $ancho ?>')
.attr('style', 'width:100%')
.attr('id', 'imagen_original');

}
//document.getElementById('image_output').src = img.src;
result.children().replaceWith(content);
if (img.getContext) {
actionsNode.show();
window.setTimeout("marcar('middle-center');", 500);
}
},
displayImage = function (file, options) {
currentFile = file;
if (!loadImage(
file,
replaceResults,
options
)) {
result.children().replaceWith(
$('<span>Your browser does not support the URL or FileReader API.</span>')
);
}
},
displayExifData = function (exif) {
var thumbnail = exif.get('Thumbnail'),
tags = exif.getAll(),
table = exifNode.find('table').empty(),
row = $('<tr></tr>'),
cell = $('<td></td>'),
prop;
if (thumbnail) {
thumbNode.empty();
loadImage(thumbnail, function (img) {
thumbNode.append(img).show();
}, {orientation: exif.get('Orientation')});
}
for (prop in tags) {
if (tags.hasOwnProperty(prop)) {
table.append(
row.clone()
.append(cell.clone().text(prop))
.append(cell.clone().text(tags[prop]))
);
}
}
exifNode.show();
},
dropChangeHandler = function (e) {
e.preventDefault();
e = e.originalEvent;
var target = e.dataTransfer || e.target,
file = target && target.files && target.files[0],
options = {
maxWidth: result.width(),
canvas: true
};
if (!file) {
return;
}
exifNode.hide();
thumbNode.hide();
loadImage.parseMetaData(file, function (data) {
if (data.exif) {
options.orientation = data.exif.get('Orientation');
displayExifData(data.exif);
}
displayImage(file, options);
});
},
coordinates;
// Hide URL/FileReader API requirement message in capable browsers:
if (window.createObjectURL || window.URL || window.webkitURL || window.FileReader) {
result.children().hide();
}
$(document)
.on('dragover', function (e) {
e.preventDefault();
e = e.originalEvent;
e.dataTransfer.dropEffect = 'copy';
})
.on('drop', dropChangeHandler);
$('#file-input').on('change', dropChangeHandler);
$('#edit').on('click', function (event) {
event.preventDefault();
var imgNode = result.find('img, canvas'),
img = imgNode[0];
imgNode.Jcrop({
setSelect: [40, 40, img.width - 40, img.height - 40],
onSelect: function (coords) {
coordinates = coords;
},
onRelease: function () {
coordinates = null;
}
}).parent().on('click', function (event) {
event.preventDefault();
});
});
$('#crop').on('click', function (event) {
event.preventDefault();
var img = result.find('img, canvas')[0];
if (img && coordinates) {
replaceResults(loadImage.scale(img, {
left: coordinates.x,
top: coordinates.y,
sourceWidth: coordinates.w,
sourceHeight: coordinates.h,
minWidth: result.width()
}));
coordinates = null;
}
});

});
</script>

<br>
<script src="milfs/addon/logis/js/load-image.all.min.js"></script>
<!-- <script src="js/load-image.js"></script> -->
<!-- <script src="js/load-image-ios.js"></script> -->
<!-- <script src="js/load-image-orientation.js"></script> -->
<!-- <script src="js/load-image-meta.js"></script> -->
<!-- <script src="js/load-image-exif.js"></script> -->
<!-- <script src="js/load-image-exif-map.js"></script> -->
<!-- jQuery and Jcrop are not required by JavaScript Load Image, but included for the demo -->
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->
<!-- <script src="js/vendor/jquery.Jcrop.js"></script> -->
<!-- <script src="js/demo.js"></script> -->
</div>

+ 91
- 0
addon/brigada/funciones/funciones.php View File

@@ -0,0 +1,91 @@
<?php
function brigadistas_grabar_imagen($data,$identificador) {
$respuesta = new xajaxResponse('utf-8');
$control = md5("$identificador");
//$form_id = $fomulario["formulario_id"];

$imagen= grabar_imagen($data,$control);
$preview = "<img src='$_SESSION[url]/images/secure/?file=150/$imagen'>";
$respuesta->addScript("javascript: document.getElementById('imagen').value= '$imagen' ;");
$respuesta->addAssign("aviso","innerHTML","$preview");
return $respuesta;
}
$xajax->registerFunction("brigadistas_grabar_imagen");
function brigadistas_grabar($formulario) {
$identificador = $formulario['identificador'];
$control = md5("$identificador");
$data = $formulario['debugConsole'];
$imagen= grabar_imagen($data,$control);
$texto_url = urlencode("#BrigadaDigital");
$uri = urlencode("$_SESSION[url]/images/secure/?file=600/$imagen");
$url ="https://twitter.com/share?url=$uri&text=$texto_url";

//$respuesta->addScript("window.location.href ='$url';");

$respuesta = new xajaxResponse('utf-8');
//$identificador = $formulario['identificador'];
$id_formulario = $formulario['formulario_id'];
$campo_imagen = buscar_campo_tipo("$id_formulario","15");
$formulario[$campo_imagen[0]][0] = $imagen;
$empresa = remplacetas('form_id','id',"$id_formulario",'id_empresa',"") ;
$id_empresa = $empresa[0];

include_once("librerias/conex.php");
$link=Conectarse();
mysqli_query("SET NAMES 'utf8'");
foreach($formulario as $campo=>$valor){
if(is_array($valor)) {
foreach($valor as $c=>$v){
$consulta = "INSERT INTO form_datos ( timestamp,id_usuario,id_empresa,form_id,ip,control,id_campo,contenido) VALUES
( UNIX_TIMESTAMP(),'$_SESSION[id]','$id_empresa','$id_formulario','$ip' ,'$control', '$campo' , '".mysql_real_escape_string( $v )."')
";
$sql=mysqli_query($consulta,$link);
// $campos .= " $campo // $valor // $c -> $v $consulta <br>";
}
}
}
$twitter = $formulario['498'][0];
$_SESSION['logis'] = "$control";
$_SESSION['mensaje'] = "$twitter";
$preview = "
<div class='row'>
<div class='center-block'>
<div class='thumbnail'>
<img src='$_SESSION[url]/images/secure/?file=300/$imagen'>
<h2 class='text-center'>$twitter<h2>
<a download='brigadistas.png' href='$_SESSION[url]images/secure/?file=600/$imagen' >
<span class='btn btn-default'><i class='fa fa-download'></i> </span>
</a>
<span class='btn btn-default'>
<a target= 'twitter' href ='milfs/addon/logis/funciones/twitter/tuitear.php' ><i class='fa fa-twitter'></i></a>
</span>
<a href='S58'>
<span class='btn btn-default'><i class='fa fa-eye'></i> </span>
</a>
<a href='#' onclick = \"javascript:location.reload(); \">
<span class='btn btn-default'><i class='fa fa-refresh'></i> </span>
</a>
</div>
</div>
</div>

";
$resultado = "$preview ";

$respuesta->addAssign("aviso","innerHTML","$preview");
//$respuesta->addAlert("$resultado");
//$respuesta->addScript("javascript:location.reload(true);");
return $respuesta;
}
$xajax->registerFunction("brigadistas_grabar");



?>

+ 36
- 0
addon/brigada/funciones/twitter/autoload.php View File

@@ -0,0 +1,36 @@
<?php

/**
* Use to autoload needed classes without Composer.
*
* @param string $class The fully-qualified class name.
* @return void
*/
spl_autoload_register(function ($class) {

// project-specific namespace prefix
$prefix = 'Abraham\\TwitterOAuth\\';

// base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';

// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}

// get the relative class name
$relative_class = substr($class, $len);

// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});

BIN
addon/brigada/funciones/twitter/c.png View File

Before After
Width: 150  |  Height: 149  |  Size: 38KB

+ 6
- 0
addon/brigada/funciones/twitter/config.php View File

@@ -0,0 +1,6 @@
<?php
define('CONSUMER_KEY', 'QS1JHXs7OgJcFArJmMv117JEn');
define('CONSUMER_SECRET', 'NoO1FUXHmTB74HUrnDbcs64XgZoroBkaPav8w0FgbK3ZYSU9PZ');
define('OAUTH_CALLBACK', 'http://datos.labmde.org/milfs/toa/hola.php');

?>

+ 31
- 0
addon/brigada/funciones/twitter/datos.php View File

@@ -0,0 +1,31 @@
<?php
ini_set('display_errors', 1);
require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
/*
define('CONSUMER_KEY', getenv('wMtivKDSAgZmkP7EZhYcfw'));
define('CONSUMER_SECRET', getenv('AvWbHfjuSJkZYhkxsU8ojsDpNtvapBoiRUzwF3OAvbo'));
define('OAUTH_CALLBACK', getenv('http://datos.labmde.org/milfs/toa/hola.php'));
*/
define('CONSUMER_KEY', 'QS1JHXs7OgJcFArJmMv117JEn');
define('CONSUMER_SECRET', 'NoO1FUXHmTB74HUrnDbcs64XgZoroBkaPav8w0FgbK3ZYSU9PZ');
define('OAUTH_CALLBACK', 'http://datos.labmde.org/milfs/addon/logis/funciones/twitter/hola.php');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
//print $connection; //print connection contents
//$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
$request_token = $connection->oauth('oauth/request_token');
//$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
$user = $connection->get("account/verify_credentials");
//print $user->screen_name;
print_r($user);
// Post Update

$content = $connection->post('statuses/update', array('status' => 'Bonito dia'));
print_r( $content);
print_r($url);


//print_r($request_token); //print connection contentsa


?>

+ 65
- 0
addon/brigada/funciones/twitter/hola.php View File

@@ -0,0 +1,65 @@
<?php
session_start();
ini_set('display_errors', 1);

require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once('config.php');
/* Crear un objeto TwitteroAuth con las credenciales de la aplicacion y el token temporal */
//$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Solicitar a twitter el token de acceso */
//$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));

/* Guardar el token de acceso. Normalmente, este token se guardará también en una base
de datos para volver a ser utilizado en otras ocasiones. */
$_SESSION['access_token'] = $access_token;
/* Eliminar el token temporal de solicitud */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
/* Si todo va bien, presentar al usuario la página principal "index.php" del servicio */
//if (200 == $connection->http_code) {
/* El usuario ha sido verificado */
$_SESSION['status'] = 'verified';
echo send_tweet($access_token);
//}
function base64_encode_image ($filename=string,$filetype=string) {
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return base64_encode($imgbinary);
}
}

function send_tweet($access_token) {
$tweet = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$access_token['oauth_token'], $access_token['oauth_token_secret']);
$nombre= $_SESSION['logis'].".png";
$nombre = "$_SESSION[path_images_secure]/600/$nombre";
$media1 = $tweet->upload('media/upload', array('media' => "$nombre"));
$parameters = array('status' =>"$_SESSION[mensaje] #BrigadaDigital #CD2015 http://datos.labmde.org/jlogis",'media_ids' => implode(',', array($media1->media_id_string)),
);

$result = $tweet-> post('statuses/update', $parameters);
$image = "$nombre";
$base64 = base64_encode_image (''.$image,'png');
$result = $tweet-> post('account/update_profile_image', array('image' => $base64.';type=image/jpg;filename='.$image));

// $message = "Bonito dia $nombre";
// $tweet->post('statuses/update', array('status' => "$message"));
//
}

header('Location: https://twitter.com/hashtag/CD2015');

// header('Location: ./index.php');
//} else {
//header('Location: ./clearsessions.php');
//

+ 64
- 0
addon/brigada/funciones/twitter/src/Config.php View File

@@ -0,0 +1,64 @@
<?php

namespace Abraham\TwitterOAuth;

/**
* Handle setting and storing config for TwitterOAuth.
*
* @author Abraham Williams <abraham@abrah.am>
*/
class Config
{
/** @var int How long to wait for a response from the API */
protected $timeout = 5;
/** @var int how long to wait while connecting to the API */
protected $connectionTimeout = 5;
/**
* Decode JSON Response as associative Array
*
* @see http://php.net/manual/en/function.json-decode.php
*
* @var bool
*/
protected $decodeJsonAsArray = false;
/** @var string User-Agent header */
protected $userAgent = 'TwitterOAuth (+https://twitteroauth.com)';
/** @var array Store proxy connection details */
protected $proxy = [];

/**
* Set the connection and response timeouts.
*
* @param int $connectionTimeout
* @param int $timeout
*/
public function setTimeouts($connectionTimeout, $timeout)
{
$this->connectionTimeout = (int)$connectionTimeout;
$this->timeout = (int)$timeout;
}

/**
* @param bool $value
*/
public function setDecodeJsonAsArray($value)
{
$this->decodeJsonAsArray = (bool)$value;
}

/**
* @param string $userAgent
*/
public function setUserAgent($userAgent)
{
$this->userAgent = (string)$userAgent;
}

/**
* @param array $proxy
*/
public function setProxy(array $proxy)
{
$this->proxy = $proxy;
}
}

+ 36
- 0
addon/brigada/funciones/twitter/src/Consumer.php View File

@@ -0,0 +1,36 @@
<?php
/**
* The MIT License
* Copyright (c) 2007 Andy Smith
*/
namespace Abraham\TwitterOAuth;

class Consumer
{
/** @var string */
public $key;
/** @var string */
public $secret;
/** @var string|null */
public $callbackUrl;

/**
* @param string $key
* @param string $secret
* @param null $callbackUrl
*/
public function __construct($key, $secret, $callbackUrl = null)
{
$this->key = $key;
$this->secret = $secret;
$this->callbackUrl = $callbackUrl;
}

/**
* @return string
*/
public function __toString()
{
return "Consumer[key=$this->key,secret=$this->secret]";
}
}

+ 39
- 0
addon/brigada/funciones/twitter/src/HmacSha1.php View File

@@ -0,0 +1,39 @@
<?php
/**
* The MIT License
* Copyright (c) 2007 Andy Smith
*/
namespace Abraham\TwitterOAuth;

/**
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
* where the Signature Base String is the text and the key is the concatenated values (each first
* encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
* character (ASCII code 38) even if empty.
* - Chapter 9.2 ("HMAC-SHA1")
*/
class HmacSha1 extends SignatureMethod
{
/**
* {@inheritDoc}
*/
public function getName()
{
return "HMAC-SHA1";
}

/**
* {@inheritDoc}
*/
public function buildSignature(Request $request, Consumer $consumer, Token $token = null)
{
$signatureBase = $request->getSignatureBaseString();

$parts = [$consumer->secret, null !== $token ? $token->secret : ""];

$parts = Util::urlencodeRfc3986($parts);
$key = implode('&', $parts);

return base64_encode(hash_hmac('sha1', $signatureBase, $key, true));
}
}

+ 254
- 0
addon/brigada/funciones/twitter/src/Request.php View File

@@ -0,0 +1,254 @@
<?php
/**
* The MIT License
* Copyright (c) 2007 Andy Smith
*/
namespace Abraham\TwitterOAuth;

class Request
{
protected $parameters;
protected $httpMethod;
protected $httpUrl;
public static $version = '1.0';

/**
* Constructor
*
* @param string $httpMethod
* @param string $httpUrl
* @param array|null $parameters
*/
public function __construct($httpMethod, $httpUrl, array $parameters = [])
{
$parameters = array_merge(Util::parseParameters(parse_url($httpUrl, PHP_URL_QUERY)), $parameters);
$this->parameters = $parameters;
$this->httpMethod = $httpMethod;
$this->httpUrl = $httpUrl;
}

/**
* pretty much a helper function to set up the request
*
* @param Consumer $consumer
* @param Token $token
* @param string $httpMethod
* @param string $httpUrl
* @param array $parameters
*
* @return Request
*/
public static function fromConsumerAndToken(
Consumer $consumer,
Token $token = null,
$httpMethod,
$httpUrl,
array $parameters = []
) {
$defaults = [
"oauth_version" => Request::$version,
"oauth_nonce" => Request::generateNonce(),
"oauth_timestamp" => time(),
"oauth_consumer_key" => $consumer->key
];
if (null !== $token) {
$defaults['oauth_token'] = $token->key;
}

$parameters = array_merge($defaults, $parameters);

return new Request($httpMethod, $httpUrl, $parameters);
}

/**
* @param string $name
* @param string $value
*/
public function setParameter($name, $value)
{
$this->parameters[$name] = $value;
}

/**
* @param $name
*
* @return string|null
*/
public function getParameter($name)
{
return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
}

/**
* @return array
*/
public function getParameters()
{
return $this->parameters;
}

/**
* @param $name
*/
public function removeParameter($name)
{
unset($this->parameters[$name]);
}

/**
* The request parameters, sorted and concatenated into a normalized string.
*
* @return string
*/
public function getSignableParameters()
{
// Grab all parameters
$params = $this->parameters;

// Remove oauth_signature if present
// Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
if (isset($params['oauth_signature'])) {
unset($params['oauth_signature']);
}

return Util::buildHttpQuery($params);
}

/**
* Returns the base string of this request
*
* The base string defined as the method, the url
* and the parameters (normalized), each urlencoded
* and the concated with &.
*
* @return string
*/
public function getSignatureBaseString()
{
$parts = [
$this->getNormalizedHttpMethod(),
$this->getNormalizedHttpUrl(),
$this->getSignableParameters()
];

$parts = Util::urlencodeRfc3986($parts);

return implode('&', $parts);
}

/**
* Returns the HTTP Method in uppercase
*
* @return string
*/
public function getNormalizedHttpMethod()
{
return strtoupper($this->httpMethod);
}

/**
* parses the url and rebuilds it to be
* scheme://host/path
*
* @return string
*/
public function getNormalizedHttpUrl()
{
$parts = parse_url($this->httpUrl);

$scheme = $parts['scheme'];
$host = strtolower($parts['host']);
$path = $parts['path'];

return "$scheme://$host$path";
}

/**
* Builds a url usable for a GET request
*
* @return string
*/
public function toUrl()
{
$postData = $this->toPostdata();
$out = $this->getNormalizedHttpUrl();
if ($postData) {
$out .= '?' . $postData;
}
return $out;
}

/**
* Builds the data one would send in a POST request
*
* @return string
*/
public function toPostdata()
{
return Util::buildHttpQuery($this->parameters);
}

/**
* Builds the Authorization: header
*
* @return string
* @throws TwitterOAuthException
*/
public function toHeader()
{
$first = true;
$out = 'Authorization: OAuth';
foreach ($this->parameters as $k => $v) {
if (substr($k, 0, 5) != "oauth") {
continue;
}
if (is_array($v)) {
throw new TwitterOAuthException('Arrays not supported in headers');
}
$out .= ($first) ? ' ' : ', ';
$out .= Util::urlencodeRfc3986($k) . '="' . Util::urlencodeRfc3986($v) . '"';
$first = false;
}
return $out;
}

/**
* @return string
*/
public function __toString()
{
return $this->toUrl();
}

/**
* @param SignatureMethod $signatureMethod
* @param Consumer $consumer
* @param Token $token
*/
public function signRequest(SignatureMethod $signatureMethod, Consumer $consumer, Token $token = null)
{
$this->setParameter("oauth_signature_method", $signatureMethod->getName());
$signature = $this->buildSignature($signatureMethod, $consumer, $token);
$this->setParameter("oauth_signature", $signature);
}

/**
* @param SignatureMethod $signatureMethod
* @param Consumer $consumer
* @param Token $token
*
* @return string
*/
public function buildSignature(SignatureMethod $signatureMethod, Consumer $consumer, Token $token = null)
{
return $signatureMethod->buildSignature($this, $consumer, $token);
}

/**
* @return string
*/
public static function generateNonce()
{
return md5(microtime() . mt_rand());
}
}

+ 107
- 0
addon/brigada/funciones/twitter/src/Response.php View File

@@ -0,0 +1,107 @@
<?php

namespace Abraham\TwitterOAuth;

/**
* The result of the most recent API request.
*
* @author Abraham Williams <abraham@abrah.am>
*/
class Response
{
/** @var string|null API path from the most recent request */
private $apiPath;
/** @var int HTTP status code from the most recent request */
private $httpCode = 0;
/** @var array HTTP headers from the most recent request */
private $headers = [];
/** @var array|object Response body from the most recent request */
private $body = [];
/** @var array HTTP headers from the most recent request that start with X */
private $xHeaders = [];

/**
* @param string $apiPath
*/
public function setApiPath($apiPath)
{
$this->apiPath = $apiPath;
}

/**
* @return string|null
*/
public function getApiPath()
{
return $this->apiPath;
}

/**
* @param array|object $body
*/
public function setBody($body)
{
$this->body = $body;
}

/**
* @return array|object|string
*/
public function getBody()
{
return $this->body;
}

/**
* @param int $httpCode
*/
public function setHttpCode($httpCode)
{
$this->httpCode = $httpCode;
}

/**
* @return int
*/
public function getHttpCode()
{
return $this->httpCode;
}

/**
* @param array $headers
*/
public function setHeaders($headers)
{
foreach ($headers as $key => $value) {
if (substr($key, 0, 1) == 'x') {
$this->xHeaders[$key] = $value;
}
}
$this->headers = $headers;
}

/**
* @return array
*/
public function getsHeaders()
{
return $this->headers;
}

/**
* @param array $xHeaders
*/
public function setXHeaders($xHeaders)
{
$this->xHeaders = $xHeaders;
}

/**
* @return array
*/
public function getXHeaders()
{
return $this->xHeaders;
}
}

+ 66
- 0
addon/brigada/funciones/twitter/src/SignatureMethod.php View File

@@ -0,0 +1,66 @@
<?php
/**
* The MIT License
* Copyright (c) 2007 Andy Smith
*/
namespace Abraham\TwitterOAuth;

/**
* A class for implementing a Signature Method
* See section 9 ("Signing Requests") in the spec
*/
abstract class SignatureMethod
{
/**
* Needs to return the name of the Signature Method (ie HMAC-SHA1)
*
* @return string
*/
abstract public function getName();

/**
* Build up the signature
* NOTE: The output of this function MUST NOT be urlencoded.
* the encoding is handled in OAuthRequest when the final
* request is serialized
*
* @param Request $request
* @param Consumer $consumer
* @param Token $token
*
* @return string
*/
abstract public function buildSignature(Request $request, Consumer $consumer, Token $token = null);

/**
* Verifies that a given signature is correct
*
* @param Request $request
* @param Consumer $consumer
* @param Token $token
* @param string $signature
*
* @return bool
*/
public function checkSignature(Request $request, Consumer $consumer, Token $token, $signature)
{
$built = $this->buildSignature($request, $consumer, $token);

// Check for zero length, although unlikely here
if (strlen($built) == 0 || strlen($signature) == 0) {
return false;
}

if (strlen($built) != strlen($signature)) {
return false;
}

// Avoid a timing leak with a (hopefully) time insensitive compare
$result = 0;
for ($i = 0; $i < strlen($signature); $i++) {
$result |= ord($built{$i}) ^ ord($signature{$i});
}

return $result == 0;
}
}

+ 38
- 0
addon/brigada/funciones/twitter/src/Token.php View File

@@ -0,0 +1,38 @@
<?php
/**
* The MIT License
* Copyright (c) 2007 Andy Smith
*/
namespace Abraham\TwitterOAuth;

class Token
{
/** @var string */
public $key;
/** @var string */
public $secret;

/**
* @param string $key The OAuth Token
* @param string $secret The OAuth Token Secret
*/
public function __construct($key, $secret)
{
$this->key = $key;
$this->secret = $secret;
}

/**
* Generates the basic string serialization of a token that a server
* would respond to request_token and access_token calls with
*
* @return string
*/
public function __toString()
{
return sprintf("oauth_token=%s&oauth_token_secret=%s",
Util::urlencodeRfc3986($this->key),
Util::urlencodeRfc3986($this->secret)
);
}
}

+ 448
- 0
addon/brigada/funciones/twitter/src/TwitterOAuth.php View File

@@ -0,0 +1,448 @@
<?php
/**
* The most popular PHP library for use with the Twitter OAuth REST API.
*
* @license MIT
*/
namespace Abraham\TwitterOAuth;

use Abraham\TwitterOAuth\Util\JsonDecoder;

/**
* TwitterOAuth class for interacting with the Twitter API.
*
* @author Abraham Williams <abraham@abrah.am>
*/
class TwitterOAuth extends Config
{
const API_VERSION = '1.1';
const API_HOST = 'https://api.twitter.com';
const UPLOAD_HOST = 'https://upload.twitter.com';
const UPLOAD_CHUNK = 40960; // 1024 * 40

/** @var Response details about the result of the last request */
private $response;
/** @var string|null Application bearer token */
private $bearer;
/** @var Consumer Twitter application details */
private $consumer;
/** @var Token|null User access token details */
private $token;
/** @var HmacSha1 OAuth 1 signature type used by Twitter */
private $signatureMethod;

/**
* Constructor
*
* @param string $consumerKey The Application Consumer Key
* @param string $consumerSecret The Application Consumer Secret
* @param string|null $oauthToken The Client Token (optional)
* @param string|null $oauthTokenSecret The Client Token Secret (optional)
*/
public function __construct($consumerKey, $consumerSecret, $oauthToken = null, $oauthTokenSecret = null)
{
$this->resetLastResponse();
$this->signatureMethod = new HmacSha1();
$this->consumer = new Consumer($consumerKey, $consumerSecret);
if (!empty($oauthToken) && !empty($oauthTokenSecret)) {
$this->token = new Token($oauthToken, $oauthTokenSecret);
}
if (empty($oauthToken) && !empty($oauthTokenSecret)) {
$this->bearer = $oauthTokenSecret;
}
}

/**
* @param string $oauthToken
* @param string $oauthTokenSecret
*/
public function setOauthToken($oauthToken, $oauthTokenSecret)
{
$this->token = new Token($oauthToken, $oauthTokenSecret);
}

/**
* @return string|null
*/
public function getLastApiPath()
{
return $this->response->getApiPath();
}

/**
* @return int
*/
public function getLastHttpCode()
{
return $this->response->getHttpCode();
}

/**
* @return array
*/
public function getLastXHeaders()
{
return $this->response->getXHeaders();
}

/**
* @return array|object|null
*/
public function getLastBody()
{
return $this->response->getBody();
}

/**
* Resets the last response cache.
*/
public function resetLastResponse()
{
$this->response = new Response();
}

/**
* Make URLs for user browser navigation.
*
* @param string $path
* @param array $parameters
*
* @return string
*/
public function url($path, array $parameters)
{
$this->resetLastResponse();
$this->response->setApiPath($path);
$query = http_build_query($parameters);
return sprintf('%s/%s?%s', self::API_HOST, $path, $query);
}

/**
* Make /oauth/* requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array
* @throws TwitterOAuthException
*/
public function oauth($path, array $parameters = [])
{
$response = [];
$this->resetLastResponse();
$this->response->setApiPath($path);
$url = sprintf('%s/%s', self::API_HOST, $path);
$result = $this->oAuthRequest($url, 'POST', $parameters);

if ($this->getLastHttpCode() != 200) {
throw new TwitterOAuthException($result);
}

parse_str($result, $response);
$this->response->setBody($response);

return $response;
}

/**
* Make /oauth2/* requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function oauth2($path, array $parameters = [])
{
$method = 'POST';
$this->resetLastResponse();
$this->response->setApiPath($path);
$url = sprintf('%s/%s', self::API_HOST, $path);
$request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters);
$authorization = 'Authorization: Basic ' . $this->encodeAppAuthorization($this->consumer);
$result = $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters);
$response = JsonDecoder::decode($result, $this->decodeJsonAsArray);
$this->response->setBody($response);
return $response;
}

/**
* Make GET requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function get($path, array $parameters = [])
{
return $this->http('GET', self::API_HOST, $path, $parameters);
}

/**
* Make POST requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function post($path, array $parameters = [])
{
return $this->http('POST', self::API_HOST, $path, $parameters);
}

/**
* Make DELETE requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function delete($path, array $parameters = [])
{
return $this->http('DELETE', self::API_HOST, $path, $parameters);
}

/**
* Make PUT requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function put($path, array $parameters = [])
{
return $this->http('PUT', self::API_HOST, $path, $parameters);
}

/**
* Upload media to upload.twitter.com.
*
* @param string $path
* @param array $parameters
* @param boolean $chunked
*
* @return array|object
*/
public function upload($path, array $parameters = [], $chunked = false)
{
if ($chunked) {
return $this->uploadMediaChunked($path, $parameters);
} else {
return $this->uploadMediaNotChunked($path, $parameters);
}
}

/**
* Private method to upload media (not chunked) to upload.twitter.com.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
private function uploadMediaNotChunked($path, $parameters)
{
$file = file_get_contents($parameters['media']);
$base = base64_encode($file);
$parameters['media'] = $base;
return $this->http('POST', self::UPLOAD_HOST, $path, $parameters);
}

/**
* Private method to upload media (chunked) to upload.twitter.com.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
private function uploadMediaChunked($path, $parameters)
{
// Init
$init = $this->http('POST', self::UPLOAD_HOST, $path, [
'command' => 'INIT',
'media_type' => $parameters['media_type'],
'total_bytes' => filesize($parameters['media'])
]);
// Append
$segment_index = 0;
$media = fopen($parameters['media'], 'rb');
while (!feof($media))
{
$this->http('POST', self::UPLOAD_HOST, 'media/upload', [
'command' => 'APPEND',
'media_id' => $init->media_id_string,
'segment_index' => $segment_index++,
'media_data' => base64_encode(fread($media, self::UPLOAD_CHUNK))
]);
}
fclose($media);
// Finalize
$finalize = $this->http('POST', self::UPLOAD_HOST, 'media/upload', [
'command' => 'FINALIZE',
'media_id' => $init->media_id_string
]);
return $finalize;
}

/**
* @param string $method
* @param string $host
* @param string $path
* @param array $parameters
*
* @return array|object
*/
private function http($method, $host, $path, array $parameters)
{
$this->resetLastResponse();
$url = sprintf('%s/%s/%s.json', $host, self::API_VERSION, $path);
$this->response->setApiPath($path);
$result = $this->oAuthRequest($url, $method, $parameters);
$response = JsonDecoder::decode($result, $this->decodeJsonAsArray);
$this->response->setBody($response);
return $response;
}

/**
* Format and sign an OAuth / API request
*
* @param string $url
* @param string $method
* @param array $parameters
*
* @return string
* @throws TwitterOAuthException
*/
private function oAuthRequest($url, $method, array $parameters)
{
$request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters);
if (array_key_exists('oauth_callback', $parameters)) {
// Twitter doesn't like oauth_callback as a parameter.
unset($parameters['oauth_callback']);
}
if ($this->bearer === null) {
$request->signRequest($this->signatureMethod, $this->consumer, $this->token);
$authorization = $request->toHeader();
} else {
$authorization = 'Authorization: Bearer ' . $this->bearer;
}
return $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters);
}

/**
* Make an HTTP request
*
* @param string $url
* @param string $method
* @param string $authorization
* @param array $postfields
*
* @return string
* @throws TwitterOAuthException
*/
private function request($url, $method, $authorization, $postfields)
{
/* Curl settings */
$options = [
// CURLOPT_VERBOSE => true,
CURLOPT_CAINFO => __DIR__ . DIRECTORY_SEPARATOR . 'cacert.pem',
CURLOPT_CONNECTTIMEOUT => $this->connectionTimeout,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => ['Accept: application/json', $authorization, 'Expect:'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => $this->userAgent,
CURLOPT_ENCODING => 'gzip',
];

if (!empty($this->proxy)) {
$options[CURLOPT_PROXY] = $this->proxy['CURLOPT_PROXY'];
$options[CURLOPT_PROXYUSERPWD] = $this->proxy['CURLOPT_PROXYUSERPWD'];
$options[CURLOPT_PROXYPORT] = $this->proxy['CURLOPT_PROXYPORT'];
$options[CURLOPT_PROXYAUTH] = CURLAUTH_BASIC;
$options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP;
}

switch ($method) {
case 'GET':
break;
case 'POST':
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = Util::buildHttpQuery($postfields);
break;
case 'DELETE':
$options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
break;
case 'PUT':
$options[CURLOPT_CUSTOMREQUEST] = 'PUT';
break;
}

if (in_array($method, ['GET', 'PUT', 'DELETE']) && !empty($postfields)) {
$options[CURLOPT_URL] .= '?' . Util::buildHttpQuery($postfields);
}


$curlHandle = curl_init();
curl_setopt_array($curlHandle, $options);
$response = curl_exec($curlHandle);

// Throw exceptions on cURL errors.
if (curl_errno($curlHandle) > 0) {
throw new TwitterOAuthException(curl_error($curlHandle), curl_errno($curlHandle));
}

$this->response->setHttpCode(curl_getinfo($curlHandle, CURLINFO_HTTP_CODE));
$parts = explode("\r\n\r\n", $response);
$responseBody = array_pop($parts);
$responseHeader = array_pop($parts);
$this->response->setHeaders($this->parseHeaders($responseHeader));

curl_close($curlHandle);

return $responseBody;
}

/**
* Get the header info to store.
*
* @param string $header
*
* @return array
*/
private function parseHeaders($header)
{
$headers = [];
foreach (explode("\r\n", $header) as $line) {
if (strpos($line, ':') !== false) {
list ($key, $value) = explode(': ', $line);
$key = str_replace('-', '_', strtolower($key));
$headers[$key] = trim($value);
}
}
return $headers;
}

/**
* Encode application authorization header with base64.
*
* @param Consumer $consumer
*
* @return string
*/
private function encodeAppAuthorization($consumer)
{
// TODO: key and secret should be rfc 1738 encoded
$key = $consumer->key;
$secret = $consumer->secret;
return base64_encode($key . ':' . $secret);
}
}

+ 10
- 0
addon/brigada/funciones/twitter/src/TwitterOAuthException.php View File

@@ -0,0 +1,10 @@
<?php

namespace Abraham\TwitterOAuth;

/**
* @author Abraham Williams <abraham@abrah.am>
*/
class TwitterOAuthException extends \Exception
{
}

+ 115
- 0
addon/brigada/funciones/twitter/src/Util.php View File

@@ -0,0 +1,115 @@
<?php
/**
* The MIT License
* Copyright (c) 2007 Andy Smith
*/
namespace Abraham\TwitterOAuth;

class Util
{
/**
* @param $input
*
* @return array|mixed|string
*/
public static function urlencodeRfc3986($input)
{
$output = '';
if (is_array($input)) {
$output = array_map([__NAMESPACE__ . '\Util', 'urlencodeRfc3986'], $input);
} elseif (is_scalar($input)) {
$output = rawurlencode($input);
}
return $output;
}

/**
* @param string $string
*
* @return string
*/
public static function urldecodeRfc3986($string)
{
return urldecode($string);
}

/**
* This function takes a input like a=b&a=c&d=e and returns the parsed
* parameters like this
* array('a' => array('b','c'), 'd' => 'e')
*
* @param mixed $input
*
* @return array
*/
public static function parseParameters($input)
{
if (!isset($input) || !$input) {
return [];
}

$pairs = explode('&', $input);

$parameters = [];
foreach ($pairs as $pair) {
$split = explode('=', $pair, 2);
$parameter = Util::urldecodeRfc3986($split[0]);
$value = isset($split[1]) ? Util::urldecodeRfc3986($split[1]) : '';

if (isset($parameters[$parameter])) {
// We have already recieved parameter(s) with this name, so add to the list
// of parameters with this name

if (is_scalar($parameters[$parameter])) {
// This is the first duplicate, so transform scalar (string) into an array
// so we can add the duplicates
$parameters[$parameter] = [$parameters[$parameter]];
}

$parameters[$parameter][] = $value;
} else {
$parameters[$parameter] = $value;
}
}
return $parameters;
}

/**
* @param $params
*
* @return string
*/
public static function buildHttpQuery($params)
{
if (!$params) {
return '';
}

// Urlencode both keys and values
$keys = Util::urlencodeRfc3986(array_keys($params));
$values = Util::urlencodeRfc3986(array_values($params));
$params = array_combine($keys, $values);

// Parameters are sorted by name, using lexicographical byte value ordering.
// Ref: Spec: 9.1.1 (1)
uksort($params, 'strcmp');

$pairs = [];
foreach ($params as $parameter => $value) {
if (is_array($value)) {
// If two or more parameters share the same name, they are sorted by their value
// Ref: Spec: 9.1.1 (1)
// June 12th, 2010 - changed to sort because of issue 164 by hidetaka
sort($value, SORT_STRING);
foreach ($value as $duplicateValue) {
$pairs[] = $parameter . '=' . $duplicateValue;
}
} else {
$pairs[] = $parameter . '=' . $value;
}
}
// For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
// Each name-value pair is separated by an '&' character (ASCII code 38)
return implode('&', $pairs);
}
}

+ 26
- 0
addon/brigada/funciones/twitter/src/Util/JsonDecoder.php View File

@@ -0,0 +1,26 @@
<?php

namespace Abraham\TwitterOAuth\Util;

/**
* @author louis <louis@systemli.org>
*/
class JsonDecoder
{
/**
* Decodes a JSON string to stdObject or associative array
*
* @param string $string
* @param bool $asArray
*
* @return array|object
*/
public static function decode($string, $asArray)
{
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
return json_decode($string, $asArray, 512, JSON_BIGINT_AS_STRING);