source: sipes/0.3-modules/situacion_actual_preliminar/situacion_actual_preliminar.module @ 153d323

stable
Last change on this file since 153d323 was 153d323, checked in by Sipes Apn <root@…>, 7 años ago

se agrego el tipo de nodo en el condicional de la consulta SQL

  • Propiedad mode establecida a 100755
File size: 115.8 KB
Línea 
1
2<?php
3  /**
4  * Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana
5  * @file situacion_actual_preliminar.module
6  * Drupal part Module to code ente planificador module
7  * Copyright 2011 Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana (CENDITEL)
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22  *
23  * @author Cenditel Merida - Phd. Juan Vizcarrondo
24  * @date 2017-06-23 // (a&#241;o-mes-dia)
25  * @version 0.3 // (0.3)
26  *
27  */
28
29/*
30 * Implementation of _situacion_actual_preliminar_get_planns()
31 * Obtiene los tipos de planes en la interpretacion
32 */
33function _situacion_actual_preliminar_get_planns() {
34  //permitir version preliminar del tipo de ente menores o iguales a $entes_version
35  //En este caso $entes_version_min = 1 y $entes_version_max = 2, solo los entes tipos >= 1 y <= 2 tienen version preliminar
36  $entes_version_min = 1;
37  $entes_version_max = 2;
38  //permitir situacion actual del tipo de ente menores o iguales a $entes_situacion_actual
39  //En este caso $entes_situacion_actual_min = 1 y $entes_situacion_actual_max = 2, solo los entes tipos >= 1 y <= 2 tienen situacion actual
40  $entes_situacion_actual_min = 1;
41  $entes_situacion_actual_max = 2;
42  //permitir interpretacion del tipo de ente mayores o iguales a $entes_interpretacion
43  //En este caso $entes_version_min = 2 y $entes_version_max = 0, solo los entes tipos >= 2 tienen interpretacion
44  $entes_interpretacion_min = 3;
45  $entes_interpretacion_max = 0;
46  $planns = array(
47    'interpretacion' => array(
48      'plan' => 'interpretacion',
49      'short' => 'vp',
50      'title' => t('Interpretación'),
51      'description' => t('Los entes micros añaden su interpretación de la explicación situacional'),
52      'title_long' => t('Interpretación preliminar de la explicación situacional'),
53      'title_ente' => t('Interpretación preliminar de la explicación situacional de @ente'),
54      'hierarchical' => 'children',
55      'hierarchical_ente' => 1,
56      'ente_type' => array(),
57    ),
58    'version' => array(
59      'plan' => 'version',
60      'short' => 'vp',
61      'title' => t('Versión preliminar'),
62      'description' => t('Los enten macro añaden su versión preliminar de la explicación situacional'),
63      'title_long' => t('Versión preliminar de la explicación situacional'),
64      'title_ente' => t('Versión Preliminar de @ente'),
65      'hierarchical' => 'fathers',
66      'hierarchical_ente' => -1,
67      'ente_type' => array(),
68    ),
69    'situacion_actual' => array(
70      'plan' => 'situacion_actual',
71      'short' => 'sa',
72      'title' => t('Situación Actual'),
73      'description' => t('Los enten macro añaden su Situación Actual de la explicación situacional'),
74      'title_long' => t('Situación Actual de la explicación situacional'),
75      'title_ente' => t('Situación Actual de @ente'),
76      'hierarchical' => 'fathers',
77      'hierarchical_ente' => -1,
78      'ente_type' => array(),
79    ),
80  );
81  //se obtienen todos los tipos de entes
82  $hierarchical = variable_get('ente_planificador_hierarchical_count', 2);
83  for($i = 1; $i < $hierarchical + 1; $i++) {
84    if ((!$entes_version_min || $i >= $entes_version_min) && (!$entes_version_max || $i <= $entes_version_max)) {
85      $planns['version']['ente_type'][$i] = $i;
86    }
87    if ((!$entes_situacion_actual_min || $i >= $entes_situacion_actual_min) && (!$entes_situacion_actual_max || $i <= $entes_situacion_actual_max)) {
88      $planns['situacion_actual']['ente_type'][$i] = $i;
89    }
90    if ((!$entes_interpretacion_min || $i >= $entes_interpretacion_min) && (!$entes_interpretacion_max || $i <= $entes_interpretacion_max)) {
91      $planns['interpretacion']['ente_type'][$i] = $i;
92    }
93  }
94  return $planns;
95}
96
97/*
98 * Implementation of hook_ente_procesos_alter()
99 */
100function situacion_actual_preliminar_ente_procesos_alter(&$procesos, $type) {
101  if ($type == 'status') {
102    $procesos['explicacion'] = array(
103      'title' => t('Explicación Situacional'),
104      'description' => t('Explicación Situacional'),
105      'weight' => -10,
106    );
107  }
108  else {
109    $planns = _situacion_actual_preliminar_get_planns();
110    $weight = -10;
111    foreach ($planns as $plann) {
112      $procesos[$plann['plan']] = array(
113        'title' => $plann['title_long'],
114        'description' => $plann['description'],
115        'message' => 'Se podrá registrar y/o modificar la interpretación de la ' . $plann['title'] . ' desde %fecha hasta la fecha %fecha1',
116        'message_expire' => 'Registrar y/o modificar la interpretación de la ' . $plann['title'] . ' no se encuentra disponible, se podra realizar desde %fecha hasta la fecha %fecha1)',
117        'weight' => $weight,
118        'proceso' => 'explicacion',
119      );
120      $weight++;
121    }
122  }
123}
124
125/*
126 * Implementation of hook_menu()
127 */
128function situacion_actual_preliminar_menu() {
129  $items = array();
130  $items['planificacion/%ente_planificador_menu/explicacion'] = array(
131    'title' => t('Explicación Situacional'),
132    'page callback' => 'ente_planificador_view_situacion_explicacion',
133    'page arguments' => array(1, 'version'),
134    'access callback' => 'tipo_plan_load',
135    'access arguments' => array('version'),
136    'weight' => -9,
137    'type' => MENU_LOCAL_TASK,
138  );
139  $planns = _situacion_actual_preliminar_get_planns();
140  $i = -10;
141  foreach ($planns as $plann) {
142    if ($plann['plan'] != 'version') {
143      $items['planificacion/%ente_planificador_menu/explicacion/' . $plann['plan']] = array(
144        'title' => $plann['title'],
145        'page callback' => 'ente_planificador_view_situacion_explicacion',
146        'page arguments' => array(1, $plann['plan'], 4, 5),
147        'access callback' => 'tipo_plan_load',
148        'access arguments' => array($plann['plan']),
149        'weight' => $i,
150        'type' => MENU_LOCAL_TASK,
151      );
152      $i += 2;
153    }
154    else {
155      $items['planificacion/%ente_planificador_menu/explicacion/' . $plann['plan']] = array(
156        'title' => $plann['title'],
157        'type' => MENU_DEFAULT_LOCAL_TASK,
158        'weight' => -9,
159      );
160    }
161  };
162  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/agregar/descriptor'] = array(
163    'title' => t('Agregar descriptor'),
164    'page callback' => 'drupal_get_form',
165    'page arguments' => array('ente_planificador_descriptores_editar_form', 1, 3),
166    'access callback' => '_get_situacion_explicacion_acceso',
167    'access arguments' => array(1, 3),
168    'weight' => -8,
169    'type' => MENU_NORMAL_ITEM,
170  );
171  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/importar/descriptor'] = array(
172    'title' => t('Importar Descriptores'),
173    'page callback' => 'drupal_get_form',
174    'page arguments' => array('ente_planificador_descriptores_importar_form', 1, 3),
175    'access callback' => '_get_situacion_explicacion_importar_acceso',
176    'access arguments' => array(1, 3),
177    'weight' => -8,
178    'type' => MENU_NORMAL_ITEM,
179  );
180  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/descriptor'] = array(
181    'title' => t('Editar descriptor'),
182    'page callback' => 'drupal_get_form',
183    'page arguments' => array('ente_planificador_descriptores_editar_form', 1, 3, 4),
184    'access callback' => '_get_situacion_explicacion_acceso',
185    'access arguments' => array(1, 3, 4),
186    'weight' => -8,
187    'type' => MENU_NORMAL_ITEM,
188  );
189  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/eliminar'] = array(
190    'title' => t('Eliminar descriptor'),
191    'page callback' => 'drupal_get_form',
192    'page arguments' => array('ente_planificador_descriptores_eliminar_form', 1, 3, 4),
193    'access callback' => '_get_situacion_explicacion_acceso',
194    'access arguments' => array(1, 3, 4),
195    'weight' => -8,
196    'type' => MENU_NORMAL_ITEM,
197  );
198  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/causas'] = array(
199    'title' => t('Causas'),
200    'page callback' => 'drupal_get_form',
201    'page arguments' => array('ente_planificador_causas_seleccionar_form', 1, 3, 4),
202    'access callback' => '_get_situacion_explicacion_acceso',
203    'access arguments' => array(1, 3, 4),
204    'weight' => -8,
205    'type' => MENU_NORMAL_ITEM,
206  );
207  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/causas/ver'] = array(
208    'title' => t('Causas'),
209    'page callback' => '_ente_planificador_causas_ver',
210    'page arguments' => array( 1, 3, 4),
211    'access callback' => '_get_situacion_explicacion_acceso',
212    'access arguments' => array(1, 3, 4),
213    'weight' => -8,
214    'type' => MENU_NORMAL_ITEM,
215  );
216  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/causas/agregar'] = array(
217    'title' => t('Agregar Causas'),
218    'page callback' => 'drupal_get_form',
219    'page arguments' => array('ente_planificador_causas_editar_form', 1, 3, 4),
220    'access callback' => '_get_situacion_explicacion_acceso',
221    'access arguments' => array(1, 3, 4),
222    'weight' => -8,
223    'type' => MENU_NORMAL_ITEM,
224  );
225  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/causas/%lcausa'] = array(
226    'title' => t('Editar Causa'),
227    'page callback' => 'drupal_get_form',
228    'page arguments' => array('ente_planificador_causas_editar_form', 1, 3, 4, 6),
229    'access callback' => '_get_situacion_explicacion_acceso',
230    'access arguments' => array(1, 3, 4),
231    'weight' => -8,
232    'type' => MENU_NORMAL_ITEM,
233  );
234  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/cambios'] = array(
235    'title' => t('Editar descriptor'),
236    'page callback' => 'drupal_get_form',
237    'page arguments' => array('ente_planificador_cambios_situacion_actual_seleccionar_form', 1, 3, 4),
238    'access callback' => '_get_situacion_explicacion_acceso',
239    'access arguments' => array(1, 3, 4),
240    'weight' => -8,
241    'type' => MENU_NORMAL_ITEM,
242  );
243  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/cambios/ver'] = array(
244    'title' => t('Causas'),
245    'page callback' => '_ente_planificador_cambios_situacion_actual_ver',
246    'page arguments' => array( 1, 3, 4),
247    'access callback' => '_get_situacion_explicacion_acceso',
248    'access arguments' => array(1, 3, 4),
249    'weight' => -8,
250    'type' => MENU_NORMAL_ITEM,
251  );
252  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/cambios/agregar'] = array(
253    'title' => t('Agregar Cambios'),
254    'page callback' => 'drupal_get_form',
255    'page arguments' => array('ente_planificador_cambios_editar_form', 1, 3, 4),
256    'access callback' => '_get_situacion_explicacion_acceso',
257    'access arguments' => array(1, 3, 4),
258    'weight' => -8,
259    'type' => MENU_NORMAL_ITEM,
260  );
261  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/%node/cambios/%lcambios'] = array(
262    'title' => t('Editar Cambio'),
263    'page callback' => 'drupal_get_form',
264    'page arguments' => array('ente_planificador_cambios_editar_form', 1, 3, 4, 6),
265    'access callback' => '_get_situacion_explicacion_acceso',
266    'access arguments' => array(1, 3, 4),
267    'weight' => -8,
268    'type' => MENU_NORMAL_ITEM,
269  );
270  $items['planificacion_cambios_pdlp_js'] = array(
271    'title' => 'Ente Planificador',
272    'page callback' => 'planificacion_cambios_pdlp_js',
273    'access arguments' => array('ver planificador'),
274    'type' => MENU_CALLBACK,
275  );
276  $items['planificacion_importar_pdlp_js'] = array(
277    'title' => 'Ente Planificador',
278    'page callback' => 'planificacion_importar_pdlp_js',
279    'access arguments' => array('ver planificador'),
280    'type' => MENU_CALLBACK,
281  );
282  //configuracion Explicación Situacional
283  $items['admin/settings/ente_planificador/explicacion'] = array(
284    'title' => t('Explicación Situacional'),
285    'page callback' => 'drupal_get_form',
286    'page arguments' => array('situacional_actual_preliminar_admin_settings'),
287    'access arguments' => array('admin planificador'),
288    'type' => MENU_LOCAL_TASK,
289    'file' => 'situacional_actual_preliminar.admin.inc',
290  );
291  $items['admin/settings/ente_planificador/explicacion/configurar'] = array(
292    'title' =>  t('Configurar'),
293    'type' => MENU_DEFAULT_LOCAL_TASK,
294  );
295  /** Procesa el ajax del js **/
296  $items['planificacion_cambios_js'] = array(
297    'title' => 'Save Values to JS',
298    'page callback' => 'planificacion_cambios_js',
299    'access arguments' => array('ver planificador'),
300  );
301  /** ahah para el cambio de vista en el admin **/
302  $items['situacional_actual_preliminar_views_js'] = array(
303    'title' => 'Vista por tipo de proceso',
304    'page callback' => 'situacional_actual_preliminar_views_js',
305    'access arguments' => array('ver planificador'),
306    'type' => MENU_CALLBACK,
307  );
308  /** Importar datos **/
309  $items['planificacion/%ente_planificador_menu/explicacion/%tipo_plan/importar/%'] = array(
310    'title' => t('Importar Datos'),
311    'page callback' => 'situacion_actual_premilimar_importar_datos',
312    'page arguments' => array(1,3,5),
313    'access callback' => '_get_situacion_explicacion_acceso_hijos_importar',
314    'access arguments' => array(1, 3, 5),
315    'weight' => -8,
316    'type' => MENU_NORMAL_ITEM,
317  );
318  return $items;
319}
320
321/*
322 * Implementation of tipo_plan_load()
323 * Lee el tipo de plan para el menu
324 */
325function tipo_plan_load($id = 0) {
326  $plan = _situacion_actual_preliminar_get_planns();
327  return isset($plan[$id]) ? $plan[$id] : FALSE;
328}
329
330/*
331 * Implementation of tipo_plan_load()
332 * Lee la causa para el menu
333 */
334function lcausa_load($nid) {
335  if ($nid && is_numeric($nid)) {
336    $causa = node_load($nid);
337    if ($causa && $causa->type == 'causas') {
338      return $causa;
339    }
340  }
341  return FALSE;
342}
343
344/*
345 * Implementation of tipo_plan_load()
346 * Lee el cambio para el menu
347 */
348function lcambios_load($nid) {
349  if ($nid && is_numeric($nid)) {
350    $causa = node_load($nid);
351    if ($causa && $causa->type == 'cambios') {
352      return $causa;
353    }
354  }
355  return FALSE;
356}
357
358/*
359 * Implementation of ente_planificador_descriptores_importar_form()
360 * Importar descriptores
361 */
362function ente_planificador_descriptores_importar_form($form_state,$ente_planificador, $tipo_plan = array()) {
363  global $user;
364  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
365  $current_time = time();
366  $fecha = FALSE;
367  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
368    $fecha = TRUE;
369  }
370  if (!$fecha) {
371    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
372  }
373  else {
374    $ente = usuario_tiene_ente($user->uid);
375    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
376      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
377    }
378  }
379  drupal_set_title(t('Importar Descriptores'));
380  $year = variable_get('situacional_actual_preliminar_anho_creacion', 0);
381  $planns = _situacion_actual_preliminar_get_planns();
382  $plan = $planns['version'];
383  $descriptores_vp = _get_situacion_actual_listar_all_descriptores($ente_planificador->nid, $plan, $year);
384  $descriptores_sa = _get_situacion_actual_listar_all_descriptores($ente_planificador->nid, $tipo_plan, $year);
385  foreach($descriptores_vp as $id => $descriptor) {
386    if (isset($descriptores_sa[$id])) {
387      unset($descriptores_vp[$id]);
388    }
389
390  }
391  $form = array();
392  $header = array();
393  $header[] = t('Seleccionar');
394  $header[] = t('Descriptor');
395  $header[] = t('Categorización');
396  $header[] = t('Causas');
397  $header[] = t('Cambios de la situación actual');
398  $prefijo = '<table width="100%" style="border: 0;"><tr>';
399  foreach($header as $texto) {
400    $prefijo .= '<th>' . $texto . '&nbsp;</th>';
401  }
402  $prefijo .= '</tr>';
403  if (!count($descriptores_vp)) {
404      $prefijo .= '<tr><td colspan="' . count($header) . '">' . t('No se encontrarón Descriptores para importar') . '&nbsp;</td></tr></table>';
405      $form['seleccionar'] = array(
406        '#value' => $prefijo,
407      );
408  }
409  else {
410    foreach($descriptores_vp as $descriptor) {
411      $clasificiacion = array();
412      foreach($descriptor['clasificacion'] as $id) {
413        $term_load = taxonomy_get_term($id);
414        if ($term_load) {
415          $clasificiacion[] = $term_load->name;
416        }
417      }
418      $causas = array();
419      foreach ($descriptor['causas'] as $causa) {
420        $causas[] = $causa['body'];
421      }
422      $output = count($causas)? theme('item_list', $causas) : t('No se han agregado causas al descriptor');
423      $solucion = array();
424      foreach ($descriptor['cambios'] as $cambio) {
425        $solucion[] = $cambio['body'];
426      }
427      $output1 = count($solucion)? theme('item_list', $solucion) : t('No se encontrarón cambios en la situación actual del descriptor');
428      $suffix = '</td><td>' . $descriptor['body'] . '</td><td>' . theme('item_list', $clasificiacion) . '</td><td>' . $output . ' </td><td>' . $output1 . ' </td></tr>';
429      $form['seleccionar_' . $descriptor['nid']] = array(
430        '#type' => 'checkbox',
431        '#title' => '',
432        '#default_value' => FALSE,
433        '#prefix' => $prefijo . '<tr><td>',
434        '#suffix' =>$suffix,
435      );
436      $prefijo = '';
437
438
439    }
440    $form['seleccionar_' . $descriptor['nid']]['#suffix'] .= '</table>';
441  }
442  $form['#descriptores'] = $descriptores_vp;
443  $form['#ente_planificador'] = $ente_planificador;
444  $form['#tipo_plan'] = $tipo_plan;
445  $form['#tipo_plan_from'] = $plan;
446  $form['buttons']['#weight'] = 100;
447  $form['buttons']['submit'] = array(
448    '#type' => 'submit',
449    '#value' => t('Submit'),
450    '#weight' => 20
451  );
452  $form['buttons']['cancel'] = array(
453    '#type' => 'submit',
454    '#value' => t('Cancel'),
455    '#weight' => 21
456  );
457
458  return $form;
459}
460
461/*
462 * Implementation of ente_planificador_descriptores_editar_form_submit()
463 */
464function ente_planificador_descriptores_importar_form_submit($form, &$form_state) {
465  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
466  if ($op == t('Cancel')) {
467    return;
468  }
469  $descriptores_values = $form_state['values'];
470  module_load_include('inc', 'node', 'node.pages');
471  $descriptores = $form['#descriptores'];
472  $causas = array();
473  $i = 0;
474  foreach($descriptores as $descriptor) {
475    if ($descriptores_values['seleccionar_' . $descriptor['nid']]) {
476      $node = node_load($descriptor['nid']);
477      if ($node->nid) {
478        $campo = 'field_' . $node->type . '_' .$form['#tipo_plan']['short'];
479        $node->{$campo} = array();
480        $node->{$campo}[]['value'] = 1;
481        foreach ($descriptor['causas'] as $causa) {
482          $causas[$causa['nid']] = $causa['nid'];
483        }
484        node_object_prepare($node);
485        $node->log = t('Se importo el descriptor desde @plan', array('@plan' => $form['#tipo_plan_from']['title']));
486        $node->revision = 1;
487        node_save($node);
488        $i++;
489      }
490    }
491    foreach($causas as $nid) {
492      $node = node_load($nid);
493      if ($node->nid) {
494        $campo = 'field_' . $node->type . '_' .$form['#tipo_plan']['short'];
495        $node->{$campo} = array();
496        $node->{$campo}[]['value'] = 1;
497        node_object_prepare($node);
498        $node->log = t('Se importo la causa desde @plan', array('@plan' => $form['#tipo_plan_from']['title']));
499        $node->revision = 1;
500        node_save($node);
501      }
502    }
503  }
504  drupal_set_message(t('Se importarón @cantidad descriptores desde @tipo_plan', array('@cantidad' => $i, '@tipo_plan' => $form['#tipo_plan_from']['title'])));
505}
506
507/*
508 * Implementation of ente_planificador_descriptores_editar_form()
509 * Agregar o editar descriptores
510 */
511function ente_planificador_descriptores_editar_form($form_state, $ente_planificador,  $tipo_plan = array(), $node = 0) {
512  global $user;
513  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
514  $current_time = time();
515  $fecha = FALSE;
516  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
517    $fecha = TRUE;
518  }
519  if (!$fecha) {
520    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
521  }
522  else {
523    $ente = usuario_tiene_ente($user->uid);
524    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
525      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
526    }
527  }
528  $titulo = t('Modificar Descriptor');
529  if (!$node) {
530    $titulo = t('Agregar Descriptor');
531    $node = new stdClass();
532    $node->body = '';
533    $node->type = 'descriptores';
534    $node->uid = $user->uid;
535    $node->title = 'Descriptor-' . $ente_planificador->nid . '-' . time();
536    $node->field_descriptores_planificador[0]['nid'] = $ente_planificador->nid;
537    $campo = 'field_' . $node->type . '_' . $tipo_plan['short'];
538    $node->{$campo}[0]['value'] = 1;
539  }
540  drupal_set_title($titulo);
541  $form = array();
542  $form['#ente_planificador'] = $ente_planificador;
543  $form['#node'] = $node;
544  if (variable_get('situacion_actual_acronimo', false)) {
545    $form['title'] = array(
546      '#type' => 'textfield',
547      '#title' => t('Acrónimo del Descriptor'),
548      '#required' => TRUE,
549      '#default_value' => $node->title,
550      '#maxlength' => 255,
551      '#weight' => -5,
552      '#description' => t('Introduzca el acrónimo del descriptor para facilitar su busqueda. Es deseable que este sea único para facilitar su distinción entre otros descriptores.'),
553    );
554  }
555  $form['descriptor'] = array(
556    '#type' => 'textarea',
557    '#title' => t('Descriptor'),
558    '#description' => t('Introduzca el Descriptor de la situación actual.'),
559    '#default_value' => $node->body,
560    '#required' => TRUE,
561  );
562  //Se agregan otros campos
563  $node_type = content_types($form['#node']->type);
564  $fields = $node_type['fields'];
565  $field_form = array();
566  $fields_form = array();
567  $arreglo = array(
568    'field_descriptores_clasificacion' => 'field_descriptores_clasificacion',
569  );
570  if (is_array($fields) && count($fields)) {
571    foreach($fields as $field_id => $field) {
572      if (array_key_exists($field_id, $arreglo)) {
573        $field_form[] = $field_id;
574        $fields_form[] = $field_id;
575      }
576    }
577  }
578  if (is_array($field_form) && count($field_form)) {
579    module_load_include('inc', 'content', 'includes/content.node_form');
580    foreach ($field_form as $field_id) {
581      $field = content_fields($field_id, $form['#node']->type);
582      $form['#field_info'][$field_id] = $field;
583      $form += (array) content_field_form($form, $form_state, $field);
584    }
585  }
586  $form['#' . $form['#node']->type . '_campos'] = $fields;
587  $form['#' . $form['#node']->type . '_fields'] = $fields_form;
588  $form['buttons']['#weight'] = 100;
589  $form['buttons']['submit'] = array(
590    '#type' => 'submit',
591    '#value' => t('Submit'),
592    '#weight' => 20
593  );
594  $form['buttons']['cancel'] = array(
595    '#type' => 'submit',
596    '#value' => t('Cancel'),
597    '#weight' => 21
598  );
599  return $form;
600}
601
602/*
603 * Implementation of ente_planificador_descriptores_editar_form_validate()
604 * Validar Agregar o editar descriptores
605 */
606function ente_planificador_descriptores_editar_form_validate($form, &$form_state) {
607  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
608  if ($op == t('Cancel')) {
609    if ($_REQUEST['destination']) {
610      $redirect = $_REQUEST['destination'];
611    }
612    else {
613      // add redirect
614      $redirect = $_GET['q'];
615    }
616    drupal_goto($redirect);
617    return;
618  }
619  if (trim($form_state['values']['descriptor']) == '') {
620    form_set_error('descriptor', t('Debe agregar el Descriptor de la situación actual'));
621  }
622  return;
623}
624
625/*
626 * Implementation of ente_planificador_descriptores_editar_form_submit()
627 */
628function ente_planificador_descriptores_editar_form_submit($form, &$form_state) {
629  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
630  if ($op == t('Cancel')) {
631    return;
632  }
633  module_load_include('inc', 'node', 'node.pages');
634  $node = $form['#node'];
635  node_object_prepare($node);
636  $form_state['values']['descriptor'] = check_plain($form_state['values']['descriptor']);
637  if (variable_get('situacion_actual_acronimo', false)) {
638    $node->title = check_plain($form_state['values']['title']);
639  }
640  else {
641    $node->title = substr($form_state['values']['descriptor'], 0, 244);
642  }
643  $node->body = $form_state['values']['descriptor'];
644  //crear una nueva revision
645  $nuevo = TRUE;
646  if ($node->nid) {
647    $nuevo = FALSE;
648    $node->log = t('Modificados los datos del descriptor @date', array('@date' => date('d-m-Y', time())));
649    $node->revision = 1;
650  }
651  $node->field_descriptores_year[0]['value'] = variable_get('situacional_actual_preliminar_anho_creacion', 0);
652  $field_form = $form['#' . $form['#node']->type . '_fields'];
653
654  if (module_exists('hs_content_taxonomy')) {
655    foreach ($form['#field_info'] as $field_name => $field_info) {
656      if ($field_info['widget']['type'] == 'content_taxonomy_hs') {
657        // Change format of values to the one Content Taxonomy expects
658        if (is_array($form_state['values'][$field_name]['tids'])) {
659          $values = array();
660          foreach($form_state['values'][$field_name]['tids'] as $tid) {
661            $values[] = array('value' => $tid);
662            array_unshift($form_state['values'][$field_name], array('value' => $tid));
663          }
664          $form_state['values'][$field_name]['tids'] = $values;
665        }
666        else {
667          $values[] = array('value' => $form_state['values'][$field_name]['tids']);
668          array_unshift($form_state['values'][$field_name],array('value' => $form_state['values'][$field_name]['tids']));
669          $form_state['values'][$field_name]['tids'] = $values;
670        }
671      }
672    }
673  }
674  if (module_exists('hs_content_taxonomy_description')) {
675    foreach ($form['#field_info'] as $field_name => $field_info) {
676      if ($field_info['widget']['type'] == 'content_taxonomy_hsd') {
677        // Change format of values to the one Content Taxonomy expects
678        if (is_array($form_state['values'][$field_name]['tids'])) {
679          $values = array();
680          foreach($form_state['values'][$field_name]['tids'] as $tid) {
681            $values[] = array('value' => $tid);
682            array_unshift($form_state['values'][$field_name], array('value' => $tid));
683          }
684          $form_state['values'][$field_name]['tids'] = $values;
685        }
686        else {
687          $values[] = array('value' => $form_state['values'][$field_name]['tids']);
688          array_unshift($form_state['values'][$field_name],array('value' => $form_state['values'][$field_name]['tids']));
689          $form_state['values'][$field_name]['tids'] = $values;
690        }
691      }
692    }
693  }
694  module_load_include('inc', 'node', 'node.pages');
695  $form_values = $form_state['values'];
696  if (is_array($field_form) && count($field_form)) {
697    foreach ($field_form as $field_id) {
698      if (isset($form_values[$field_id]) && is_array($form_values[$field_id])) {
699        foreach($form_values[$field_id] as $id => $value) {
700          if (is_numeric($id) && isset($form_values[$field_id][$id]['_error_element'])) {
701            unset($form_values[$field_id][$id]['_error_element']);
702          }
703        }
704        $node->{$field_id} = $form_values[$field_id];
705      }
706    }
707  }
708  node_save($node);
709  $form['#node'] = $node;
710  if ($nuevo) {
711    drupal_set_message(t('Se agregó el descriptor @title', array('@title' => $node->body)));
712  }
713  else {
714    drupal_set_message(t('Se modificó el descriptor @title', array('@title' => $node->body)));
715  }
716}
717
718/**
719 * Implementation of ente_planificador_descriptores_eliminar_form()
720 * Eliminar descriptores
721 */
722function ente_planificador_descriptores_eliminar_form($form_state, $ente_planificador,  $tipo_plan = array(), $descriptor = 0) {
723  global $user;
724  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
725  $current_time = time();
726  $fecha = FALSE;
727  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
728    $fecha = TRUE;
729  }
730  if (!$fecha) {
731    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
732  }
733  else {
734    $ente = usuario_tiene_ente($user->uid);
735    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
736      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
737    }
738  }
739  $form = array();
740  $form['#node'] = $descriptor;
741  $form['#ente_planificador'] = $ente_planificador;
742  $form['#tipo_plan'] = $tipo_plan;
743  $form['#ac'] = $ac;
744  $message = t('Esta seguro de eliminar el descriptor @nombre?', array('@nombre' => $descriptor->body));
745  $caption = '<p>'. t('This action cannot be undone.') .'</p>';
746  $return_path = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'];
747  return confirm_form($form, $message, $return_path, $caption, t('Eliminar'));
748}
749
750/**
751 * Implementation of ente_planificador_descriptores_eliminar_form_submit().
752 * Process funcion delete descriptores.
753 */
754function ente_planificador_descriptores_eliminar_form_submit($form, &$form_state) {
755  module_load_include('inc', 'node', 'node.pages');
756  $descriptor = $form['#node'];
757  $campo = 'field_descriptores_' . $form['#tipo_plan']['short'];
758  $descriptor->{$campo}[0]['value'] = 0;
759  $descriptor->log = t('Se elimino el descriptor de la fase (@fase) @date', array('@fase' => $form['#tipo_plan']['plan'], '@date' => date('d-m-Y', time())));
760  $descriptor->revision = 1;
761  node_save($descriptor);
762  drupal_set_message(t('Se eliminó el descriptor @title', array('@title' => $descriptor->body)));
763}
764
765/*
766 * Implementation of _sap_tipo_causa()
767 * list causes type
768 */
769function _sap_tipo_causa() {
770  $type = array(
771    'rule' => t('Rule'),
772    'accumulation' => t('Accumulation'),
773    'flow' => t('Flow'),
774  );
775  return $type;
776}
777
778/*
779 * Implementation of _sap_nivel_control()
780 * list causes level
781 */
782function _sap_nivel_control() {
783  $nivel = array(
784    'control' => t('Under absolute control of the actors planners'),
785    'shared' => t('Under shared control with other actors'),
786    'out' => t('Beyond the control of planners actors'),
787  );
788  return $nivel;
789}
790
791/*
792 * Implementation of _ente_planificador_causas_ver()
793 * Consultar las causas de un descriptor
794 */
795function _ente_planificador_causas_ver($ente_planificador,  $tipo_plan = array(), $descriptor = 0) {
796  global $user;
797  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
798  $current_time = time();
799  $fecha = FALSE;
800  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
801    $fecha = TRUE;
802  }
803  if (!$fecha) {
804    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
805  }
806  else {
807    $ente = usuario_tiene_ente($user->uid);
808    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
809      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
810    }
811  }
812  drupal_set_title(t('Causas del descriptor "@name"', array('@name' => $descriptor->body)));
813  //se obtienen las causas que han sido seleccionadas
814  $causas_select = array();
815  $causas_sql = array();
816  $causas_input = array();
817  $acceso = _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan, $descriptor);
818  $sql = "SELECT c.nid, n.title, nr.body, c.field_tipo_causa_value, c.field_causa_control_value FROM {content_type_causas} AS c INNER JOIN {node} AS n ON c.nid = n.nid AND c.vid = n.vid AND n.type = 'causas'  INNER JOIN {node_revisions} AS nr ON c.nid = nr.nid AND c.vid = nr.vid WHERE c.field_ente_planifiador_nid = %d AND c.field_causas_year_value = %d";
819  $sql .= ' AND c.field_causas_' . $tipo_plan['short'] . '_value = %d';
820  $inputs = array();
821  $inputs[] = $ente_planificador->nid;
822  $inputs[] = $descriptor->field_descriptores_year[0]['value'];
823  $inputs[] = 1;
824  foreach($descriptor->field_descriptores_causa as $causa) {
825    if ($causa['nid']) {
826      $causas_select[$causa['nid']] = 1;
827      $causas_sql[] = '%d';
828      $inputs[] = $causa['nid'];
829    }
830  }
831  if (count($causas_sql)) {
832    $sql .= ' AND c.nid IN (' . implode(',', $causas_sql) . ')';
833  }
834  $sql .= ' ORDER BY c.nid';
835  $result = db_query($sql, $inputs);
836  $causas = array();
837  $headers_table = array();
838  $headers_table[] = array('data' => t('Causa Critica'));
839  $headers_table[] = array('data' => t('Formas de Solución'));
840  $headers_table[] = array('data' => t('Tipo de Causa'));
841  $headers_table[] = array('data' => t('Nivel de Control'));
842  if ($acceso) {
843    $headers_table[] = array('data' => t('Acción'));
844  }
845  $rows = array();
846  $type = _sap_tipo_causa();
847  $level = _sap_nivel_control();
848  while($causa = db_fetch_object($result)) {
849    if (isset($causas_select[$causa->nid])) {
850      $causa_load = node_load($causa->nid);
851      $row = array();
852      $row[] = array('data' => $causa_load->body);
853      $solucions = array();
854      foreach($causa_load->field_causa_solucion as $solucion) {
855        $solucions[] = $solucion['value'];
856      }
857      $row[] = array('data' => theme('item_list', $solucions));
858      $row[] = array('data' => $type[$causa_load->field_tipo_causa[0]['value']]);
859      $row[] = array('data' => $level[$causa_load->field_causa_control[0]['value']]);
860      if ($acceso) {
861        $url = l(t('Editar Causa'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/causas/' . $causa_load->nid . '/editar');
862        if ($_REQUEST['destination']) {
863          $url = l(t('Editar Causa'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/causas/' . $causa_load->nid . '/editar', array('query' => array('destination' => $_REQUEST['destination'])));
864        }
865        $row[] = array('data' => $url);
866      }
867      $rows[] = $row;
868    }
869  }
870  if (!count($rows)) {
871    $row = array();
872    $row[] = array('data' => t('No se encontrarón causas para este descriptor'), 'colspan' => count($headers_table));
873    $rows[] = $row;
874  }
875  $url = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'];
876  $links = array();
877  //$links[] = l(t('Modificar Causas'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/causas', array('query' => array('destination' => $url)));
878  if ($acceso && $tipo_plan['plan'] != 'situacion_actual' && (count($ente_planificador->ente_planificador_hierarchical['children'])|| user_access('admin planificador'))) {
879    $links[] = l(t('Importar Causas usando Web semántica'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/causas', array('query' => array('destination' => $url)));
880    $links[] = l(t('Importar Causas'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/causas_texto', array('query' => array('destination' => $url)));
881
882  }
883  $links[] = l(t('Regresar'), $url);
884  return theme('table', $headers_table, $rows) . theme('item_list', $links);
885}
886
887/*
888 * Implementation of ente_planificador_causas_editar_form()
889 * Agregar o editar causas a descriptores
890 */
891function ente_planificador_causas_seleccionar_form($form_state, $ente_planificador,  $tipo_plan = array(), $descriptor = 0) {
892  global $user;
893  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
894  $current_time = time();
895  $fecha = FALSE;
896  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
897    $fecha = TRUE;
898  }
899  if (!$fecha) {
900    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
901  }
902  else {
903    $ente = usuario_tiene_ente($user->uid);
904    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
905      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
906    }
907  }
908  drupal_set_title(t('Agregar causas'));
909  $form = array();
910  //se obtienen las causas
911  $causas_select = array();
912  foreach($descriptor->field_descriptores_causa as $causa) {
913    if ($causa['nid']) {
914      $causas_select[$causa['nid']] = 1;
915    }
916  }
917  $sql = "SELECT c.nid, n.title, nr.body, c.field_tipo_causa_value, c.field_causa_control_value FROM {content_type_causas} AS c INNER JOIN {node} AS n ON c.nid = n.nid AND c.vid = n.vid AND n.type = 'causas' INNER JOIN {node_revisions} AS nr  ON c.nid = nr.nid AND c.vid = nr.vid WHERE c.field_ente_planifiador_nid = %d AND c.field_causas_year_value = %d";
918  $sql .= ' AND c.field_causas_' . $tipo_plan['short'] . '_value = %d ORDER BY c.nid';
919  $inputs = array();
920  $inputs[] = $ente_planificador->nid;
921  $inputs[] = $descriptor->field_descriptores_year[0]['value'];
922  $inputs[] = 1;
923  $result = db_query($sql, $inputs);
924  $causas = array();
925  $prefijo = '<table width="100%" style="border: 0;"><tr>';
926  $prefijo .= '<th>' . t('Seleccionar') . '&nbsp;</th><th>' . t('Causa Critica') . '&nbsp;</th><th>' . t('Formas de Solución') . '&nbsp;</th><th>' . t('Tipo de Causa') . '&nbsp;</th><th>' . t('Nivel de Control') . '&nbsp;</th><th>' . t('Acción') . '&nbsp;</th></tr>';
927  while($causa = db_fetch_object($result)) {
928    $causas[$causa->nid] = $causa;
929  }
930  $form = array();
931  $causas_load = array();
932  if (!count($causas)) {
933      $prefijo .= '<tr><td colspan="6">' . t('No se han ingresado causas criticas') . '&nbsp;</td></tr>';
934      //$prefijo .= '</table>';
935      $form['seleccionar'] = array(
936        '#value' => $prefijo,
937      );
938  }
939  else {
940    $type = _sap_tipo_causa();
941    $level = _sap_nivel_control();
942    foreach($causas as $causa) {
943      $causa_load = node_load($causa->nid);
944      if ($causa_load) {
945        $causas_load[$causa_load->nid] = $causa_load;
946        $solucions = array();
947        foreach($causa_load->field_causa_solucion as $solucion) {
948          $solucions[] = $solucion['value'];
949        }
950        $url = l(t('Editar Causa'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/causas/' . $causa_load->nid . '/editar');
951        if ($_REQUEST['destination']) {
952          $url = l(t('Editar Causa'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/causas/' . $causa_load->nid . '/editar', array('query' => array('destination' => $_REQUEST['destination'])));
953        }
954        $suffix = '</td><td>' . $causa_load->body . '</td><td>' . theme('item_list', $solucions) . '</td><td>' . $type[$causa_load->field_tipo_causa[0]['value']] . '</td><td>' . $level[$causa_load->field_causa_control[0]['value']] . '</td><td>' .  $url . ' </td></tr>';
955        $form['seleccionar_' . $causa_load->nid] = array(
956          '#type' => 'checkbox',
957          '#title' => '',
958          '#default_value' => $causas_select[$causa_load->nid],
959          '#prefix' => $prefijo . '<tr><td>',
960          '#suffix' =>$suffix,
961        );
962        $prefijo = '';
963      }
964    }
965    //$form['seleccionar_' . $causa_load->nid]['#suffix'] .= '</table>';
966  }
967  $form['#ente_planificador'] = $ente_planificador;
968  $form['#descriptor'] = $descriptor;
969  $form['#tipo_plan'] = $tipo_plan;
970  $form['#causas_load'] = $causas_load;
971  $form['#causas_select'] = $causas_select;
972  $form['buttons']['#weight'] = 100;
973  $prefijo .= '<tr><td colspan="5">';
974  $form['agregar'] = array(
975    '#type' => 'submit',
976    '#prefix' => '<tr><td colspan="6" align="center">',
977    '#suffix' => '</td></tr></table>',
978    '#value' => t('Agregar Causas'),
979  );
980  if (count($form['#causas_load'])) {
981    $form['buttons']['submit'] = array(
982      '#type' => 'submit',
983      '#value' => t('Seleccionar Causas'),
984      '#weight' => 100,
985    );
986  }
987  $form['buttons']['cancel'] = array(
988    '#type' => 'submit',
989    '#value' => t('Regresar'),
990    '#weight' => 101,
991  );
992  return $form;
993}
994
995/*
996 * Implementation of ente_planificador_causas_editar_form_validate()
997 * Validar Agregar o editar causas
998 */
999function ente_planificador_causas_seleccionar_form_validate($form, &$form_state) {
1000  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1001  if ($op == t('Regresar') || $op == t('Agregar Causas')) {
1002    return;
1003  }
1004  if (count($form['#causas_load'])) {
1005    $seleccionado = FALSE;
1006    foreach($form['#causas_load'] as $causa) {
1007      if ($form_state['values']['seleccionar_' . $causa->nid]) {
1008        $seleccionado = TRUE;
1009      }
1010    }
1011    if (!$seleccionado) {
1012      form_set_error('seleccionar_' . $causa->nid, t('Debe seleccionara al menos una causa'));
1013    }
1014  }
1015  return;
1016}
1017
1018/*
1019 * Implementation of ente_planificador_causas_seleccionar_form_submit()
1020 */
1021function ente_planificador_causas_seleccionar_form_submit($form, &$form_state) {
1022  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1023  if ($op == t('Regresar')) {
1024    return;
1025  }
1026  if ($op == t('Agregar Causas')) {
1027    if ($_REQUEST['destination']) {
1028      $form_state['redirect'] = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $form['#descriptor']->nid . '/causas/agregar',
1029        array(
1030          'query' => array(
1031            'destination' => $_REQUEST['destination'],
1032           ),
1033           'absolute' => TRUE,                     
1034        )
1035      );
1036      unset($_REQUEST['destination']);
1037    }
1038    else {
1039      // add redirect
1040      $form_state['redirect'] = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $form['#descriptor']->nid . '/causas/agregar';
1041    }
1042    return;
1043  }
1044  module_load_include('inc', 'node', 'node.pages');
1045  $descriptores_causa = array();
1046  $descriptor = $form['#descriptor'];
1047  if (count($form['#causas_load'])) {
1048    foreach($form['#causas_load'] as $causa) {
1049      if ($form_state['values']['seleccionar_' . $causa->nid]) {
1050        $descriptores_causa[] = array('nid' => $causa->nid);
1051        //se verifica que no ha cambiado la causa
1052        if (!isset($form['#causas_select'][$causa->nid])) {
1053          $causa_load = $form['#causas_load'][$causa->nid];
1054          $causa_load->log = t('Agregado al descriptor @date', array('@date' => date('d-m-Y', time())));
1055          $causa_load->revision = 1;
1056          $causa_load->field_descriptores_causa[]['nid'] = $descriptor->nid;
1057          node_save($causa_load);
1058        }
1059      }
1060    }
1061  }
1062  if (!$encontrado) {
1063    $descriptor->field_descriptores_causa[]['nid'] = $causa->nid;
1064  }
1065  $descriptor->field_descriptores_causa = $descriptores_causa;
1066  $descriptor->log = t('Se seleccionarón las causa del descriptor  @date', array('@date' => date('d-m-Y', time())));
1067  $descriptor->revision = 1;
1068  node_save($descriptor);
1069  drupal_set_message(t('Se guardarón las causas del descriptor @title', array('@title' => $descriptor->body)));
1070}
1071
1072/*
1073 * Implementation of ente_planificador_causas_editar_form()
1074 * Agregar o editar causas a descriptores
1075 */
1076function ente_planificador_causas_editar_form($form_state, $ente_planificador,  $tipo_plan = array(), $descriptor = 0, $node = 0) {
1077  global $user;
1078  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
1079  $current_time = time();
1080  $fecha = FALSE;
1081  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1082    $fecha = TRUE;
1083  }
1084  if (!$fecha) {
1085    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
1086  }
1087  else {
1088    $ente = usuario_tiene_ente($user->uid);
1089    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
1090      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
1091    }
1092  }
1093  if (!$node) {
1094    $node = new stdClass();
1095    $node->body = '';
1096    $node->type = 'causas';
1097    $node->uid = $user->uid;
1098    $node->title = 'Causa-' . $ente_planificador->nid . '-' . time();
1099    $node->field_ente_planifiador[0]['nid'] = $ente_planificador->nid;
1100    $campo = 'field_' . $node->type . '_' . $tipo_plan['short'];
1101    $node->{$campo}[0]['value'] = 1;
1102  }
1103  $texto = $causa? t('Modificar causa') :  t('Agregar causa');
1104  drupal_set_title($texto);
1105  $form['#ente_planificador'] = $ente_planificador;
1106  $form['#descriptor'] = $descriptor;
1107  $form['#node'] = $node;
1108  $form['#tipo_plan'] = $tipo_plan;
1109
1110  if (variable_get('situacion_actual_acronimo', false)) {
1111    $form['title'] = array(
1112      '#type' => 'textfield',
1113      '#title' => t('Acrónimo de la Causa'),
1114      '#required' => TRUE,
1115      '#default_value' => $node->title,
1116      '#maxlength' => 255,
1117      '#weight' => -5,
1118      '#description' => t('Introduzca el acrónimo de la causa para facilitar su busqueda. Es deseable que este sea único para facilitar su distinción entre otros descriptores.'),
1119    );
1120  }
1121  $form['causa'] = array(
1122    '#type' => 'textarea',
1123    '#title' => t('Causa'),
1124    '#description' => t('Introduzca la causa de la situación actual.'),
1125    '#default_value' => $node->body,
1126    '#required' => TRUE,
1127  );
1128  $node_type = content_types('causas');
1129  $fields = $node_type['fields'];
1130  $field_form = array();
1131  $fields_form = array();
1132  $arreglo = array(
1133    'field_causa_solucion' => 'field_causa_solucion',
1134  );
1135  if (is_array($fields) && count($fields)) {
1136    foreach($fields as $field_id => $field) {
1137      if (array_key_exists($field_id, $arreglo)) {
1138        $field_form[] = $field_id;
1139        $fields_form[] = $field_id;
1140      }
1141    }
1142  }
1143  if (is_array($field_form) && count($field_form)) {
1144    module_load_include('inc', 'content', 'includes/content.node_form');
1145    foreach ($field_form as $field_id) {
1146      $field = content_fields($field_id, $form['#node']->type);
1147      $form['#field_info'][$field_id] = $field;
1148      $form += (array) content_field_form($form, $form_state, $field);
1149    }
1150  }
1151  $form['#' . $form['#node']->type . '_campos'] = $fields;
1152  $form['#' . $form['#node']->type . '_fields'] = $fields_form;
1153  $type = _sap_tipo_causa();
1154  $level = _sap_nivel_control();
1155  $form['#type_causa'] = $type;
1156  $form['#type_level'] = $level;
1157  $form['tipo'] = array(
1158    '#type' => 'radios',
1159    '#title' => t('Tipo de Causa'),
1160    '#default_value' => $node->field_tipo_causa[0]['value'],
1161    '#options' => $type,
1162    '#required' => TRUE,
1163  );
1164  $form['level'] = array(
1165    '#type' => 'radios',
1166    '#title' => t('Nivel de Control'),
1167    '#default_value' => $node->field_causa_control[0]['value'],
1168    '#options' => $level,
1169    '#required' => TRUE,
1170  );
1171  $form['buttons']['#weight'] = 100;
1172  $form['buttons']['submit'] = array(
1173    '#type' => 'submit',
1174    '#value' => t('Submit'),
1175    '#weight' => 100,
1176  );
1177  $form['buttons']['cancel'] = array(
1178    '#type' => 'submit',
1179    '#value' => t('Cancel'),
1180    '#weight' => 101,
1181  );
1182  return $form;
1183}
1184
1185/*
1186 * Implementation of ente_planificador_causas_editar_form_validate()
1187 * Validar Agregar o editar causas
1188 */
1189function ente_planificador_causas_editar_form_validate($form, &$form_state) {
1190  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1191  if ($op == t('Cancel')) {
1192    if ($_REQUEST['destination']) {
1193      $redirect = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/causas',
1194        array(
1195          'query' => array(
1196            'destination' => $_REQUEST['destination'],
1197           ),
1198           'absolute' => TRUE,                     
1199        )
1200      );
1201    }
1202    else {
1203      // add redirect
1204      $redirect = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/causas';
1205    }
1206    drupal_goto($redirect);
1207    return;
1208  }
1209  if (trim($form_state['values']['causa']) == '') {
1210    form_set_error('causa', t('Debe agregar la causa de la situación actual'));
1211  }
1212  return;
1213}
1214
1215/*
1216 * Implementation of ente_planificador_descriptores_editar_form_submit()
1217 */
1218function ente_planificador_causas_editar_form_submit($form, &$form_state) {
1219  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1220  if ($op == t('Cancel')) {
1221    return;
1222  }
1223  module_load_include('inc', 'node', 'node.pages');
1224  $causa = $form['#node'];
1225  $descriptor = $form['#descriptor'];
1226  node_object_prepare($descriptor);
1227  $form_state['values']['descriptor'] = check_plain($form_state['values']['descriptor']);
1228  if (variable_get('situacion_actual_acronimo', false)) {
1229    $causa->title = check_plain($form_state['values']['title']);
1230  }
1231  else {
1232    $causa->title = substr($form_state['values']['causa'], 0, 244);
1233  }
1234  $causa->body = $form_state['values']['causa'];
1235  //crear una nueva revision
1236  $nuevo = TRUE;
1237  if ($causa->nid) {
1238    $nuevo = FALSE;
1239    $causa->log = t('Modificados los datos de la causa @date', array('@date' => date('d-m-Y', time())));
1240    $causa->revision = 1;
1241  }
1242  $encontrado = FAlSE;
1243  if (count($causa->field_descriptores_causa)) {
1244    foreach($causa->field_descriptores_causa as $enlace) {
1245      if ($enlace['nid'] == $descriptor->nid) {
1246        $encontrado = TRUE;
1247      }
1248    }
1249  }
1250  if (!$encontrado) {
1251    $causa->field_descriptores_causa[]['nid'] = $form['#descriptor']->nid;
1252  }
1253  $causa->field_causas_year[0]['value'] = variable_get('situacional_actual_preliminar_anho_creacion', 0);
1254  if ($form['#type_causa'][$form_state['values']['tipo']]) {
1255    $causa->field_tipo_causa[0]['value'] = $form_state['values']['tipo'];
1256  }
1257  if ($form['#type_level'][$form_state['values']['level']]) {
1258    $causa->field_causa_control[0]['value'] = $form_state['values']['level'];
1259  }
1260  $field_form = $form['#' . $form['#node']->type . '_fields'];
1261  module_load_include('inc', 'node', 'node.pages');
1262  $node_load = $form['#node'];
1263  $form_values = $form_state['values'];
1264  if (is_array($field_form) && count($field_form)) {
1265    foreach ($field_form as $field_id) {
1266      if (isset($form_values[$field_id]) && is_array($form_values[$field_id])) {
1267        foreach($form_values[$field_id] as $id => $value) {
1268          if (is_numeric($id) && isset($form_values[$field_id][$id]['_error_element'])) {
1269            unset($form_values[$field_id][$id]['_error_element']);
1270          }
1271        }
1272        $causa->{$field_id} = $form_values[$field_id];
1273      }
1274    }
1275  }
1276  node_save($causa);
1277  $form['#causa'] = $causa;
1278  //se agrega la causa al descriptor
1279  $encontrado = FAlSE;
1280  if (count($descriptor->field_descriptores_causa)) {
1281    foreach($descriptor->field_descriptores_causa as $enlace) {
1282      if ($enlace['nid'] == $causa->nid) {
1283        $encontrado = TRUE;
1284      }
1285    }
1286  }
1287  if (!$encontrado) {
1288    $descriptor->field_descriptores_causa[]['nid'] = $causa->nid;
1289  }
1290  $descriptor->log = t('Se agregó una nueva causa al descriptor  @date', array('@date' => date('d-m-Y', time())));
1291  $descriptor->revision = 1;
1292  node_save($descriptor);
1293  if ($nuevo) {
1294    drupal_set_message(t('Se agregó la causa @title', array('@title' => $causa->body)));
1295  }
1296  else {
1297    drupal_set_message(t('Se modificó la causa @title', array('@title' => $causa->body)));
1298  }
1299  if ($_REQUEST['destination']) {
1300    $form_state['redirect'] = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/causas',
1301      array(
1302        'query' => array(
1303          'destination' => $_REQUEST['destination'],
1304         ),
1305         'absolute' => TRUE,               
1306      )
1307    );
1308    unset($_REQUEST['destination']);
1309  }
1310  else {
1311    // add redirect
1312    $form_state['redirect'] = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/causas';
1313  }
1314}
1315
1316/*
1317 * Implementation of _situacion_actual_preliminar_get_pdlp()
1318 * Obtiene los objetivos a considerar del plan de la patria
1319 */
1320function _situacion_actual_preliminar_get_pdlp() {
1321  return  array(
1322    'historico' => t('Objetivo Historico'),
1323    'nacional' => t('Objetivo Nacional'),
1324    'estrategico' => t('Objetivo Estratégico'),
1325    'generales' => t('Objetivo General'),
1326    'metas' => t('Meta del Plan Campaña Carabobo'),
1327  );
1328}
1329
1330/*
1331 * Implementation of _ente_planificador_cambios_situacion_actual_ver()
1332 * Consultar los cambios de un descriptor
1333 */
1334function _ente_planificador_cambios_situacion_actual_ver($ente_planificador,  $tipo_plan = array(), $descriptor = 0) {
1335  global $user;
1336  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
1337  $current_time = time();
1338  $fecha = FALSE;
1339  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1340    $fecha = TRUE;
1341  }
1342  if (!$fecha) {
1343    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
1344  }
1345  else {
1346    $ente = usuario_tiene_ente($user->uid);
1347    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
1348      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
1349    }
1350  }
1351  drupal_set_title(t('Cambios en la Situación Actual del descriptor "@name"', array('@name' => $descriptor->body)));
1352  $headers_table = array();
1353  $array = _situacion_actual_preliminar_get_pdlp();
1354  $acceso = _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan, $descriptor);
1355  $headers_table[] = array('data' => t('Descripción del cambio'));
1356  foreach($array as $id_pdp => $texto) {
1357    $headers_table[] = array('data' => $texto);
1358  }
1359  $headers_table[] = array('data' => t('Meta asociada al cambio'), 'rowspan' => 2);
1360  if ($acceso) {
1361    $headers_table[] = array('data' => t('Acción'), 'rowspan' => 2);
1362  }
1363  $rows = array();
1364  foreach($descriptor->field_descriptor_cambio as $cambio) {
1365    if ($cambio['nid']) {
1366      $cambio_load = node_load($cambio['nid']);
1367      if ($cambio_load->type == 'cambios'){
1368        $row = array();
1369        $row[] = array('data' => $cambio_load->body);
1370        $k = 0;
1371        foreach($array as $id_pdp => $texto) {
1372          $texto_out = '';
1373          $term_id = 0;
1374          if ($k < 4 && isset($cambio_load->field_cambios_pdp[$k]['value'])) {
1375            $term_id = $cambio_load->field_cambios_pdp[$k]['value'];
1376          }elseif(!$term_id && $k == 4 && isset($cambio_load->field_cambios_carabobo[0]['value'])) {
1377            $term_id = $cambio_load->field_cambios_carabobo[0]['value'];
1378          }
1379          if ($term_id) {
1380            $term = taxonomy_get_term($term_id);
1381            if ($term && $k < 4) {
1382              $texto_out = $term->name . ' ' . $term->description;
1383            }
1384            else {
1385              $valores = term_fields_get_fields_values($term);
1386              $texto_out = $valores && isset($valores['plan_carabobo_meta_value'])? $valores['plan_carabobo_meta_value'] : '';
1387            }
1388          }
1389          $row[] = array('data' => $texto_out);
1390          $k++;
1391        }
1392        $metas = array();
1393        foreach($cambio_load->field_cambios_meta as $meta) {
1394          $unidad = $meta['tid'];
1395          // If this term's vocabulary supports localization.
1396          $term = taxonomy_get_term($meta['tid']);
1397          if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
1398            $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
1399          }
1400          $numero = number_format($meta['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']);
1401          $metas[] = $numero . ' ' . $term->name;
1402        }
1403        $row[] = array('data' => theme('item_list', $metas));
1404        if ($acceso) {
1405          $url = l(t('Editar Cambio en la situación Actual'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/cambios/' . $cambio_load->nid . '/editar');
1406          if ($_REQUEST['destination']) {
1407            $url = l(t('Editar Cambio en la situación Actual'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/cambios/' . $cambio_load->nid . '/editar', array('query' => array('destination' => $_REQUEST['destination'])));
1408          }
1409          $row[] = array('data' => $url);
1410        }
1411        $rows[] = $row;
1412      }
1413    }
1414  }
1415  if (!count($rows)) {
1416    $row = array();
1417    $row[] = array('data' => t('No se encontrarón Cambios en la Situación Actual para este descriptor'), 'colspan' => count($headers_table));
1418    $rows[] = $row;
1419  }
1420  $url = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'];
1421  $links = array();
1422  //$links[] = l(t('Agregar Cambios en la situación actual'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor->nid . '/cambios', array('query' => array('destination' => $url)));
1423
1424  if ($acceso && $tipo_plan['plan'] != 'situacion_actual' &&(count($ente_planificador->ente_planificador_hierarchical['children'])|| user_access('admin planificador'))) {
1425    $links[] = l(t('Importar Cambios en la situación actual usando Web semántica'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/cambios', array('query' => array('destination' => $url)));
1426    $links[] = l(t('Importar Cambios en la situación actual'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/cambios_texto', array('query' => array('destination' => $url)));
1427  }
1428  $links[] = l(t('Regresar'), $url);
1429  return theme('table', $headers_table, $rows) . theme('item_list', $links);
1430}
1431
1432/*
1433 * Implementation of ente_planificador_cambios_situacion_actual_seleccionar_form()
1434 * Seleccionar cambios en la situacion actual en descriptores
1435 */
1436function ente_planificador_cambios_situacion_actual_seleccionar_form($form_state, $ente_planificador,  $tipo_plan = array(), $descriptor = 0) {
1437  global $user;
1438  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
1439  $current_time = time();
1440  $fecha = FALSE;
1441  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1442    $fecha = TRUE;
1443  }
1444  if (!$fecha) {
1445    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
1446  }
1447  else {
1448    $ente = usuario_tiene_ente($user->uid);
1449    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
1450      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
1451    }
1452  }
1453  drupal_set_title(t('Agregar Cambios en la Situación Actual'));
1454  $form = array();
1455  $cambios_select = array();
1456  foreach($descriptor->field_descriptor_cambio as $cambio) {
1457    if ($cambio['nid']) {
1458      $cambios_select[$cambio['nid']] = 1;
1459    }
1460  }
1461  $array_pdlp = _situacion_actual_preliminar_get_pdlp();
1462
1463
1464  $prefijo = '<table width="100%" style="border: 0;"><tr><th>';
1465  $header = array();
1466  $header[] = t('Eliminar');
1467  $header[] = t('Descripción del cambio');
1468  foreach($array_pdlp as $id_pdp => $texto) {
1469    $header[] = $texto;
1470  }
1471  $header[] = t('Meta asociada al cambio');
1472  $header[] = t('Acción');
1473  $prefijo .= implode('</th><th>', $header) .  '</th></tr>';
1474  $form = array();
1475  $form['#tipo_plan'] = $tipo_plan;
1476  $cambios_load = array();
1477  if (!count($cambios_select)) {
1478    $prefijo .= '<tr><td colspan="6">' . t('No se han ingresado Cambios en la Situación Actual del descriptor') . '&nbsp;</td></tr>';
1479    $form['seleccionar'] = array(
1480      '#value' => $prefijo,
1481    );
1482  }
1483  else {
1484    foreach($descriptor->field_descriptor_cambio as $cambio) {
1485      $cambio_load = node_load($cambio['nid']);
1486      if ($cambio_load && $cambio_load->type == 'cambios') {
1487        $cambios_load[$cambio_load->nid] = $cambio_load;
1488        $metas = array();
1489        $suffix = '</td><td>' . $cambio_load->body . '</td>';
1490        $k = 0;
1491        foreach($array_pdlp as $id_pdp => $texto) {
1492          $texto_out = '';
1493          $term_id = 0;
1494          if ($k < 4 && isset($cambio_load->field_cambios_pdp[$k]['value'])) {
1495            $term_id = $cambio_load->field_cambios_pdp[$k]['value'];
1496          }elseif(!$term_id && $k == 4 && isset($cambio_load->field_cambios_carabobo[0]['value'])) {
1497            $term_id = $cambio_load->field_cambios_carabobo[0]['value'];
1498          }
1499          if ($term_id) {
1500            $term = taxonomy_get_term($term_id);
1501            if ($term && $k < 4) {
1502              $texto_out = $term->name . ' ' . $term->description;
1503            }
1504            else {
1505              $valores = term_fields_get_fields_values($term);
1506              $texto_out = $valores && isset($valores['plan_carabobo_meta_value'])? $valores['plan_carabobo_meta_value'] : '';
1507            }
1508          }
1509          $suffix .= '</td><td>' . $texto_out . '</td>';
1510          $k++;
1511        }
1512        foreach($cambio_load->field_cambios_meta as $meta) {
1513          $unidad = $meta['tid'];
1514          // If this term's vocabulary supports localization.
1515          $term = taxonomy_get_term($meta['tid']);
1516          if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
1517            $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
1518          }
1519          $numero = number_format($meta['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']);
1520          $metas[] = $numero . ' ' . $term->name;
1521        }
1522        $suffix .= '</td><td>' . theme('item_list', $metas) . '</td>';
1523        $url = l(t('Editar Cambio en la situación Actual'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios/' . $cambio_load->nid . '/editar');
1524        if ($_REQUEST['destination']) {
1525          $url = l(t('Editar Cambio en la situación Actual'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios/' . $cambio_load->nid . '/editar', array('query' => array('destination' => $_REQUEST['destination'])));
1526        }
1527        $suffix .= '</td><td>' . $url . '</td></tr>';
1528
1529        $pdlp = '';
1530        if (isset($cambio_load->field_cambios_pdp[$cant - 1]['value'])) {
1531          $term = taxonomy_get_term($cambio_load->field_cambios_pdp[$cant - 1]['value']);
1532          if ($term) {
1533            $pdlp = $term->name . ' ' . $term->description;
1534          }
1535        }
1536        $carabobo = '';
1537        if (isset($cambio_load->field_cambios_carabobo[0]['value'])) {
1538          $term = taxonomy_get_term($cambio_load->field_cambios_carabobo[0]['value']);
1539          if ($term) {
1540            $valores = term_fields_get_fields_values($term);
1541            if ($valores && isset($valores['plan_carabobo_meta_value'])) {
1542              $carabobo = $valores['plan_carabobo_meta_value'];
1543            }
1544          }
1545        }
1546        $form['seleccionar_' . $cambio_load->nid] = array(
1547          '#type' => 'checkbox',
1548          '#title' => '',
1549          '#default_value' => 0,
1550          '#prefix' => $prefijo . '<tr><td>',
1551          '#suffix' =>$suffix,
1552        );
1553        $prefijo = '';
1554      }
1555    }
1556    //$form['seleccionar_' . $cambio_load->nid]['#suffix'] .= '</table>';
1557  }
1558  $form['#ente_planificador'] = $ente_planificador;
1559  $form['#descriptor'] = $descriptor;
1560  $form['#array_pdlp'] = $array_pdlp;
1561  $form['#cambios_load'] = $cambios_load;
1562  $form['#cambios_select'] = $cambios_select;
1563  $form['buttons']['#weight'] = 1000;
1564  $form['agregar'] = array(
1565    '#type' => 'submit',
1566    '#prefix' => '<tr><td colspan="' . count($header) . '" align="center">',
1567    '#suffix' => '</td></tr></table>',
1568    '#value' => t('Agregar Cambio en la Situación Actual'),
1569  );
1570  if (count($form['#cambios_load'])) {
1571    $form['buttons']['submit'] = array(
1572      '#type' => 'submit',
1573      '#value' => t('Eliminar Cambios en la Situación Actual'),
1574      '#weight' => 99,
1575    );
1576  }
1577  $form['buttons']['cancel'] = array(
1578    '#type' => 'submit',
1579    '#value' => t('Regresar'),
1580    '#weight' => 101,
1581  );
1582  return $form;
1583}
1584
1585/*
1586 * Implementation of ente_planificador_cambios_situacion_actual_seleccionar_form_validate()
1587 * Validar Agregar o editar cambios
1588 */
1589function ente_planificador_cambios_situacion_actual_seleccionar_form_validate($form, &$form_state) {
1590  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1591  if ($op == t('Regresar') || $op == t('Agregar Cambio en la Situación Actual')) {
1592    return;
1593  }
1594  if (count($form['#cambios_load'])) {
1595    $seleccionado = FALSE;
1596    foreach($form['#cambios_load'] as $cambio) {
1597      if ($form_state['values']['seleccionar_' . $cambio->nid]) {
1598        $seleccionado = TRUE;
1599      }
1600    }
1601    if (!$seleccionado) {
1602      form_set_error('seleccionar_' . $cambio->nid, t('Debe seleccionar al menos un Cambio en la Situación Actual para eliminar'));
1603    }
1604  }
1605  return;
1606}
1607
1608/*
1609 * Implementation of ente_planificador_cambios_situacion_actual_seleccionar_form_submit()
1610 */
1611function ente_planificador_cambios_situacion_actual_seleccionar_form_submit($form, &$form_state) {
1612  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1613  if ($op == t('Regresar')) {
1614    return;
1615  }
1616  if ($op == t('Agregar Cambio en la Situación Actual')) {
1617    if ($_REQUEST['destination']) {
1618      $form_state['redirect'] = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $form['#descriptor']->nid . '/cambios/agregar',
1619        array(
1620          'query' => array(
1621            'destination' => $_REQUEST['destination'],
1622           ),
1623           'absolute' => TRUE,                     
1624        )
1625      );
1626      unset($_REQUEST['destination']);
1627    }
1628    else {
1629      // add redirect
1630      $form_state['redirect'] = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $form['#descriptor']->nid . '/cambios/agregar';
1631    }
1632    return;
1633  }
1634  module_load_include('inc', 'node', 'node.pages');
1635  $descriptores_cambio = array();
1636  $descriptor = $form['#descriptor'];
1637  $borrados = array();
1638  if (count($form['#cambios_load'])) {
1639    foreach($form['#cambios_load'] as $cambio) {
1640      if (!$form_state['values']['seleccionar_' . $cambio->nid]) {
1641        $descriptores_cambio[] = array('nid' => $cambio->nid);
1642      }
1643      else {
1644        $borrados[] = $cambio->nid;
1645      }
1646    }
1647  }
1648  if (count($borrados)) {
1649    $descriptor->field_descriptor_cambio = $descriptores_cambio;
1650    $descriptor->log = t('Se eliminarón los Cambios en la Situación Actual (@borrados) del descriptor  @date', array('@borrados' => implode(', ', $borrados),'@date' => date('d-m-Y', time())));
1651  }
1652  $descriptor->revision = 1;
1653  node_save($descriptor);
1654  drupal_set_message(t('Se guardarón los Cambios en la Situación Actual del descriptor @title', array('@title' => $descriptor->body)));
1655}
1656
1657/*
1658 * Implementation of _ente_planificador_cambios_taxonomy()
1659 * Obtiene los terminos hijos de un termino dado y su taxonomia
1660 */
1661function _ente_planificador_cambios_taxonomy($vid = 0, $tid = 0) {
1662  $result = db_query(db_rewrite_sql('SELECT t.tid, t.*, parent FROM {term_data} t INNER JOIN  {term_hierarchy} h ON t.tid = h.tid WHERE t.vid = %d AND h.parent = %d ORDER BY weight, name', 't', 'tid'), $vid, $tid);
1663  $terms = array();
1664  while ($term = db_fetch_object($result)) {
1665    $terms[$term->tid] = $term->name . ' ' . $term->description;
1666  }
1667  return $terms;
1668}
1669
1670/*
1671 * planificacion_cambios_pdlp_js
1672 * Genera el plan de la patria
1673 */
1674function planificacion_cambios_pdlp_js($func) {
1675  $form_state = array('submitted' => FALSE);
1676  $form_build_id = $_POST['form_build_id'];
1677  // Add the new element to the stored form. Without adding the element to the
1678  // form, Drupal is not aware of this new elements existence and will not
1679  // process it. We retreive the cached form, add the element, and resave.
1680  $form = form_get_cache($form_build_id, $form_state);
1681  $array = $form['#pdlp'];
1682  $opens_div = '';
1683  $i = 0;
1684  $term_id = 0;
1685  $encontrado = FALSE;
1686  $new_form = array();
1687  $terms = array();
1688  $node_type = content_types('cambios');
1689  $fields = $form['#' . $form['#node']->type . '_campos'];
1690  $vid = $fields['field_cambios_pdp']['vid'];
1691  $inputs_metas = array();
1692  $inputs_metas_sql = array();
1693  $inputs = array();
1694  $inputs[] = $vid;
1695  foreach ($array as $id => $texto) {
1696    $valor = intval($_POST[$id]);
1697    if (!$encontrado && $valor > 0) {
1698      $inputs[] = $valor;
1699      $inputs_metas_sql[] = '%d';
1700    }
1701    if ($encontrado) {
1702      if ($id != 'metas') {
1703        $terms = array(0 => t('Seleccione'),);
1704        if ($term_id || $i == 0) {
1705          $terms += _ente_planificador_cambios_taxonomy($vid, $term_id);
1706        }
1707        $form['pdlp'][$id] = array(
1708          '#type' => 'select',
1709          '#title' => t('Objetivo @tipo', array('@tipo' => $texto)),
1710          '#default_value' => $term_id,
1711          '#options' => $terms,
1712          '#description' => t('Seleccione el Objetivo @tipo.', array('@tipo' => $texto)),
1713          '#required' => TRUE,
1714          '#ahah' => array(
1715            'event' => 'change',
1716            'path' => 'planificacion_cambios_pdlp_js/' . $id,
1717            'wrapper' => 'situacion_preliminar_' . $id,
1718            'method' => 'replace',
1719            'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
1720          ),
1721        );
1722        $term_id = 0;
1723        $ant_term = 0;
1724      }
1725      else {
1726        $terms = array(0 => t('Seleccione'),);
1727        if (count($inputs)) {
1728          $sql = 'SELECT f.plan_carabobo_meta_value AS meta, f.tid FROM {term_fields_term} AS f INNER JOIN {term_data} AS t ON t.tid = f.plan_carabobo_relations_value AND t.vid = %d WHERE f.plan_carabobo_relations_value IN (' . implode(', ', $inputs_metas_sql) . ')';
1729          $result = db_query($sql, $inputs);
1730          $j = 1;
1731          while ($termino = db_fetch_object($result)) {
1732            $meta = trim($termino->meta);
1733            if ($meta != '') {
1734              $terms[$termino->tid] = '(' . $j . ') ' . $meta;
1735              $j++;
1736            }
1737          }
1738        }
1739        $form['pdlp'][$id] = array(
1740          '#type' => 'select',
1741          '#title' => t('@texto_metas (cantidad de metas: @metas)', array('@texto_metas' => $texto, '@metas' => $j - 1)),
1742          '#default_value' => 0,
1743          '#options' => $terms,
1744          '#description' => t('Seleccione la meta del Plan Campaña de Carabobo.'),
1745        );
1746      }
1747      $form['pdlp'][$id]['#prefix'] = '<div id = "situacion_preliminar_' . $id . '">';
1748      $opens_div .= '</div>';
1749      $i++;
1750    }
1751    if ($id == $func) {
1752      $encontrado = TRUE;
1753      $term_id = intval($_POST[$id]) > 0 ? intval($_POST[$id]) : 0;
1754    }
1755  }
1756  if ($encontrado) {
1757    $form['pdlp'][$id]['#suffix'] = $opens_div;
1758  }
1759  //$form += $new_form;
1760  form_set_cache($form_build_id, $form, $form_state);
1761  $form += array(
1762    '#post' => $_POST,
1763    '#programmed' => FALSE,
1764  );
1765  // Rebuild the form.
1766    $form = form_builder($_POST['form_id'], $form, $form_state);
1767  $encontrado = FALSE;
1768  $new_form = array();
1769  foreach ($array as $id => $texto) {
1770    if ($id == $func) {
1771      $encontrado = TRUE;
1772    }
1773    if ($encontrado) {
1774      $new_form[$id] = $form['pdlp'][$id];
1775    }
1776  }
1777  $output = drupal_render($new_form);
1778  print drupal_to_js(array('data' => $output, 'status' => true));
1779  exit();
1780}
1781
1782/*
1783 * Implementation of ente_planificador_cambios_editar_form()
1784 * Agregar o editar Cambio en la Situacion Actual
1785 */
1786function ente_planificador_cambios_editar_form($form_state, $ente_planificador,  $tipo_plan = array(), $descriptor = 0, $node = 0) {
1787  global $user;
1788  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
1789  $current_time = time();
1790  $fecha = FALSE;
1791  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1792    $fecha = TRUE;
1793  }
1794  if (!$fecha) {
1795    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
1796  }
1797  else {
1798    $ente = usuario_tiene_ente($user->uid);
1799    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
1800      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
1801    }
1802  }
1803  $texto = $node ? t('Modificar Cambio en la Situación Actual') :  t('Agregar Cambio en la Situación Actual');
1804  drupal_set_title($texto);
1805  if (!$node) {
1806    $node = new stdClass();
1807    $node->body = '';
1808    $node->type = 'cambios';
1809    $node->uid = $user->uid;
1810    $node->title = 'Cambios-' . $ente_planificador->nid . '-' . time();
1811    $node->field_cambios_ente[0]['nid'] = $ente_planificador->nid;
1812    $campo = 'field_' . $node->type . '_' . $tipo_plan['short'];
1813    $node->{$campo}[0]['value'] = 1;
1814  }
1815  $form['#tipo_plan'] = $tipo_plan;
1816  $form['#ente_planificador'] = $ente_planificador;
1817  $form['#descriptor'] = $descriptor;
1818  $form['#node'] = $node;
1819  if (variable_get('situacion_actual_acronimo', false)) {
1820    $form['title'] = array(
1821      '#type' => 'textfield',
1822      '#title' => t('Acrónimo del Cambio de la situación Actual'),
1823      '#required' => TRUE,
1824      '#default_value' => $node->title,
1825      '#maxlength' => 255,
1826      '#weight' => -5,
1827      '#description' => t('Introduzca el acrónimo del cambio Situación Actual para facilitar su busqueda. Es deseable que este sea único para facilitar su distinción entre otros descriptores.'),
1828    );
1829  }
1830  $form['cambio'] = array(
1831    '#type' => 'textarea',
1832    '#title' => t('Cambio de la Situación Actual'),
1833    '#description' => t('Introduzca el cambio de la Situación Actual.'),
1834    '#default_value' => $node->body,
1835    '#required' => TRUE,
1836  );
1837  //se agrega el plan de la patria
1838  $form['pdlp'] = array(
1839    '#type' => 'fieldset',
1840    '#title' => t('Plan de la Patria'),
1841  );
1842  $array = _situacion_actual_preliminar_get_pdlp();
1843  $opens_div = '';
1844  $i = 0;
1845  $ant_term = 0;
1846  $node_type = content_types('cambios');
1847  $fields = $node_type['fields'];
1848  $vid = $fields['field_cambios_pdp']['vid'];
1849  $inputs = array();
1850  $inputs[] = $vid;
1851  $inputs_metas_sql = array();
1852  foreach ($array as $id => $texto) {
1853    if ($id != 'metas') {
1854      $term_id = $node->field_cambios_pdp[$i]['value'] ? $node->field_cambios_pdp[$i]['value'] : 0;
1855      $terms = array(0 => t('Seleccione'),);
1856      if ($ant_term || $i == 0) {
1857        $terms += _ente_planificador_cambios_taxonomy($vid, $ant_term);
1858      }
1859      $ant_term = $term_id;
1860      if ($term_id) {
1861        $inputs[] = $term_id;
1862        $inputs_metas_sql[] = '%d';
1863      }
1864      $form['pdlp'][$id] = array(
1865        '#type' => 'select',
1866        '#title' => $texto,
1867        '#default_value' => $term_id,
1868        '#options' => $terms,
1869        '#description' => t('Seleccione el Objetivo @tipo.', array('@tipo' => $texto)),
1870        '#required' => TRUE,
1871        '#ahah' => array(
1872          'event' => 'change',
1873          'path' => 'planificacion_cambios_pdlp_js/' . $id,
1874          'wrapper' => 'situacion_preliminar_' . $id,
1875          'method' => 'replace',
1876          'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
1877        ),
1878      );
1879    }
1880    else {
1881      $terms = array(
1882        0 => t('Seleccione'),
1883      );
1884      if (count($inputs)) {
1885        $sql = 'SELECT f.plan_carabobo_meta_value AS meta, f.tid FROM {term_fields_term} AS f INNER JOIN {term_data} AS t ON t.tid = f.plan_carabobo_relations_value AND t.vid = %d WHERE f.plan_carabobo_relations_value IN (' . implode(', ', $inputs_metas_sql) . ')';
1886        $result = db_query($sql, $inputs);
1887        $j = 1;
1888        while ($termino = db_fetch_object($result)) {
1889          $meta = trim($termino->meta);
1890          if ($meta != '') {
1891            $terms[$termino->tid] = '(' . $j . ') ' . $meta;
1892            $j++;
1893          }
1894        }
1895      }
1896      $term_id = $node->field_cambios_carabobo[0]['value'] ? $node->field_cambios_carabobo[0]['value'] : 0;
1897      $form['pdlp'][$id] = array(
1898        '#type' => 'select',
1899        '#title' => t('@texto_metas (cantidad de metas: @metas)', array('@texto_metas' => $texto, '@metas' => $j - 1)),
1900        '#default_value' => $term_id,
1901        '#options' => $terms,
1902        '#description' => t('Seleccione la meta del Plan Campaña de Carabobo.'),
1903      );
1904    }
1905    $form['pdlp'][$id]['#prefix'] = '<div id = "situacion_preliminar_' . $id . '">';
1906    $opens_div .= '</div>';
1907    $i++;
1908  }
1909  $form['pdlp'][$id]['#suffix'] = $opens_div;
1910  //se agrega otros campos de interes
1911  $field_form = array();
1912  $fields_form = array();
1913  $arreglo = array(
1914    'field_cambios_meta' => 'field_cambios_meta',
1915  );
1916  if (is_array($fields) && count($fields)) {
1917    foreach($fields as $field_id => $field) {
1918      if (array_key_exists($field_id, $arreglo)) {
1919        $field_form[] = $field_id;
1920        $fields_form[] = $field_id;
1921      }
1922    }
1923  }
1924  if (is_array($field_form) && count($field_form)) {
1925    module_load_include('inc', 'content', 'includes/content.node_form');
1926    foreach ($field_form as $field_id) {
1927      $field = content_fields($field_id, $form['#node']->type);
1928      $form['#field_info'][$field_id] = $field;
1929      $form += (array) content_field_form($form, $form_state, $field);
1930    }
1931  }
1932  $form['#' . $form['#node']->type . '_campos'] = $fields;
1933  $form['#' . $form['#node']->type . '_fields'] = $fields_form;
1934  $form['#pdlp'] = $array;
1935  $form['buttons']['#weight'] = 100;
1936  $form['buttons']['submit'] = array(
1937    '#type' => 'submit',
1938    '#value' => t('Submit'),
1939    '#weight' => 100,
1940  );
1941  $form['buttons']['cancel'] = array(
1942    '#type' => 'submit',
1943    '#value' => t('Cancel'),
1944    '#weight' => 101,
1945  );
1946  return $form;
1947}
1948
1949/*
1950 * Implementation of ente_planificador_cambios_editar_form_validate()
1951 * Validar Agregar o editar Cambio en la Situacion Actual
1952 */
1953function ente_planificador_cambios_editar_form_validate($form, &$form_state) {
1954  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1955  if ($op == t('Cancel')) {
1956    if ($_REQUEST['destination']) {
1957      $redirect = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios',
1958        array(
1959          'query' => array(
1960            'destination' => $_REQUEST['destination'],
1961           ),
1962           'absolute' => TRUE,                     
1963        )
1964      );
1965    }
1966    else {
1967      // add redirect
1968      $redirect = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios';
1969    }
1970    drupal_goto($redirect);
1971    return;
1972  }
1973  if (trim($form_state['values']['cambio']) == '') {
1974    form_set_error('cambios', t('Debe agregar el cambio de la Situación Actual'));
1975  }
1976  if (count($form['pdlp']['metas']['#options']) > 1 && !$form_state['values']['metas']) {
1977    form_set_error('metas', t('Debe Indicar una meta del Plan Campaña de Carabobo'));
1978
1979  }
1980  return;
1981}
1982
1983/*
1984 * Implementation of ente_planificador_cambios_editar_form_submit()
1985 */
1986function ente_planificador_cambios_editar_form_submit($form, &$form_state) {
1987  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1988  if ($op == t('Cancel')) {
1989    return;
1990  }
1991  module_load_include('inc', 'node', 'node.pages');
1992  $cambio = $form['#node'];
1993  $descriptor = $form['#descriptor'];
1994  node_object_prepare($descriptor);
1995  $form_state['values']['descriptor'] = check_plain($form_state['values']['descriptor']);
1996  if (variable_get('situacion_actual_acronimo', false)) {
1997    $cambio->title = check_plain($form_state['values']['title']);
1998  }
1999  else {
2000    $cambio->title = substr($form_state['values']['cambio'], 0, 244);
2001  }
2002  $cambio->body = $form_state['values']['cambio'];
2003  //crear una nueva revision
2004  $nuevo = TRUE;
2005  if ($cambio->nid) {
2006    $nuevo = FALSE;
2007    $cambio->log = t('Modificados los datos del cambio en la situación actual @date', array('@date' => date('d-m-Y', time())));
2008    $cambio->revision = 1;
2009  }
2010  $encontrado = FAlSE;
2011  if (count($cambio->field_cambios_descriptor)) {
2012    foreach($cambio->field_cambios_descriptor as $enlace) {
2013      if ($enlace['nid'] == $descriptor->nid) {
2014        $encontrado = TRUE;
2015      }
2016    }
2017  }
2018  if (!$encontrado) {
2019    $cambio->field_cambios_descriptor[]['nid'] = $descriptor->nid;
2020  }
2021  $field_form = $form['#' . $form['#node']->type . '_fields'];
2022  module_load_include('inc', 'node', 'node.pages');
2023  $node_load = $form['#node'];
2024  $form_values = $form_state['values'];
2025  //$node_load->title = check_plain($form_values['title']);
2026  if (is_array($field_form) && count($field_form)) {
2027    foreach ($field_form as $field_id) {
2028      if (isset($form_values[$field_id]) && is_array($form_values[$field_id])) {
2029        foreach($form_values[$field_id] as $id => $value) {
2030          if (is_numeric($id) && isset($form_values[$field_id][$id]['_error_element'])) {
2031            unset($form_values[$field_id][$id]['_error_element']);
2032          }
2033        }
2034        $cambio->{$field_id} = $form_values[$field_id];
2035      }
2036    }
2037  }
2038  //se incluye el plan de la patria
2039  $i = 0;
2040  foreach ($form['#pdlp'] as $id => $texto) {
2041    if ($form_values[$id]) {
2042      if ($id == 'metas') {
2043        $cambio->field_cambios_carabobo[0]['value'] = $form_values[$id];
2044      }
2045      else {
2046        $cambio->field_cambios_pdp[$i]['value'] = $form_values[$id];
2047      }
2048    }
2049    $i++;
2050  }
2051  node_save($cambio);
2052  $form['#cambio'] = $cambio;
2053  //se agrega el cambio al descriptor
2054  $encontrado = FAlSE;
2055  if (count($descriptor->field_descriptor_cambio)) {
2056    foreach($descriptor->field_descriptor_cambio as $enlace) {
2057      if ($enlace['nid'] == $cambio->nid) {
2058        $encontrado = TRUE;
2059      }
2060    }
2061  }
2062  if (!$encontrado) {
2063    $descriptor->field_descriptor_cambio[]['nid'] = $cambio->nid;
2064  }
2065  $descriptor->log = t('Se agregó un nuevo cambio en la situación actual al descriptor  @date', array('@date' => date('d-m-Y', time())));
2066  $descriptor->revision = 1;
2067  node_save($descriptor);
2068  if ($nuevo) {
2069    drupal_set_message(t('Se agregó el cambio en la situación actual @title', array('@title' => $cambio->body)));
2070  }
2071  else {
2072    drupal_set_message(t('Se modificó el cambio en la situación actual @title', array('@title' => $cambio->body)));
2073  }
2074  if ($_REQUEST['destination']) {
2075    $form_state['redirect'] = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios',
2076      array(
2077        'query' => array(
2078          'destination' => $_REQUEST['destination'],
2079         ),
2080         'absolute' => TRUE,               
2081      )
2082    );
2083    unset($_REQUEST['destination']);
2084  }
2085  else {
2086    // add redirect
2087    $form_state['redirect'] = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios';
2088  }
2089}
2090
2091/*
2092 * Implementation of mis_entes_planificadores_planificacion_explicacion()
2093 */
2094function mis_entes_planificadores_planificacion_explicacion() {
2095  global $user;
2096  $output = '';
2097  $ente = usuario_tiene_ente($user->uid);
2098  if ($ente->nid) {
2099    drupal_goto('planificacion/' . $ente->nid . '/explicacion');
2100  }
2101  drupal_goto('mi_ente_planificador/planificacion');
2102  return $output;
2103}
2104
2105/*
2106 * Implementation of situacion_actual_preliminar_status_planificacion_explicacion()
2107 */
2108function situacion_actual_preliminar_status_planificacion_explicacion($ente_planificador, $tipo = 2) {
2109  $estado_preliminar = array();
2110  $planns = _situacion_actual_preliminar_get_planns();
2111  foreach ($planns as $id => $plann) {
2112    if (isset($plann['ente_type'][$tipo]) && $plann['ente_type'][$tipo]) {
2113      $descriptores = _get_situacion_actual_listar_all_descriptores($ente_planificador, $plann['plan'], variable_get('situacional_actual_preliminar_anho_creacion', 0));
2114      $estado_preliminar['situacion_actual_' . $plann['plan']] = array(
2115        'value' => count($descriptores) ? 1 : 0,
2116        'title' => $plann['title_long'],
2117        'link' => 'planificacion/' . $ente_planificador . '/explicacion/' . $plann['short'],
2118        'mylink' => 'mi_ente_planificador/planificacion/explicacion/' . $plann['short'],
2119        'weight' => 1,
2120      );
2121    }
2122  }
2123  return $estado_preliminar;
2124}
2125
2126/*
2127 * Implementation of hook_access()
2128 */
2129function situacion_actual_preliminar_access($op, $node, $account) {
2130  if ($op == 'view') {
2131    return user_access('ver planificador');
2132  }
2133  if ($op == 'create' ) {
2134    return (user_access('admin planificador'));
2135  }
2136  if ($op == 'update') {
2137    return user_access('admin planificador');
2138  }
2139  if ($op == 'delete') {
2140    return (user_access('admin planificador'));
2141  }
2142}
2143
2144/*
2145 * Implementation of _get_situacion_actual_listar_all_descriptores()
2146 * Get ente's descriptores
2147 * Inputs:
2148   - $ente_planificador (integer): ente planificador nid
2149   - $tipo (integer): plann type
2150   - $year (integer): descriptor year creation, if no available 'situacional_actual_preliminar_anho_creacion' variable will be used
2151 * Outputs:
2152   - Descriptores (array nid descriptor):
2153     + body: Description descriptor
2154     + title: Acronimo
2155     + nid: Descriptor nid node reference
2156     + year: descriptor year creation
2157     + clasificacion: descriptor type
2158       / tid: taxonomy term
2159     + causas: causas list (array nid causa-descriptor):
2160       / body: Description causa
2161       / title: Acronimo causa
2162       / nid: Causa nid node reference
2163       / descriptor: Descriptor nid node reference
2164     + solucion: solucion list (array nid solucion-descriptor):
2165       / body: Description solucion
2166       / title: Acronimo solucion
2167       / nid: Solucion nid node reference
2168       / descriptor: Descriptor nid node reference
2169 */
2170function _get_situacion_actual_listar_all_descriptores($ente_planificador, $tipo_plan = array(), $year = 0) {
2171  //se obtienen los descriptores
2172  $descriptores = array();
2173  $sql = "SELECT c.nid, n.title, nr.body FROM {content_type_descriptores} AS c INNER JOIN {node} AS n ON c.nid = n.nid AND c.vid = n.vid AND n.type = 'descriptores' INNER JOIN {node_revisions} AS nr  ON c.nid = nr.nid AND c.vid = nr.vid WHERE c.field_descriptores_planificador_nid = %d AND c.field_descriptores_year_value = %d";
2174  $inputs = array();
2175  $inputs[] = $ente_planificador;
2176  $year_display = $year? $year: variable_get('situacional_actual_preliminar_anho_creacion', 0);
2177  $inputs[] = $year_display;
2178  if ($tipo_plan['short']) {
2179    $sql .= ' AND c.field_descriptores_' . $tipo_plan['short'] . '_value = %d';
2180    $inputs[] = 1;
2181  }
2182  $sql .=' ORDER BY c.nid';
2183  $result = db_query($sql, $inputs);
2184  $inpunts = array();
2185  $inpunts_values = array();
2186  $solucion = array();
2187  while($descriptor = db_fetch_object($result)) {
2188    $descriptores[$descriptor->nid] = array(
2189      'body' => $descriptor->body,
2190      'title' => $descriptor->title,
2191      'nid' => $descriptor->nid,
2192      'year' => $year_display,
2193      'clasificacion' => array(),
2194      'causas' => array(),
2195      'cambios' => array(),
2196    );
2197    $inpunts[] = '%d';
2198    $inpunts_values[] = $descriptor->nid;
2199  }
2200  if (count($inpunts)) {
2201    $implode = implode(',',$inpunts);
2202    //Se obtienen la clasificacion de los descriptores
2203    $sql = 'SELECT c.field_descriptores_clasificacion_value AS tid, c.nid FROM {content_field_descriptores_clasificacion} AS c INNER JOIN {node} AS n ON n.nid = c.nid AND n.vid = c.vid WHERE c.nid IN (' . $implode . ')';
2204    $result = db_query($sql, $inpunts_values);
2205    while($clasificacion = db_fetch_object($result)) {
2206      $descriptores[$clasificacion->nid]['clasificacion'][$clasificacion->tid] = $clasificacion->tid;
2207    }
2208    //se obtienen las causas
2209    //field_descriptores_causa
2210    $sql = "SELECT c.field_descriptores_causa_nid as nid, c.nid as descriptor, n.title, nr.body FROM {content_field_descriptores_causa} AS c INNER JOIN {node} AS n ON c.field_descriptores_causa_nid = n.nid AND n.type = 'causas' INNER JOIN {node} AS n1 ON c.nid = n1.nid AND c.vid = n1.vid INNER JOIN {node_revisions} AS nr ON n.nid = nr.nid AND n.vid = nr.vid WHERE c.nid IN (" . $implode . ") ORDER BY c.field_descriptores_causa_nid";
2211    $result = db_query($sql, $inpunts_values);
2212    while($causa = db_fetch_object($result)) {
2213      $descriptores[$causa->descriptor]['causas'][$causa->nid] = array(
2214        'body' => $causa->body,
2215        'nid' => $causa->nid,
2216        'title' => $causa->title,
2217        'descriptor' => $causa->descriptor,
2218      );
2219    }
2220    //se obtienen los cambios
2221    //field_descriptor_cambio_nid
2222    $sql = "SELECT c.field_descriptor_cambio_nid as nid, c.nid as descriptor, n.title, nr.body FROM {content_field_descriptor_cambio} AS c INNER JOIN {node} AS n ON c.field_descriptor_cambio_nid = n.nid AND n.type = 'cambios' INNER JOIN {node} AS n1 ON c.nid = n1.nid AND c.vid = n1.vid INNER JOIN {node_revisions} AS nr ON n.nid = nr.nid AND n.vid = nr.vid WHERE c.nid IN (" . $implode . ") ORDER BY c.field_descriptor_cambio_nid";
2223    $result = db_query($sql, $inpunts_values);
2224    while($meta = db_fetch_object($result)) {
2225      $descriptores[$meta->descriptor]['cambios'][$meta->nid] = array(
2226        'body' => $meta->body,
2227        'nid' => $meta->nid,
2228        'title' => $meta->title,
2229        'descriptor' => $meta->descriptor,
2230      );
2231    }
2232  }
2233  return $descriptores;
2234}
2235
2236/*
2237 * Implementation of _display_situacion_actual_listar_all_descriptores()
2238 */
2239function _display_situacion_actual_listar_all_descriptores($ente_planificador = 0, $tipo_plan = array(), $acceso = FALSE, $year = 0) {
2240  $descriptores = _get_situacion_actual_listar_all_descriptores($ente_planificador, $tipo_plan, $year);
2241  $output = '';
2242  $headers_table = array();
2243  $headers_table[] = array('data' => t('Descriptores'));
2244  $headers_table[] = array('data' => t('Categorización'));
2245  $headers_table[] = array('data' => t('Causas'));
2246  $headers_table[] = array('data' => t('Cambios de la situación actual'));
2247  $year = $year? $year : variable_get('situacional_actual_preliminar_anho_creacion', 0);
2248  if ($acceso) {
2249    $headers_table[] = array('data' => t('Acciones'));
2250  }
2251  if (count($descriptores)) {
2252    $rows = array();
2253    foreach($descriptores as $descriptor) {
2254      $row = array();
2255      $row[] = array('data' => $descriptor['body']);
2256      $clasificiacion = array();
2257      foreach($descriptor['clasificacion'] as $id) {
2258        $term_load = taxonomy_get_term($id);
2259        if ($term_load) {
2260          $clasificiacion[] = $term_load->name;
2261        }
2262      }
2263      $row[] = array('data' => theme('item_list', $clasificiacion));
2264      $causas = array();
2265      foreach ($descriptor['causas'] as $causa) {
2266        $causas[] = $causa['body'];
2267      }
2268      $output = count($causas)? theme('item_list', $causas) : t('No se han agregado causas al descriptor');
2269      $row[] = array('data' => $output);
2270      $solucion = array();
2271      foreach ($descriptor['cambios'] as $cambio) {
2272        $solucion[] = $cambio['body'];
2273      }
2274      $output = count($solucion)? theme('item_list', $solucion) : t('No se encontrarón cambios en la situación actual del descriptor');
2275
2276      $row[] = array('data' => $output);
2277      $redirect = $_GET["q"];
2278      if ($acceso && $descriptor['year'] == $year) {
2279        $acciones = array();
2280        $acciones[] = l(t('Editar Descriptor'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/descriptor', array('query' => array('destination' => $redirect)));
2281        $acciones[] = l(t('Consultar Causas'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/causas/ver', array('query' => array('destination' => $redirect)));
2282        $acciones[] = l(t('Agregar Causas'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/causas', array('query' => array('destination' => $redirect)));
2283        $acciones[] = l(t('Consultar Cambios en la situación actual'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/cambios/ver', array('query' => array('destination' => $redirect)));
2284        $acciones[] = l(t('Agregar Cambios en la situación actual'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/cambios', array('query' => array('destination' => $redirect)));
2285        $acciones[] = l(t('Eliminar Descriptor'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/eliminar', array('query' => array('destination' => $redirect)));
2286      }
2287      if (count($acciones)) {
2288        $row[] = array('data' => theme('item_list', $acciones));
2289      }
2290      $rows[] = $row;
2291    }
2292
2293  }
2294  else {
2295    $row = array();
2296    $row[] = array('data' => t('No se encontrarón descriptores para este ente'), 'colspan' => count($headers_table));
2297    $rows[] = $row;
2298  }
2299  return theme('table', $headers_table, $rows);
2300}
2301
2302/*
2303 * Implementation of _get_situacion_explicacion_acceso()
2304 * Obtiene el acceso de modificar descriptores
2305 */
2306function _get_situacion_explicacion_acceso_hijos($ente_planificador, $tipo_plan = 'interpretacion', $descriptor = 0) {
2307  global $user;
2308  $ente_obj = (object) $ente_planificador['level'];
2309  $ente_obj->tipo = $ente_obj->level;
2310  $ente_obj->type = 'ente_planificador';
2311  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_obj);
2312  $current_time = time();
2313  $ente = usuario_tiene_ente($user->uid);
2314  $mi_ente = user_access('admin all planificador') || ($ente && $ente->nid && $ente->nid == $ente_planificador['nid']);
2315  return $mi_ente && (($mi_fecha[1]  + 86399 > $current_time) && ($mi_fecha[0] < $current_time) && (!$descriptor || ($descriptor->type == 'descriptores' && $descriptor->field_descriptores_year[0]['value'] == variable_get('situacional_actual_preliminar_anho_creacion', 0))));
2316}
2317
2318/*
2319 * Implementation of _get_situacion_explicacion_acceso()
2320 * Obtiene el acceso de modificar descriptores
2321 */
2322function _get_situacion_explicacion_importar_acceso($ente_planificador, $tipo_plan = array()) {
2323  return $tipo_plan['plan'] == 'situacion_actual' && $tipo_plan['ente_type'][$ente_planificador->tipo] && _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan, 0);
2324}
2325
2326
2327
2328/*
2329 * Implementation of _get_situacion_explicacion_acceso()
2330 * Obtiene el acceso de modificar descriptores
2331 */
2332function _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan = array(), $descriptor = 0) {
2333  global $user;
2334  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
2335  $current_time = time();
2336  $ente = usuario_tiene_ente($user->uid);
2337  $campo = 'field_descriptores_' . $tipo_plan['short'];
2338  $mi_ente = user_access('admin all planificador') || ($ente && $ente->nid && $ente->nid == $ente_planificador->nid);
2339  return $mi_ente && (($mi_fecha[1]  + 86399 > $current_time) && ($mi_fecha[0] < $current_time) && (!$descriptor || ($descriptor->type == 'descriptores' && $descriptor->{$campo}[0]['value'] && $descriptor->field_descriptores_year[0]['value'] == variable_get('situacional_actual_preliminar_anho_creacion', 0))));
2340}
2341
2342/*
2343 * Implementation of _get_situacion_actual_listar_descriptores_all()
2344 * Obtiene todos los descriptores de un ente planificador
2345 */
2346function _get_situacion_actual_listar_descriptores_all($ente_planificador, $tipo_plan = array(), $micro = 0, $year = 0) {
2347  global $user;
2348  $title = t($tipo_plan['title_long']);
2349  $contenido_ente = '';
2350  $redirect = $_GET["q"];
2351  if (isset($tipo_plan['ente_type'][$ente_planificador->tipo]) && $tipo_plan['ente_type'][$ente_planificador->tipo]) {
2352    $acceso = _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan);
2353    $title = t($tipo_plan['title_ente'], array('@ente' => $ente_planificador->title));
2354    $contenido_ente = _display_situacion_actual_listar_all_descriptores($ente_planificador->nid, $tipo_plan, $acceso, $year);
2355
2356    if ($acceso) {
2357      $links[] = l(t('Agregar Descriptor'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/agregar/descriptor', array('query' => array('destination' => $redirect)));
2358      if ($tipo_plan['plan'] == 'situacion_actual') {
2359        $planns = _situacion_actual_preliminar_get_planns();
2360        $plan = $planns['version'];
2361        $links[] = l(t('Importar Descriptores desde @plan', array('@plan' => $plan['title'])), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/descriptor', array('query' => array('destination' => $redirect)));
2362      }
2363      if ($tipo_plan['plan'] != 'situacion_actual' && (count($ente_planificador->ente_planificador_hierarchical['children']) || user_access('admin planificador'))) {
2364        $links[] = l(t('Importar Causas usando Web semántica'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/causas', array('query' => array('destination' => $redirect)));
2365        $links[] = l(t('Importar Causas'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/causas_texto', array('query' => array('destination' => $redirect)));
2366
2367        $links[] = l(t('Importar Cambios en la situación actual usando Web semántica'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/cambios', array('query' => array('destination' => $redirect)));
2368        $links[] = l(t('Importar Cambios en la situación actual'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/cambios_texto', array('query' => array('destination' => $redirect)));
2369        $links[] = l(t('Importar Descriptor usando Web semántica'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/descriptores', array('query' => array('destination' => $redirect)));
2370        $links[] = l(t('Importar Descriptor'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/descriptores_texto', array('query' => array('destination' => $redirect)));
2371      }
2372    }
2373    $contenido_ente .= '<div class="planificacion-explicacion">' . $contenido . theme('item_list', $links) . '</div>';
2374  }
2375  //se muestran las herencias de entes
2376  $links = array();
2377  if (isset($ente_planificador->ente_planificador_hierarchical[$tipo_plan['hierarchical']])) {
2378    $tipo_allow = $ente_planificador->tipo + $tipo_plan['hierarchical_ente'];
2379    $all_children = $ente_planificador->tipo < $tipo_allow;
2380    $entes = array();
2381    if ($tipo_allow > 0 && $tipo_allow <= variable_get('ente_planificador_hierarchical_count', 2)) {
2382      $entes = array();
2383      $levels = array();
2384      $hierarchical = $ente_planificador->ente_planificador_hierarchical[$tipo_plan['hierarchical']];
2385      foreach($hierarchical as $ente){
2386        $levels[$ente['level']] = $ente;
2387        if ($ente['level'] == $tipo_allow || ($all_children && $ente['level'] > $tipo_allow)) {
2388          $entes[$ente['nid']] = $ente['title'];
2389        }
2390      }
2391    }
2392    //en caso de que $tipo_allow no se encuentrem se muestra el siguiente nivel si tiene el tipo
2393    if (!count($entes) && $tipo_plan['hierarchical'] == 'fathers') {
2394      $tipo_allow += $tipo_plan['hierarchical_ente'];
2395      $encontrado = FALSE;
2396      while(!$encontrado && $tipo_allow >= 0 && $tipo_allow <= variable_get('ente_planificador_hierarchical_count', 2)) {
2397        if (isset($levels[$tipo_allow]) && isset($tipo_plan['ente_type'][$tipo_allow])) {
2398          $entes[$ente['nid']] = $ente['title'];
2399          $encontrado = TRUE;
2400        }
2401        $tipo_allow += $tipo_plan['hierarchical_ente'];
2402      }
2403    }
2404    $links = array();
2405    foreach($entes as $nid => $ente) {
2406      $contenido .= '';
2407      $contenido_hijos = '';
2408      if ($nid == $micro) {
2409        $acceso_hijo = _get_situacion_explicacion_acceso_hijos($nid, $tipo_plan['plan']);
2410        $contenido_hijos .= _display_situacion_actual_listar_all_descriptores($nid, $tipo_plan, $acceso_hijo, $year);
2411        $agregar = '';
2412        if ($acceso_hijo) {
2413          $agregar = l(t('Agregar Descriptor'), 'planificacion/' . $nid . '/explicacion/' . $tipo_plan['plan'] . '/agregar/descriptor', array('query' => array('destination' => $redirect)));
2414        }
2415        $contenido_hijos .= '<div class="planificacion-explicacion">' . $contenido_version . $agregar . '</div>';
2416      }
2417      $enlace = l($ente, 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $nid);
2418      $links[] = $enlace . $contenido_hijos;
2419    }
2420  }
2421  if (count($links)) {
2422    $contenido_hijos = $ente_planificador->tipo < $tipo_allow ? '<h3>' . t('Interpretación preliminar de la explicación situacional de mis entes adscriptos') . '</h3>' : '';
2423    $contenido_hijos .= theme('item_list', $links);
2424  }
2425  drupal_set_title($title);
2426  return $contenido_ente . $contenido_hijos;
2427}
2428
2429/*
2430 * Implementation of ente_planificador_view_situacion_explicacion()
2431 * Display Versión Preliminar page
2432 */
2433function ente_planificador_view_situacion_explicacion($ente_planificador, $tipo_plan = 'interpretacion', $children = 0, $year = 0) {
2434  global $user;
2435  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
2436  $current_time = time();
2437  $fecha = FALSE;
2438  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2439    $fecha = TRUE;
2440  }
2441  if (!$fecha) {
2442    muestra_mensaje($tipo_plan, $ente_planificador);
2443  }
2444  else {
2445    $ente = usuario_tiene_ente($user->uid);
2446    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
2447      muestra_mensaje($tipo_plan, $ente_planificador, 0);
2448    }
2449  }
2450  $planns = _situacion_actual_preliminar_get_planns();
2451  $plan = $planns[$tipo_plan];
2452  $year = $year? $year : variable_get('situacional_actual_preliminar_anho_creacion', 0);
2453  $output = _get_situacion_actual_listar_descriptores_all($ente_planificador, $plan, $children, $year);
2454  return $output;
2455}
2456
2457/*
2458 * Implementation of _situacion_actual_preliminar_node_estructura()
2459 * Clona un nodo de la situación actual preliminar
2460 */
2461function _situacion_actual_preliminar_node_estructura() {
2462  return array(
2463    'ente_planificador' => array(
2464      'node_type' => array(
2465        'descriptores' => array(
2466          'field_descriptores_planificador' => 'field_descriptores_planificador',
2467        ),
2468        'causas' => array(
2469          'field_ente_planifiador' => 'field_ente_planifiador',
2470        ),
2471        'cambios' => array(
2472          'field_cambios_ente' => 'field_cambios_ente',
2473        ),
2474      ),
2475      'value_type' => 'nid',
2476    ),
2477    'link_node' => array(
2478      'node_type' => array(
2479        'descriptores' => array(
2480          'causas' => 'field_descriptores_causa',
2481          'cambios' => 'field_descriptor_cambio',
2482        ),
2483        'causas' => array(
2484          'descriptores' => 'field_descriptores_causa',
2485        ),
2486        'cambios' => array(
2487          'descriptores' => 'field_cambios_descriptor',
2488        ),
2489      ),
2490      'value_type' => 'nid',
2491    ),
2492    'year' => array(
2493      'node_type' => array(
2494        'descriptores' => array(
2495          'field_descriptores_year' => 'field_descriptores_year',
2496        ),
2497        'causas' => array(
2498          'field_causas_year' => 'field_causas_year',
2499        ),
2500        'cambios' => array(
2501        ),
2502      ),
2503      'value_type' => 'value',
2504    ),
2505  );
2506}
2507
2508/*
2509 * Implementation of _situacion_actual_preliminar_clonar()
2510 * Clona un nodo de la situación actual preliminar
2511 */
2512function _situacion_actual_preliminar_clonar($nid = 0, $nodeenlace = array()) {
2513  global $user;
2514  module_load_include('inc', 'node', 'node.pages');
2515  $arreglo = _situacion_actual_preliminar_node_estructura();
2516  $node = !is_object($nid)? node_load($nid) : $nid;
2517  $enlaces = array();
2518  $enlace_existe = array();
2519  $new_nodeenlace = array();
2520  if ($node) {
2521    $node_load = clone $node;
2522    unset($node_load->nid);
2523    unset($node_load->vid);
2524    unset($node_load->created);
2525    unset($node_load->changed);
2526    unset($node_load->revision_uid);
2527    unset($node_load->path);
2528    unset($node_load->data);
2529    unset($node_load->current_revision_id);
2530    unset($node_load->is_current);
2531    unset($node_load->num_revisions);
2532    $node_load->uid = $user->uid;
2533    $node_load->is_new = 1;
2534    foreach($arreglo as $id => $tipo) {
2535      $valor = isset($nodeenlace[$id]) ? $nodeenlace[$id] : 0;
2536      $campos = isset($tipo['node_type'][$node->type])? $tipo['node_type'][$node->type] : array();
2537      foreach($campos as $campo) {
2538        $node_load->{$campo} = array();
2539        if (!$valor  && $id == 'link_node') {
2540          foreach($node->{$campo} as $link) {
2541            if ($link[$tipo['value_type']]) {
2542              $enlaces[] = array(
2543                'value' => $link[$tipo['value_type']],
2544                'campo' => $campo,
2545              );
2546            }
2547          }
2548        }
2549        elseif($valor) {
2550          $node_load->{$campo}[][$tipo['value_type']] = $valor;
2551          $new_nodeenlace[$id] = $valor;
2552          if ($id == 'link_node') {
2553            $enlace_exist[] = array(
2554              'value' => $valor,
2555              'campo' => $campo,
2556              'node_type' => $node->type,
2557            );
2558          }
2559        }
2560      }
2561    }
2562    node_save($node_load);
2563    //si existen enlaces que agregar
2564    if ($node_load && count($enlaces)) {
2565      $new_nodeenlace['link_node'] = $node_load->nid;
2566      foreach ($enlaces as $nid) {
2567        if ($node_load->{$nid['campo']}[0]['nid'] == 0) {
2568          $node_load->{$nid['campo']} = array();
2569        }
2570
2571        $enlace = _situacion_actual_preliminar_clonar($nid['value'], $new_nodeenlace);
2572        if ($enlace && $enlace->nid) {
2573          $node_load->{$nid['campo']}[]['nid'] = $enlace->nid;
2574        }
2575      }
2576      node_save($node_load);
2577    }
2578  }
2579  return $node_load;
2580}
2581
2582
2583/*
2584 * Implementation of hook_node_info()
2585 */
2586function situacion_actual_preliminar_node_info() {
2587  return array(
2588    //se agrega el nodo causas
2589    'causas' => array(
2590      'name' => t('Causas'),
2591      'description' => '',
2592      'has_body' => TRUE,
2593      'title_label' => 'Acrónimo de la causa',
2594      'has_title' => TRUE,
2595      'body_label' => 'Causa',
2596      'module' => 'situacion_actual_preliminar',
2597    ),
2598    //se agrega el nodo descriptores
2599    'descriptores' => array(
2600      'name' => t('Descriptores'),
2601      'description' => '',
2602      'has_body' => TRUE,
2603      'title_label' => 'Acrónimo del descriptor',
2604      'has_title' => TRUE,
2605      'body_label' => 'Descriptor',
2606      'module' => 'situacion_actual_preliminar',
2607    ),
2608    //se agrega el nodo cambios en la situacion actual
2609    'cambios' => array(
2610      'name' => t('Cambios en la Situación Actual'),
2611      'description' => '',
2612      'has_body' => TRUE,
2613      'title_label' => 'Acrónimo del cambio',
2614      'has_title' => TRUE,
2615      'body_label' => 'Descripción del cambio',
2616      'module' => 'situacion_actual_preliminar',
2617    ),
2618  );
2619}
2620
2621/*
2622 * Implementation of hook_form()
2623 */
2624function situacion_actual_preliminar_form(&$node, $form_state) {
2625  return node_content_form($node, $form_state);
2626}
2627
2628/**
2629 * Implements hook_theme().
2630 */
2631function situacion_actual_preliminar_theme() {
2632  if (module_exists('views_semantic')) {
2633  return array(
2634      'situacion_actual_views_semantic' => array(
2635        'arguments' => array(
2636          'reports' => array(),
2637          'wrid' => 0,
2638          'reports_format' => 'rep',
2639        ),
2640      ),
2641    );
2642  }
2643}
2644
2645/**
2646 * Implementation of hook_views_api().
2647 */
2648function situacion_actual_preliminar_views_api() {
2649  return array(
2650    'api' => '2',
2651    'path' => drupal_get_path('module', 'situacion_actual_preliminar') . '/views',
2652  );
2653}
2654
2655/**
2656 * Implementation of hook_views_semantic_links_op_alter()
2657 */
2658function situacion_actual_preliminar_views_semantic_links_op_alter(&$links, $link) {
2659/*
2660  $links['views-semantic-op-' . $link['key']]['exportar'] = array(
2661    'name' => t('Exportar'),
2662    'link' => '#',
2663    'description' => t('Exportar contenido'),
2664    'class' => 'views-semantic-op-exportar',
2665    'target' => '_self',
2666  );
2667*/
2668  $path = drupal_get_path('module', 'situacion_actual_preliminar');
2669  drupal_add_js($path . '/js/situacion_actual_preliminar.js', 'module', 'footer');
2670}
2671
2672/**
2673 * Save values to web semantic
2674 */
2675function planificacion_cambios_js() {
2676  global $user;
2677  $ente = usuario_tiene_ente($user->uid);
2678  $values = json_decode(file_get_contents('php://input'));
2679
2680  if (!$ente->nid || (!$values || !is_object($values))) {
2681    drupal_not_found();
2682  }
2683  else {
2684    //se estrae los nodos a clonar
2685    $nids = property_exists($values, 'element_nid') ? $values->element_nid : array();
2686    $id_reference = property_exists($values, 'descriptor_nid')? $values->descriptor_nid : 0;
2687    $arreglo = array();
2688    $arreglo['ente_planificador'] = $ente->nid;
2689    $arreglo['year'] = variable_get('situacional_actual_preliminar_anho_creacion', 0);
2690    if ($id_reference) {
2691      $arreglo['link_node'] = $id_reference;
2692    }
2693    $nodos = array();
2694    foreach ($nids as $nid) {
2695      $nodos[] = _situacion_actual_preliminar_clonar($nid, $arreglo);
2696    }
2697
2698    if ($id_reference) {
2699      $descriptor = node_load($id_reference);
2700      $arreglo = _situacion_actual_preliminar_node_estructura();
2701      foreach ($nodos as $node) {
2702        $nuevo_campo = $arreglo['link_node']['node_type'][$descriptor->type][$node->type];
2703        if (empty($descriptor->{$nuevo_campo}[0]['nid']) || $descriptor->{$nuevo_campo}[0]['nid'] == 0) {
2704          $descriptor->{$nuevo_campo} = array();
2705        }
2706        $descriptor->{$nuevo_campo}[]['nid'] = $node->nid;
2707      }
2708      node_save($descriptor);
2709    }
2710    print drupal_to_js(array('data' => $nodos, 'status' => true));
2711  }
2712  exit();
2713}
2714
2715/**
2716 * Genera el ahah para el display de cada vista
2717 */
2718function situacional_actual_preliminar_views_js($proceso, $tipo) {
2719  $form_state = array('submitted' => FALSE);
2720  $form_build_id = $_POST['form_build_id'];
2721  // Add the new element to the stored form. Without adding the element to the
2722  // form, Drupal is not aware of this new elements existence and will not
2723  // process it. We retreive the cached form, add the element, and resave.
2724  $form = form_get_cache($form_build_id, $form_state);
2725
2726  $view_name = $_POST['situacion_actual_preliminar_' . $proceso . '_' . $tipo];
2727  $options = array('_none' => 'Ninguna');
2728  $view =  views_get_view($view_name);
2729  foreach ($view->display as $key => $display) {
2730    $options[$key] = $display->display_title;
2731  }
2732
2733  $form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso . '_' . $tipo] = array(
2734    '#title' => t("Seleccione el display de la vista"),
2735    '#type' => 'select',
2736    '#default_value' => variable_get('situacion_actual_preliminar_display_views_' . $proceso . '_' . $tipo, 0),
2737    '#options' => $options,
2738    '#requerid' => TRUE,
2739  );
2740
2741
2742  form_set_cache($form_build_id, $form, $form_state);
2743  $form += array(
2744    '#post' => $_POST,
2745    '#programmed' => FALSE,
2746  );
2747  // Rebuild the form.
2748  $form = form_builder($_POST['form_id'], $form, $form_state);
2749
2750  $new_form = array();
2751
2752  unset($form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso  . '_' . $tipo]['#prefix']);
2753  unset($form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso  . '_' . $tipo]['#suffix']);
2754  $new_form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso  . '_' . $tipo] = $form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso . '_' . $tipo];
2755
2756  $output = drupal_render($new_form);
2757  print drupal_to_js(array('data' => $output, 'status' => true));
2758  exit();
2759}
2760
2761/*
2762 * Implementation of _ente_planificador_cambios_situacion_actual_ver()
2763 * Consultar los cambios de un descriptor
2764 */
2765function situacion_actual_premilimar_importar_datos($ente_planificador,  $tipo_plan = array(), $tipo = 'causas') {
2766  global $user;
2767  $tipos = array(
2768    'causas' => t('Causas'),
2769    'descriptores' => t('Descriptores'),
2770    'cambios' => t('Cambios de la Situación Actual'),
2771    'causas_texto' => t('Causas (Texto)'),
2772    'descriptores_texto' => t('Descriptores (Texto)'),
2773    'cambios_texto' => t('Cambios de la Situación Actual (Texto)'),
2774  );
2775  $view_id = variable_get('situacion_actual_preliminar_' . $tipo_plan['plan'] . '_' . $tipo, 0);
2776  $view = views_get_view($view_id);
2777  $display_id = variable_get('situacion_actual_preliminar_display_views_' . $tipo_plan['plan'] . '_' . $tipo, 'default');
2778  $view->set_display($display_id);
2779
2780  $title = $tipos[$tipo];
2781  drupal_set_title(t('Importar @name ("@tipo")', array('@name' => $tipo_plan['title'], '@tipo' => $title)));
2782
2783  $view->override_path = $_GET['q'];
2784  $view->pre_execute();
2785  $view->execute();
2786  $output = $view->render();
2787
2788  $url = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'];
2789  $links = array();
2790  $links[] = l(t('Regresar'), $url);
2791  return $output . theme('item_list', $links);
2792}
2793
2794/*
2795 * Implementation of _get_situacion_explicacion_acceso()
2796 * Obtiene el acceso de modificar descriptores
2797 */
2798function _get_situacion_explicacion_acceso_hijos_importar($ente_planificador, $tipo_plan = 'interpretacion', $tipo = 'causas') {
2799  return _get_situacion_explicacion_acceso_hijos((array) $ente_planificador, $tipo_plan) || count($ente_planificador->ente_planificador_hierarchical['children']) || user_access('admin planificador');
2800}
2801
2802/*
2803 * Implementation of ente_planificador_descriptores_importar_form()
2804 * Importar descriptores
2805 */
2806function situacional_actual_preliminar_importar_descriptor_form($form_state, $ente_planificador = 0, $nid = 0, $tipo = '', $descriptores = array()) {
2807  global $user;
2808  $form = array();
2809  $planns = _situacion_actual_preliminar_get_planns();
2810  $plan = $planns['version'];
2811  $year = variable_get('situacional_actual_preliminar_anho_creacion', 0);
2812  $form = array();
2813  $form['#import_nid'] = $nid;
2814  $form['#type_node'] = $tipo;
2815  $form['#year'] = $year;
2816  $form['#plan'] = $plan;
2817  $form['#ente_planificador'] = $ente_planificador;
2818  $form['#descriptores'] = $descriptores;
2819  $textos = array(
2820    'descriptores' => t('el Descriptor'),
2821    'causas' => t('la Causa'),
2822    'cambios' => t('el Cambio en la situación actual'),
2823
2824  );
2825  $form['#textos'] = $textos;
2826  if ($form['#ente_planificador']->nid) {
2827    if ($tipo == 'causas' || $tipo == 'cambios') {
2828      if (!count($descriptores)) {
2829        $descriptores = _get_situacion_actual_listar_all_descriptores($ente->nid, $plan, variable_get('situacional_actual_preliminar_anho_creacion', 0));
2830      }
2831      $options = array();
2832      foreach ($descriptores as $nid => $descriptor) {
2833        $options[$nid] = $descriptor['body'];
2834      }
2835      $form['descriptor'] = array(
2836        '#type' => 'select',
2837        '#title' => t('Descriptor'),
2838        '#description' => t('Seleccione el descriptor.'),
2839        '#default_value' => isset($context['target_sid']) ? $context['target_sid'] : '',
2840        '#options' => $options,
2841      );
2842    }
2843    $form['buttons']['situacion_preliminar'] = array(
2844      '#type' => 'button',
2845      '#value' => t('Importar @tipo', array('@tipo' => $form['#textos'][$form['#type_node']])),
2846      '#weight' => 20,
2847      '#prefix' => '<div id = "' . 'situacion-preliminar_' . $form['#import_nid'] . '">',
2848      '#suffix' => '</div>',
2849      '#ahah' => array(
2850        'path' => 'planificacion_importar_pdlp_js/' . $tipo .  '/' . $form['#import_nid'],
2851        'wrapper' => 'situacion-preliminar_' . $form['#import_nid'],
2852        'method' => 'replace',
2853        'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
2854      ),
2855    );
2856  }
2857  return $form;
2858}
2859
2860/*
2861 * Implementation of ente_planificador_descriptores_editar_form_submit()
2862 */
2863function situacional_actual_preliminar_importar_descriptor_form_submit($form, &$form_state) {
2864  $nidl = $form['#import_nid'];
2865  $arreglo = array();
2866  $arreglo['ente_planificador'] = $form['#ente_planificador']->nid;
2867  $arreglo['year'] = $form['#year'];
2868  $id_reference = ($form['#type_node'] == 'causas' || $form['#type_node'] == 'cambios')? $form_state['values']['descriptor'] : 0;
2869  if ($nidl) {
2870    if ($id_reference) {
2871      $arreglo['link_node'] = $id_reference;
2872    }
2873    $node_load = _situacion_actual_preliminar_clonar($nidl, $arreglo);
2874    if ($id_reference) {
2875      $descriptor = node_load($id_reference);
2876      $arreglo_l = _situacion_actual_preliminar_node_estructura();
2877      $nuevo_campo = $arreglo_l['link_node']['node_type'][$descriptor->type][$node_load->type];
2878      if (empty($descriptor->{$nuevo_campo}[0]['nid']) || $descriptor->{$nuevo_campo}[0]['nid'] == 0) {
2879        $descriptor->{$nuevo_campo} = array();
2880      }
2881      $descriptor->{$nuevo_campo}[]['nid'] = $node_load->nid;
2882      node_save($descriptor);
2883    }
2884  }
2885  drupal_set_message(t('Se importó @tipo', array('@tipo' => $form['#textos'][$form['#type_node']])));
2886}
2887
2888/*
2889 * Implementation of planificacion_importar_pdlp_js()
2890 * importa el nodo por tipo
2891 */
2892function planificacion_importar_pdlp_js($tipo = '', $nid = 0) {
2893  $form_state = array('submitted' => FALSE);
2894  $form_build_id = $_POST['form_build_id'];
2895  $form = form_get_cache($form_build_id, $form_state);
2896  $nidl = $form['#import_nid'];
2897  $arreglo = array();
2898  $arreglo['ente_planificador'] = $form['#ente_planificador']->nid;
2899  $arreglo['year'] = $form['#year'];
2900  $id_reference = ($form['#type_node'] == 'causas' || $form['#type_node'] == 'cambios') && intval($_POST['descriptor']) > 0? intval($_POST['descriptor']) : 0;
2901  if ($nidl) {
2902    if ($id_reference) {
2903      $arreglo['link_node'] = $id_reference;
2904    }
2905    $node_load = _situacion_actual_preliminar_clonar($nidl, $arreglo);
2906    if ($id_reference) {
2907      $descriptor = node_load($id_reference);
2908      $arreglo_l = _situacion_actual_preliminar_node_estructura();
2909      $nuevo_campo = $arreglo_l['link_node']['node_type'][$descriptor->type][$node_load->type];
2910      if (empty($descriptor->{$nuevo_campo}[0]['nid']) || $descriptor->{$nuevo_campo}[0]['nid'] == 0) {
2911        $descriptor->{$nuevo_campo} = array();
2912      }
2913      $descriptor->{$nuevo_campo}[]['nid'] = $node_load->nid;
2914      node_save($descriptor);
2915    }
2916  }
2917  unset($form['buttons']['submit']);
2918  form_set_cache($form_build_id, $form, $form_state);
2919  $form += array(
2920    '#post' => $_POST,
2921    '#programmed' => FALSE,
2922  );
2923  // Rebuild the form.
2924  $form = form_builder($_POST['form_id'], $form, $form_state);
2925  $texto = t('Se importó @tipo', array('@tipo' => $form['#textos'][$form['#type_node']]));
2926  print drupal_to_js(array('data' => $texto, 'status' => true));
2927  exit();
2928}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.