summaryrefslogtreecommitdiff
path: root/bin/wiki/ImportarExperiencia/import.php
blob: d45e7e08c4d056e38479091b078c546189ed1f6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
<?php
# ----
# Copyright (C) 2013-2020 - Reevo Project (http://reevo.org)
# License: Affero GPL version 3 - http://www.gnu.org/licenses/agpl.html
# ES: Este script importa los datos de usuario desde el perfil de Elgg hacia la paginade usuario en MW
# ----


// error_reporting(-1);
// Load all the stuff
require_once( __DIR__ . '/../vendor/autoload.php' );
require_once( __DIR__ .'/../../../etc/global_config.php' );
//
// // Log in to a wiki
$api = new \Mediawiki\Api\MediawikiApi( $wgServer .'/api.php' );
$api->login( new \Mediawiki\Api\ApiUser( $REEVO_WIKI_API_USER, $REEVO_WIKI_API_PASS ) );
$services = new \Mediawiki\Api\MediawikiFactory( $api );

$uid = $_POST['uid'];
$titulo = $_POST['titulo'];

$strJsonFileContents = file_get_contents("export-mapa.json");
$fullarray = json_decode($strJsonFileContents, true);
// print_r($fullarray); // print array
$key = array_search((int)$uid, array_column($fullarray, '#'));
if ($key) {
  $array = $fullarray[$key];

  $media_urls = array();
  $media_videos = array();
  $media_images = array();
  $file = fopen('export-mapa-media.csv', 'r');
  while (($line = fgetcsv($file)) !== FALSE) {
    //$line is an array of the csv elements
    if ($line[0] == $uid) {
      if(filter_var($line[1], FILTER_VALIDATE_URL) !== FALSE){
        # si es una URL, lo cargamos en un array de URLs. Diferencia los videos...
        if (strpos($line[1], 'www.youtube.com') !== false || strpos($line[1], 'youtu.be') !== false || strpos($line[1], 'vimeo.com') !== false) {
          array_push($media_videos,$line[1]);
        } else {
          array_push($media_urls,$line[1]);
        }
      } else {
        # si NO es una URL, lo cargamos en un array de URLs
        array_push($media_images,$line[1]);
      }
    }
  }
  fclose($file);
  $text = ImportarExperiencia($array, $titulo, $uid, $services, $media_urls, $media_images, $media_videos);

}


function get_title($url){
  $doc = new DOMDocument();
  @$doc->loadHTMLFile($url);
  $xpath = new DOMXPath($doc);
  return $xpath->query('//title')->item(0)->nodeValue;
}


function ImportarExperiencia($array, $titulo, $id, $services, $media_urls, $media_images, $media_videos) {


  $content  = '{{Experiencia
|experiencia:oldid='.$id.'
|experiencia:descripcion='.$array["DESCRIPCION"].'

'.$array["CATEGORIA"].'

|experiencia:contacto-url='.$array["URL"].'
|experiencia:contacto-email='.$array["EMAIL"].'
|experiencia:contacto-telefono='.$array["TELEFONO"].'

|experiencia:lugar='.$array["LATITUD"].', '.$array["LONGITUD"].'
|experiencia:lugar-pais=
|experiencia:lugar-provincia=
|experiencia:lugar-ciudad=
|experiencia:lugar-calle='.$array["UBICACION"].'

|experiencia:info-inicio='.$array["INICIO"].'
|experiencia:info-niveleconomico='.$array["SOCIOECONOMICO"].'
|experiencia:info-contextosocial='.$array["CONTEXTO"].'
|experiencia:info-participantes='.$array["PARTICIPANTES"].'

|experiencia:info-corrientes=
|experiencia:info-certificacion='.$array["CERTIFICACION"].'
|experiencia:info-tipoeducacion='.$array["TIPO"].'
|experiencia:info-niveleducacion='.$array["NIVEL"].'
|experiencia:info-lucro='.$array["LUCRO"].'
|experiencia:info-virtual='.$array["VIRTUAL"].'
}}';

if ($array["CARACTERISTICAS"]) {
$content .= "

== Características ==
{$array['CARACTERISTICAS']}";
};

if ($array["HISTORIA"]) {
$content .= "

== Historia ==
{$array['HISTORIA']}";
};

if ($array["PRACTICAS"]) {
$content .= "

== Prácticas o acciones principales ==
{$array['PRACTICAS']}";
};

if ($array["FUNDAMENTOS"]) {
$content .= "

== Fundamentos teóricos ==
{$array['FUNDAMENTOS']}";
};

if ($array["INFORMACIONEXTRA"]) {
$content .= "

== Información adicional ==
{$array['INFORMACIONEXTRA']}
";
};

if ($media_videos) {
  $content .= "

== Videos ==
";
  foreach ($media_videos as $key => $value) {
    // $titleurl = get_title($value);
    $content .= "{{#evu:$value}} \n";
  }
};


if ($media_urls) {
  $content .= "
== Referencias externas ==
";
  foreach ($media_urls as $key => $value) {
    $titleurl = get_title($value);
    $content .= "* [$value $titleurl] \n";
  }
};


if ($media_images) {
  $content .= "

== Imagenes ==
<gallery>
";
  foreach ($media_images as $key => $value) {
    $image = ImportarImagen($value,$titulo,$key,$services);
    $content .= "$image \n";
  }
  $content .= "</gallery>";

};




$content .= "
[[Categoría:Experiencia]]
[[Categoría:Experiencia migrada]]
";

  $newContent = new \Mediawiki\DataModel\Content( $content );
  $title = new \Mediawiki\DataModel\Title( 'Experiencia:' . $titulo );
  $identifier = new \Mediawiki\DataModel\PageIdentifier( $title );
  $revision = new \Mediawiki\DataModel\Revision( $newContent, $identifier );
  $log = $services->newRevisionSaver()->save( $revision );
  // print_r($log, FALSE);


  $lines = file('./procesados.log');
  $existe = FALSE;
	foreach ($lines as $lineNumber => $line) {
			$exp = explode(',',$line);
			if ($exp[0] == $id) {
        $existe = TRUE;
        $lineNumber = $lineNumber;
				break;
			}
	}
  if ($existe === FALSE) {
    # Solo lo agrego al log si antes no estaba
    $file = 'procesados.log';
    $estado = 'si';
    $salida = "$id,$titulo,$estado\r\n";
    file_put_contents($file, $salida, FILE_APPEND);
  } else {
    # Si ya estaba en el log, cambio su estado
    $fileName = 'procesados.log';
    $estado = 'si';
    $salida = "$id,$titulo,$estado\r\n";
    // Load file into array
    $contents = file($fileName);
    // Replace line
    $contents[$lineNumber] = $salida;
    // Implode and save
    file_put_contents($fileName, implode('',$contents));
  }

  $proximo = $id + 1;
  $html = '<br/><p>Se importó: '.$titulo.' ('.$id.')</p><br/>
  <a target="_blank" href="/index.php?title=Experiencia:'.$titulo.'&action=formedit" class="btn btn-primary active" role="button" aria-pressed="true">Editar en el wiki</a>
  <a href="/ImportarExperiencia/?id='.$proximo.'" class="btn btn-secondary active" role="button" aria-pressed="true">Importar siguiente experiencia</a>
  <a href="/ImportarExperiencia/" class="btn btn-warning active" role="button" aria-pressed="true">Importar otra experiencia</a>';

  return $html;
}

function ImportarImagen($filename,$pagename,$numero,$services) {
  // Definimos el nombre del archivo de la imagen
  $num = sprintf("%02d", $numero);
  $extension = explode('.', $filename);
  $pagetitle = 'Experiencia-'. $pagename . '-'.$num.'.'.$extension[1];
  $localfile = '/srv/reevo-web/files/mapa/'.$filename;
  $snaphot_pagecontent = 'Imagen importada del mapa de REEVO para [[Experiencia:'. $pagename .']]';
  $snaphot_desc = 'Imagen importada del mapa de REEVO para [[Experiencia:'. $pagename .']]';
  $fileUploader = $services->newFileUploader();
  $fileUploader->setChunkSize( 1024 * 1024 * 10 );
  // exec("cp /srv/reevo-web/files/red/recext/{$elggid}/`ls /srv/reevo-web/files/red/recext/{$elggid}/` /tmp/imagen && convert /tmp/imagen /tmp/imagen.jpg");
  $fileUploader->upload( $pagetitle, $localfile, $snaphot_pagecontent, $snaphot_desc );

  return $pagetitle;

}

function accessProtected($obj, $prop) {
  $reflection = new ReflectionClass($obj);
  $property = $reflection->getProperty($prop);
  $property->setAccessible(true);
  return $property->getValue($obj);
}

?>



<!DOCTYPE html>
<html lang="en">
	<head>
		<!-- ================================================== -->
		<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

		<!-- ================================================== -->
		<!-- Optional support for older (IE9 or older) Microsoft browsers: -->
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<!-- ================================================== -->
		<title>REEVO - Importar Experiencia</title>
		<!-- ================================================== -->
		<!-- Bootstrap CSS: -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
		<!-- ================================================== -->
		<!-- Bootstrap CSS optional theme: -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
		<!-- ================================================== -->
		<!-- Optional Font Awesome library: -->
		<link rel="stylesheet" href="https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css"/>
		<!--
			Font Awesome attribution is appreciated, but not required, as of version 3.0: "Font Awesome by Dave Gandy - http://fontawesome.io".
			Font Awesome CDN: https://fontawesomecdn.com/
			Font Awesome cheat sheet: http://fontawesome.io/cheatsheet/
			Font Awesome examples: http://fontawesome.io/examples/
			Font Awesome icons: http://fontawesome.io/icons/
		-->
		<!-- ================================================== -->
		<style>
			* {/*INCLUDE BORDER AND PADDING WITHIN HEIGHT AND WIDTH*/
				box-sizing: border-box;
				}
			article, aside, figure, footer, header, main, nav, section {/*BACKWARD COMPATIBILITY*/
				display: block;
				}
			blockquote,body,button,code,div,footer,h1,h2,h3,h4,h5,h6,html,i,img,li,.nowrap,ol,p,pre,.row,ul {/*CSS RESET*/
				margin:0;
				max-width: 100%;
				padding:0;
				word-wrap: break-word;
				}
			unknown-element-name {/*UNKNOWN ELEMENT*/
				display: block;
				}

			pre {
		    white-space: pre-wrap;       /* Since CSS 2.1 */
		    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
		    white-space: -pre-wrap;      /* Opera 4-6 */
		    white-space: -o-pre-wrap;    /* Opera 7 */
		    word-wrap: break-word;       /* Internet Explorer 5.5+ */
				}
		</style>
	</head>
	<body>
		<div class="panel panel-default col-md-8 col-md-offset-2">
			<div class="panel-body">

	 <h1>Importación completa</h1>

   <?php echo $text;?>

	</body>
	<!-- ================================================== -->
	<!-- JavaScript at bottom for faster page loading. -->
	<!-- ================================================== -->
	<!-- jQuery library: -->
	<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
	<!-- <script src="js/bootstrap.min.js"></script> -->
	<!-- ================================================== -->
	<!-- jQuery library: -->
	<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
	<script type="application/javascript">window.jQuery || document.write('<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">\x3C/script>')</script>
	<script type="application/javascript">window.jQuery || document.write('<script src="../jquery.min.js">\x3C/script>')</script>
	<script>
		$(document).ready(function(){
			});
	</script>
	<!-- ================================================== -->
	<!-- Bootstrap JavaScript library: -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<script type="application/javascript">$.fn.modal || document.write('<script src="../bootstrap.min.js">\x3C/script>')</script>
	<!-- ================================================== -->
	<!-- Bootstrap hack for Windows 8 IE10 viewport Surface/desktop bug (local fall-back) -->
	<script src="../ie10-viewport-bug-workaround.js"></script>
	<!-- ================================================== -->
	<!-- Optional support for handling unknown elements in older browsers: -->
	<!--[if lt IE 9]>
		<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
		<script src="/js/html5shiv.js"></script>
	<![endif]-->
	<!-- ================================================== -->
</html>