source: sipes/0.3-modules/situacion_actual_preliminar/situacion_actual_preliminar.module @ 2bc6c7e

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

se corregio problema del nid en el ahah

  • Propiedad mode establecida a 100755
File size: 115.5 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 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 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      $row = array();
1368      $row[] = array('data' => $cambio_load->body);
1369      $k = 0;
1370      foreach($array as $id_pdp => $texto) {
1371        $texto_out = '';
1372        $term_id = 0;
1373        if ($k < 4 && isset($cambio_load->field_cambios_pdp[$k]['value'])) {
1374          $term_id = $cambio_load->field_cambios_pdp[$k]['value'];
1375        }elseif(!$term_id && $k == 4 && isset($cambio_load->field_cambios_carabobo[0]['value'])) {
1376          $term_id = $cambio_load->field_cambios_carabobo[0]['value'];
1377        }
1378        if ($term_id) {
1379          $term = taxonomy_get_term($term_id);
1380          if ($term && $k < 4) {
1381            $texto_out = $term->name . ' ' . $term->description;
1382          }
1383          else {
1384            $valores = term_fields_get_fields_values($term);
1385            $texto_out = $valores && isset($valores['plan_carabobo_meta_value'])? $valores['plan_carabobo_meta_value'] : '';
1386          }
1387        }
1388        $row[] = array('data' => $texto_out);
1389        $k++;
1390      }
1391      $metas = array();
1392      foreach($cambio_load->field_cambios_meta as $meta) {
1393        $unidad = $meta['tid'];
1394        // If this term's vocabulary supports localization.
1395        $term = taxonomy_get_term($meta['tid']);
1396        if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
1397          $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
1398        }
1399        $numero = number_format($meta['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']);
1400        $metas[] = $numero . ' ' . $term->name;
1401      }
1402      $row[] = array('data' => theme('item_list', $metas));
1403      if ($acceso) {
1404        $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');
1405        if ($_REQUEST['destination']) {
1406          $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'])));
1407        }
1408        $row[] = array('data' => $url);
1409
1410      }
1411      $rows[] = $row;
1412    }
1413  }
1414  if (!count($rows)) {
1415    $row = array();
1416    $row[] = array('data' => t('No se encontrarón Cambios en la Situación Actual para este descriptor'), 'colspan' => count($headers_table));
1417    $rows[] = $row;
1418  }
1419  $url = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'];
1420  $links = array();
1421  //$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)));
1422
1423  if ($acceso && $tipo_plan['plan'] != 'situacion_actual' &&(count($ente_planificador->ente_planificador_hierarchical['children'])|| user_access('admin planificador'))) {
1424    $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)));
1425    $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)));
1426  }
1427  $links[] = l(t('Regresar'), $url);
1428  return theme('table', $headers_table, $rows) . theme('item_list', $links);
1429}
1430
1431/*
1432 * Implementation of ente_planificador_cambios_situacion_actual_seleccionar_form()
1433 * Seleccionar cambios en la situacion actual en descriptores
1434 */
1435function ente_planificador_cambios_situacion_actual_seleccionar_form($form_state, $ente_planificador,  $tipo_plan = array(), $descriptor = 0) {
1436  global $user;
1437  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
1438  $current_time = time();
1439  $fecha = FALSE;
1440  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1441    $fecha = TRUE;
1442  }
1443  if (!$fecha) {
1444    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
1445  }
1446  else {
1447    $ente = usuario_tiene_ente($user->uid);
1448    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
1449      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
1450    }
1451  }
1452  drupal_set_title(t('Agregar Cambios en la Situación Actual'));
1453  $form = array();
1454  $cambios_select = array();
1455  foreach($descriptor->field_descriptor_cambio as $cambio) {
1456    if ($cambio['nid']) {
1457      $cambios_select[$cambio['nid']] = 1;
1458    }
1459  }
1460  $array_pdlp = _situacion_actual_preliminar_get_pdlp();
1461
1462
1463  $prefijo = '<table width="100%" style="border: 0;"><tr><th>';
1464  $header = array();
1465  $header[] = t('Eliminar');
1466  $header[] = t('Descripción del cambio');
1467  foreach($array_pdlp as $id_pdp => $texto) {
1468    $header[] = $texto;
1469  }
1470  $header[] = t('Meta asociada al cambio');
1471  $header[] = t('Acción');
1472  $prefijo .= implode('</th><th>', $header) .  '</th></tr>';
1473  $form = array();
1474  $form['#tipo_plan'] = $tipo_plan;
1475  $cambios_load = array();
1476  if (!count($cambios_select)) {
1477    $prefijo .= '<tr><td colspan="6">' . t('No se han ingresado Cambios en la Situación Actual del descriptor') . '&nbsp;</td></tr>';
1478    $form['seleccionar'] = array(
1479      '#value' => $prefijo,
1480    );
1481  }
1482  else {
1483    foreach($descriptor->field_descriptor_cambio as $cambio) {
1484      $cambio_load = node_load($cambio['nid']);
1485      if ($cambio_load) {
1486        $cambios_load[$cambio_load->nid] = $cambio_load;
1487        $metas = array();
1488        $suffix = '</td><td>' . $cambio_load->body . '</td>';
1489        $k = 0;
1490        foreach($array_pdlp as $id_pdp => $texto) {
1491          $texto_out = '';
1492          $term_id = 0;
1493          if ($k < 4 && isset($cambio_load->field_cambios_pdp[$k]['value'])) {
1494            $term_id = $cambio_load->field_cambios_pdp[$k]['value'];
1495          }elseif(!$term_id && $k == 4 && isset($cambio_load->field_cambios_carabobo[0]['value'])) {
1496            $term_id = $cambio_load->field_cambios_carabobo[0]['value'];
1497          }
1498          if ($term_id) {
1499            $term = taxonomy_get_term($term_id);
1500            if ($term && $k < 4) {
1501              $texto_out = $term->name . ' ' . $term->description;
1502            }
1503            else {
1504              $valores = term_fields_get_fields_values($term);
1505              $texto_out = $valores && isset($valores['plan_carabobo_meta_value'])? $valores['plan_carabobo_meta_value'] : '';
1506            }
1507          }
1508          $suffix .= '</td><td>' . $texto_out . '</td>';
1509          $k++;
1510        }
1511        foreach($cambio_load->field_cambios_meta as $meta) {
1512          $unidad = $meta['tid'];
1513          // If this term's vocabulary supports localization.
1514          $term = taxonomy_get_term($meta['tid']);
1515          if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
1516            $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
1517          }
1518          $numero = number_format($meta['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']);
1519          $metas[] = $numero . ' ' . $term->name;
1520        }
1521        $suffix .= '</td><td>' . theme('item_list', $metas) . '</td>';
1522        $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');
1523        if ($_REQUEST['destination']) {
1524          $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'])));
1525        }
1526        $suffix .= '</td><td>' . $url . '</td></tr>';
1527
1528        $pdlp = '';
1529        if (isset($cambio_load->field_cambios_pdp[$cant - 1]['value'])) {
1530          $term = taxonomy_get_term($cambio_load->field_cambios_pdp[$cant - 1]['value']);
1531          if ($term) {
1532            $pdlp = $term->name . ' ' . $term->description;
1533          }
1534        }
1535        $carabobo = '';
1536        if (isset($cambio_load->field_cambios_carabobo[0]['value'])) {
1537          $term = taxonomy_get_term($cambio_load->field_cambios_carabobo[0]['value']);
1538          if ($term) {
1539            $valores = term_fields_get_fields_values($term);
1540            if ($valores && isset($valores['plan_carabobo_meta_value'])) {
1541              $carabobo = $valores['plan_carabobo_meta_value'];
1542            }
1543          }
1544        }
1545        $form['seleccionar_' . $cambio_load->nid] = array(
1546          '#type' => 'checkbox',
1547          '#title' => '',
1548          '#default_value' => 0,
1549          '#prefix' => $prefijo . '<tr><td>',
1550          '#suffix' =>$suffix,
1551        );
1552        $prefijo = '';
1553      }
1554    }
1555    //$form['seleccionar_' . $cambio_load->nid]['#suffix'] .= '</table>';
1556  }
1557  $form['#ente_planificador'] = $ente_planificador;
1558  $form['#descriptor'] = $descriptor;
1559  $form['#array_pdlp'] = $array_pdlp;
1560  $form['#cambios_load'] = $cambios_load;
1561  $form['#cambios_select'] = $cambios_select;
1562  $form['buttons']['#weight'] = 1000;
1563  $form['agregar'] = array(
1564    '#type' => 'submit',
1565    '#prefix' => '<tr><td colspan="' . count($header) . '" align="center">',
1566    '#suffix' => '</td></tr></table>',
1567    '#value' => t('Agregar Cambio en la Situación Actual'),
1568  );
1569  if (count($form['#cambios_load'])) {
1570    $form['buttons']['submit'] = array(
1571      '#type' => 'submit',
1572      '#value' => t('Eliminar Cambios en la Situación Actual'),
1573      '#weight' => 99,
1574    );
1575  }
1576  $form['buttons']['cancel'] = array(
1577    '#type' => 'submit',
1578    '#value' => t('Regresar'),
1579    '#weight' => 101,
1580  );
1581  return $form;
1582}
1583
1584/*
1585 * Implementation of ente_planificador_cambios_situacion_actual_seleccionar_form_validate()
1586 * Validar Agregar o editar cambios
1587 */
1588function ente_planificador_cambios_situacion_actual_seleccionar_form_validate($form, &$form_state) {
1589  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1590  if ($op == t('Regresar') || $op == t('Agregar Cambio en la Situación Actual')) {
1591    return;
1592  }
1593  if (count($form['#cambios_load'])) {
1594    $seleccionado = FALSE;
1595    foreach($form['#cambios_load'] as $cambio) {
1596      if ($form_state['values']['seleccionar_' . $cambio->nid]) {
1597        $seleccionado = TRUE;
1598      }
1599    }
1600    if (!$seleccionado) {
1601      form_set_error('seleccionar_' . $cambio->nid, t('Debe seleccionar al menos un Cambio en la Situación Actual para eliminar'));
1602    }
1603  }
1604  return;
1605}
1606
1607/*
1608 * Implementation of ente_planificador_cambios_situacion_actual_seleccionar_form_submit()
1609 */
1610function ente_planificador_cambios_situacion_actual_seleccionar_form_submit($form, &$form_state) {
1611  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1612  if ($op == t('Regresar')) {
1613    return;
1614  }
1615  if ($op == t('Agregar Cambio en la Situación Actual')) {
1616    if ($_REQUEST['destination']) {
1617      $form_state['redirect'] = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $form['#descriptor']->nid . '/cambios/agregar',
1618        array(
1619          'query' => array(
1620            'destination' => $_REQUEST['destination'],
1621           ),
1622           'absolute' => TRUE,                     
1623        )
1624      );
1625      unset($_REQUEST['destination']);
1626    }
1627    else {
1628      // add redirect
1629      $form_state['redirect'] = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $form['#descriptor']->nid . '/cambios/agregar';
1630    }
1631    return;
1632  }
1633  module_load_include('inc', 'node', 'node.pages');
1634  $descriptores_cambio = array();
1635  $descriptor = $form['#descriptor'];
1636  $borrados = array();
1637  if (count($form['#cambios_load'])) {
1638    foreach($form['#cambios_load'] as $cambio) {
1639      if (!$form_state['values']['seleccionar_' . $cambio->nid]) {
1640        $descriptores_cambio[] = array('nid' => $cambio->nid);
1641      }
1642      else {
1643        $borrados[] = $cambio->nid;
1644      }
1645    }
1646  }
1647  if (count($borrados)) {
1648    $descriptor->field_descriptor_cambio = $descriptores_cambio;
1649    $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())));
1650  }
1651  $descriptor->revision = 1;
1652  node_save($descriptor);
1653  drupal_set_message(t('Se guardarón los Cambios en la Situación Actual del descriptor @title', array('@title' => $descriptor->body)));
1654}
1655
1656/*
1657 * Implementation of _ente_planificador_cambios_taxonomy()
1658 * Obtiene los terminos hijos de un termino dado y su taxonomia
1659 */
1660function _ente_planificador_cambios_taxonomy($vid = 0, $tid = 0) {
1661  $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);
1662  $terms = array();
1663  while ($term = db_fetch_object($result)) {
1664    $terms[$term->tid] = $term->name . ' ' . $term->description;
1665  }
1666  return $terms;
1667}
1668
1669/*
1670 * planificacion_cambios_pdlp_js
1671 * Genera el plan de la patria
1672 */
1673function planificacion_cambios_pdlp_js($func) {
1674  $form_state = array('submitted' => FALSE);
1675  $form_build_id = $_POST['form_build_id'];
1676  // Add the new element to the stored form. Without adding the element to the
1677  // form, Drupal is not aware of this new elements existence and will not
1678  // process it. We retreive the cached form, add the element, and resave.
1679  $form = form_get_cache($form_build_id, $form_state);
1680  $array = $form['#pdlp'];
1681  $opens_div = '';
1682  $i = 0;
1683  $term_id = 0;
1684  $encontrado = FALSE;
1685  $new_form = array();
1686  $terms = array();
1687  $node_type = content_types('cambios');
1688  $fields = $form['#' . $form['#node']->type . '_campos'];
1689  $vid = $fields['field_cambios_pdp']['vid'];
1690  $inputs_metas = array();
1691  $inputs_metas_sql = array();
1692  $inputs = array();
1693  $inputs[] = $vid;
1694  foreach ($array as $id => $texto) {
1695    $valor = intval($_POST[$id]);
1696    if (!$encontrado && $valor > 0) {
1697      $inputs[] = $valor;
1698      $inputs_metas_sql[] = '%d';
1699    }
1700    if ($encontrado) {
1701      if ($id != 'metas') {
1702        $terms = array(0 => t('Seleccione'),);
1703        if ($term_id || $i == 0) {
1704          $terms += _ente_planificador_cambios_taxonomy($vid, $term_id);
1705        }
1706        $form['pdlp'][$id] = array(
1707          '#type' => 'select',
1708          '#title' => t('Objetivo @tipo', array('@tipo' => $texto)),
1709          '#default_value' => $term_id,
1710          '#options' => $terms,
1711          '#description' => t('Seleccione el Objetivo @tipo.', array('@tipo' => $texto)),
1712          '#required' => TRUE,
1713          '#ahah' => array(
1714            'event' => 'change',
1715            'path' => 'planificacion_cambios_pdlp_js/' . $id,
1716            'wrapper' => 'situacion_preliminar_' . $id,
1717            'method' => 'replace',
1718            'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
1719          ),
1720        );
1721        $term_id = 0;
1722        $ant_term = 0;
1723      }
1724      else {
1725        $terms = array(0 => t('Seleccione'),);
1726        if (count($inputs)) {
1727          $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) . ')';
1728          $result = db_query($sql, $inputs);
1729          $j = 1;
1730          while ($termino = db_fetch_object($result)) {
1731            $meta = trim($termino->meta);
1732            if ($meta != '') {
1733              $terms[$termino->tid] = '(' . $j . ') ' . $meta;
1734              $j++;
1735            }
1736          }
1737        }
1738        $form['pdlp'][$id] = array(
1739          '#type' => 'select',
1740          '#title' => t('@texto_metas (cantidad de metas: @metas)', array('@texto_metas' => $texto, '@metas' => $j - 1)),
1741          '#default_value' => 0,
1742          '#options' => $terms,
1743          '#description' => t('Seleccione la meta del Plan Campaña de Carabobo.'),
1744        );
1745      }
1746      $form['pdlp'][$id]['#prefix'] = '<div id = "situacion_preliminar_' . $id . '">';
1747      $opens_div .= '</div>';
1748      $i++;
1749    }
1750    if ($id == $func) {
1751      $encontrado = TRUE;
1752      $term_id = intval($_POST[$id]) > 0 ? intval($_POST[$id]) : 0;
1753    }
1754  }
1755  if ($encontrado) {
1756    $form['pdlp'][$id]['#suffix'] = $opens_div;
1757  }
1758  //$form += $new_form;
1759  form_set_cache($form_build_id, $form, $form_state);
1760  $form += array(
1761    '#post' => $_POST,
1762    '#programmed' => FALSE,
1763  );
1764  // Rebuild the form.
1765    $form = form_builder($_POST['form_id'], $form, $form_state);
1766  $encontrado = FALSE;
1767  $new_form = array();
1768  foreach ($array as $id => $texto) {
1769    if ($id == $func) {
1770      $encontrado = TRUE;
1771    }
1772    if ($encontrado) {
1773      $new_form[$id] = $form['pdlp'][$id];
1774    }
1775  }
1776  $output = drupal_render($new_form);
1777  print drupal_to_js(array('data' => $output, 'status' => true));
1778  exit();
1779}
1780
1781/*
1782 * Implementation of ente_planificador_cambios_editar_form()
1783 * Agregar o editar Cambio en la Situacion Actual
1784 */
1785function ente_planificador_cambios_editar_form($form_state, $ente_planificador,  $tipo_plan = array(), $descriptor = 0, $node = 0) {
1786  global $user;
1787  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
1788  $current_time = time();
1789  $fecha = FALSE;
1790  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1791    $fecha = TRUE;
1792  }
1793  if (!$fecha) {
1794    muestra_mensaje($tipo_plan['plan'], $ente_planificador);
1795  }
1796  else {
1797    $ente = usuario_tiene_ente($user->uid);
1798    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
1799      muestra_mensaje($tipo_plan['plan'], $ente_planificador, 0);
1800    }
1801  }
1802  $texto = $node ? t('Modificar Cambio en la Situación Actual') :  t('Agregar Cambio en la Situación Actual');
1803  drupal_set_title($texto);
1804  if (!$node) {
1805    $node = new stdClass();
1806    $node->body = '';
1807    $node->type = 'cambios';
1808    $node->uid = $user->uid;
1809    $node->title = 'Cambios-' . $ente_planificador->nid . '-' . time();
1810    $node->field_cambios_ente[0]['nid'] = $ente_planificador->nid;
1811    $campo = 'field_' . $node->type . '_' . $tipo_plan['short'];
1812    $node->{$campo}[0]['value'] = 1;
1813  }
1814  $form['#tipo_plan'] = $tipo_plan;
1815  $form['#ente_planificador'] = $ente_planificador;
1816  $form['#descriptor'] = $descriptor;
1817  $form['#node'] = $node;
1818  if (variable_get('situacion_actual_acronimo', false)) {
1819    $form['title'] = array(
1820      '#type' => 'textfield',
1821      '#title' => t('Acrónimo del Cambio de la situación Actual'),
1822      '#required' => TRUE,
1823      '#default_value' => $node->title,
1824      '#maxlength' => 255,
1825      '#weight' => -5,
1826      '#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.'),
1827    );
1828  }
1829  $form['cambio'] = array(
1830    '#type' => 'textarea',
1831    '#title' => t('Cambio de la Situación Actual'),
1832    '#description' => t('Introduzca el cambio de la Situación Actual.'),
1833    '#default_value' => $node->body,
1834    '#required' => TRUE,
1835  );
1836  //se agrega el plan de la patria
1837  $form['pdlp'] = array(
1838    '#type' => 'fieldset',
1839    '#title' => t('Plan de la Patria'),
1840  );
1841  $array = _situacion_actual_preliminar_get_pdlp();
1842  $opens_div = '';
1843  $i = 0;
1844  $ant_term = 0;
1845  $node_type = content_types('cambios');
1846  $fields = $node_type['fields'];
1847  $vid = $fields['field_cambios_pdp']['vid'];
1848  $inputs = array();
1849  $inputs[] = $vid;
1850  $inputs_metas_sql = array();
1851  foreach ($array as $id => $texto) {
1852    if ($id != 'metas') {
1853      $term_id = $node->field_cambios_pdp[$i]['value'] ? $node->field_cambios_pdp[$i]['value'] : 0;
1854      $terms = array(0 => t('Seleccione'),);
1855      if ($ant_term || $i == 0) {
1856        $terms += _ente_planificador_cambios_taxonomy($vid, $ant_term);
1857      }
1858      $ant_term = $term_id;
1859      if ($term_id) {
1860        $inputs[] = $term_id;
1861        $inputs_metas_sql[] = '%d';
1862      }
1863      $form['pdlp'][$id] = array(
1864        '#type' => 'select',
1865        '#title' => $texto,
1866        '#default_value' => $term_id,
1867        '#options' => $terms,
1868        '#description' => t('Seleccione el Objetivo @tipo.', array('@tipo' => $texto)),
1869        '#required' => TRUE,
1870        '#ahah' => array(
1871          'event' => 'change',
1872          'path' => 'planificacion_cambios_pdlp_js/' . $id,
1873          'wrapper' => 'situacion_preliminar_' . $id,
1874          'method' => 'replace',
1875          'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
1876        ),
1877      );
1878    }
1879    else {
1880      $terms = array(
1881        0 => t('Seleccione'),
1882      );
1883      if (count($inputs)) {
1884        $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) . ')';
1885        $result = db_query($sql, $inputs);
1886        $j = 1;
1887        while ($termino = db_fetch_object($result)) {
1888          $meta = trim($termino->meta);
1889          if ($meta != '') {
1890            $terms[$termino->tid] = '(' . $j . ') ' . $meta;
1891            $j++;
1892          }
1893        }
1894      }
1895      $term_id = $node->field_cambios_carabobo[0]['value'] ? $node->field_cambios_carabobo[0]['value'] : 0;
1896      $form['pdlp'][$id] = array(
1897        '#type' => 'select',
1898        '#title' => t('@texto_metas (cantidad de metas: @metas)', array('@texto_metas' => $texto, '@metas' => $j - 1)),
1899        '#default_value' => $term_id,
1900        '#options' => $terms,
1901        '#description' => t('Seleccione la meta del Plan Campaña de Carabobo.'),
1902      );
1903    }
1904    $form['pdlp'][$id]['#prefix'] = '<div id = "situacion_preliminar_' . $id . '">';
1905    $opens_div .= '</div>';
1906    $i++;
1907  }
1908  $form['pdlp'][$id]['#suffix'] = $opens_div;
1909  //se agrega otros campos de interes
1910  $field_form = array();
1911  $fields_form = array();
1912  $arreglo = array(
1913    'field_cambios_meta' => 'field_cambios_meta',
1914  );
1915  if (is_array($fields) && count($fields)) {
1916    foreach($fields as $field_id => $field) {
1917      if (array_key_exists($field_id, $arreglo)) {
1918        $field_form[] = $field_id;
1919        $fields_form[] = $field_id;
1920      }
1921    }
1922  }
1923  if (is_array($field_form) && count($field_form)) {
1924    module_load_include('inc', 'content', 'includes/content.node_form');
1925    foreach ($field_form as $field_id) {
1926      $field = content_fields($field_id, $form['#node']->type);
1927      $form['#field_info'][$field_id] = $field;
1928      $form += (array) content_field_form($form, $form_state, $field);
1929    }
1930  }
1931  $form['#' . $form['#node']->type . '_campos'] = $fields;
1932  $form['#' . $form['#node']->type . '_fields'] = $fields_form;
1933  $form['#pdlp'] = $array;
1934  $form['buttons']['#weight'] = 100;
1935  $form['buttons']['submit'] = array(
1936    '#type' => 'submit',
1937    '#value' => t('Submit'),
1938    '#weight' => 100,
1939  );
1940  $form['buttons']['cancel'] = array(
1941    '#type' => 'submit',
1942    '#value' => t('Cancel'),
1943    '#weight' => 101,
1944  );
1945  return $form;
1946}
1947
1948/*
1949 * Implementation of ente_planificador_cambios_editar_form_validate()
1950 * Validar Agregar o editar Cambio en la Situacion Actual
1951 */
1952function ente_planificador_cambios_editar_form_validate($form, &$form_state) {
1953  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1954  if ($op == t('Cancel')) {
1955    if ($_REQUEST['destination']) {
1956      $redirect = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios',
1957        array(
1958          'query' => array(
1959            'destination' => $_REQUEST['destination'],
1960           ),
1961           'absolute' => TRUE,                     
1962        )
1963      );
1964    }
1965    else {
1966      // add redirect
1967      $redirect = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios';
1968    }
1969    drupal_goto($redirect);
1970    return;
1971  }
1972  if (trim($form_state['values']['cambio']) == '') {
1973    form_set_error('cambios', t('Debe agregar el cambio de la Situación Actual'));
1974  }
1975  if (count($form['pdlp']['metas']['#options']) > 1 && !$form_state['values']['metas']) {
1976    form_set_error('metas', t('Debe Indicar una meta del Plan Campaña de Carabobo'));
1977
1978  }
1979  return;
1980}
1981
1982/*
1983 * Implementation of ente_planificador_cambios_editar_form_submit()
1984 */
1985function ente_planificador_cambios_editar_form_submit($form, &$form_state) {
1986  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1987  if ($op == t('Cancel')) {
1988    return;
1989  }
1990  module_load_include('inc', 'node', 'node.pages');
1991  $cambio = $form['#node'];
1992  $descriptor = $form['#descriptor'];
1993  node_object_prepare($descriptor);
1994  $form_state['values']['descriptor'] = check_plain($form_state['values']['descriptor']);
1995  if (variable_get('situacion_actual_acronimo', false)) {
1996    $cambio->title = check_plain($form_state['values']['title']);
1997  }
1998  else {
1999    $cambio->title = substr($form_state['values']['cambio'], 0, 244);
2000  }
2001  $cambio->body = $form_state['values']['cambio'];
2002  //crear una nueva revision
2003  $nuevo = TRUE;
2004  if ($cambio->nid) {
2005    $nuevo = FALSE;
2006    $cambio->log = t('Modificados los datos del cambio en la situación actual @date', array('@date' => date('d-m-Y', time())));
2007    $cambio->revision = 1;
2008  }
2009  $encontrado = FAlSE;
2010  if (count($cambio->field_cambios_descriptor)) {
2011    foreach($cambio->field_cambios_descriptor as $enlace) {
2012      if ($enlace['nid'] == $descriptor->nid) {
2013        $encontrado = TRUE;
2014      }
2015    }
2016  }
2017  if (!$encontrado) {
2018    $cambio->field_cambios_descriptor[]['nid'] = $descriptor->nid;
2019  }
2020  $field_form = $form['#' . $form['#node']->type . '_fields'];
2021  module_load_include('inc', 'node', 'node.pages');
2022  $node_load = $form['#node'];
2023  $form_values = $form_state['values'];
2024  //$node_load->title = check_plain($form_values['title']);
2025  if (is_array($field_form) && count($field_form)) {
2026    foreach ($field_form as $field_id) {
2027      if (isset($form_values[$field_id]) && is_array($form_values[$field_id])) {
2028        foreach($form_values[$field_id] as $id => $value) {
2029          if (is_numeric($id) && isset($form_values[$field_id][$id]['_error_element'])) {
2030            unset($form_values[$field_id][$id]['_error_element']);
2031          }
2032        }
2033        $cambio->{$field_id} = $form_values[$field_id];
2034      }
2035    }
2036  }
2037  //se incluye el plan de la patria
2038  $i = 0;
2039  foreach ($form['#pdlp'] as $id => $texto) {
2040    if ($form_values[$id]) {
2041      if ($id == 'metas') {
2042        $cambio->field_cambios_carabobo[0]['value'] = $form_values[$id];
2043      }
2044      else {
2045        $cambio->field_cambios_pdp[$i]['value'] = $form_values[$id];
2046      }
2047    }
2048    $i++;
2049  }
2050  node_save($cambio);
2051  $form['#cambio'] = $cambio;
2052  //se agrega el cambio al descriptor
2053  $encontrado = FAlSE;
2054  if (count($descriptor->field_descriptor_cambio)) {
2055    foreach($descriptor->field_descriptor_cambio as $enlace) {
2056      if ($enlace['nid'] == $cambio->nid) {
2057        $encontrado = TRUE;
2058      }
2059    }
2060  }
2061  if (!$encontrado) {
2062    $descriptor->field_descriptor_cambio[]['nid'] = $cambio->nid;
2063  }
2064  $descriptor->log = t('Se agregó un nuevo cambio en la situación actual al descriptor  @date', array('@date' => date('d-m-Y', time())));
2065  $descriptor->revision = 1;
2066  node_save($descriptor);
2067  if ($nuevo) {
2068    drupal_set_message(t('Se agregó el cambio en la situación actual @title', array('@title' => $cambio->body)));
2069  }
2070  else {
2071    drupal_set_message(t('Se modificó el cambio en la situación actual @title', array('@title' => $cambio->body)));
2072  }
2073  if ($_REQUEST['destination']) {
2074    $form_state['redirect'] = url('planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios',
2075      array(
2076        'query' => array(
2077          'destination' => $_REQUEST['destination'],
2078         ),
2079         'absolute' => TRUE,               
2080      )
2081    );
2082    unset($_REQUEST['destination']);
2083  }
2084  else {
2085    // add redirect
2086    $form_state['redirect'] = 'planificacion/' . $form['#ente_planificador']->nid . '/explicacion/' . $form['#tipo_plan']['plan'] . '/' . $descriptor->nid . '/cambios';
2087  }
2088}
2089
2090/*
2091 * Implementation of mis_entes_planificadores_planificacion_explicacion()
2092 */
2093function mis_entes_planificadores_planificacion_explicacion() {
2094  global $user;
2095  $output = '';
2096  $ente = usuario_tiene_ente($user->uid);
2097  if ($ente->nid) {
2098    drupal_goto('planificacion/' . $ente->nid . '/explicacion');
2099  }
2100  drupal_goto('mi_ente_planificador/planificacion');
2101  return $output;
2102}
2103
2104/*
2105 * Implementation of situacion_actual_preliminar_status_planificacion_explicacion()
2106 */
2107function situacion_actual_preliminar_status_planificacion_explicacion($ente_planificador, $tipo = 2) {
2108  $estado_preliminar = array();
2109  $planns = _situacion_actual_preliminar_get_planns();
2110  foreach ($planns as $id => $plann) {
2111    if (isset($plann['ente_type'][$tipo]) && $plann['ente_type'][$tipo]) {
2112      $descriptores = _get_situacion_actual_listar_all_descriptores($ente_planificador, $plann['plan'], variable_get('situacional_actual_preliminar_anho_creacion', 0));
2113      $estado_preliminar['situacion_actual_' . $plann['plan']] = array(
2114        'value' => count($descriptores) ? 1 : 0,
2115        'title' => $plann['title_long'],
2116        'link' => 'planificacion/' . $ente_planificador . '/explicacion/' . $plann['short'],
2117        'mylink' => 'mi_ente_planificador/planificacion/explicacion/' . $plann['short'],
2118        'weight' => 1,
2119      );
2120    }
2121  }
2122  return $estado_preliminar;
2123}
2124
2125/*
2126 * Implementation of hook_access()
2127 */
2128function situacion_actual_preliminar_access($op, $node, $account) {
2129  if ($op == 'view') {
2130    return user_access('ver planificador');
2131  }
2132  if ($op == 'create' ) {
2133    return (user_access('admin planificador'));
2134  }
2135  if ($op == 'update') {
2136    return user_access('admin planificador');
2137  }
2138  if ($op == 'delete') {
2139    return (user_access('admin planificador'));
2140  }
2141}
2142
2143/*
2144 * Implementation of _get_situacion_actual_listar_all_descriptores()
2145 * Get ente's descriptores
2146 * Inputs:
2147   - $ente_planificador (integer): ente planificador nid
2148   - $tipo (integer): plann type
2149   - $year (integer): descriptor year creation, if no available 'situacional_actual_preliminar_anho_creacion' variable will be used
2150 * Outputs:
2151   - Descriptores (array nid descriptor):
2152     + body: Description descriptor
2153     + title: Acronimo
2154     + nid: Descriptor nid node reference
2155     + year: descriptor year creation
2156     + clasificacion: descriptor type
2157       / tid: taxonomy term
2158     + causas: causas list (array nid causa-descriptor):
2159       / body: Description causa
2160       / title: Acronimo causa
2161       / nid: Causa nid node reference
2162       / descriptor: Descriptor nid node reference
2163     + solucion: solucion list (array nid solucion-descriptor):
2164       / body: Description solucion
2165       / title: Acronimo solucion
2166       / nid: Solucion nid node reference
2167       / descriptor: Descriptor nid node reference
2168 */
2169function _get_situacion_actual_listar_all_descriptores($ente_planificador, $tipo_plan = array(), $year = 0) {
2170  //se obtienen los descriptores
2171  $descriptores = array();
2172  $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 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";
2173  $inputs = array();
2174  $inputs[] = $ente_planificador;
2175  $year_display = $year? $year: variable_get('situacional_actual_preliminar_anho_creacion', 0);
2176  $inputs[] = $year_display;
2177  if ($tipo_plan['short']) {
2178    $sql .= ' AND c.field_descriptores_' . $tipo_plan['short'] . '_value = %d';
2179    $inputs[] = 1;
2180  }
2181  $sql .=' ORDER BY c.nid';
2182  $result = db_query($sql, $inputs);
2183  $inpunts = array();
2184  $inpunts_values = array();
2185  $solucion = array();
2186  while($descriptor = db_fetch_object($result)) {
2187    $descriptores[$descriptor->nid] = array(
2188      'body' => $descriptor->body,
2189      'title' => $descriptor->title,
2190      'nid' => $descriptor->nid,
2191      'year' => $year_display,
2192      'clasificacion' => array(),
2193      'causas' => array(),
2194      'cambios' => array(),
2195    );
2196    $inpunts[] = '%d';
2197    $inpunts_values[] = $descriptor->nid;
2198  }
2199  if (count($inpunts)) {
2200    $implode = implode(',',$inpunts);
2201    //Se obtienen la clasificacion de los descriptores
2202    $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 . ')';
2203    $result = db_query($sql, $inpunts_values);
2204    while($clasificacion = db_fetch_object($result)) {
2205      $descriptores[$clasificacion->nid]['clasificacion'][$clasificacion->tid] = $clasificacion->tid;
2206    }
2207    //se obtienen las causas
2208    //field_descriptores_causa
2209    $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 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";
2210    $result = db_query($sql, $inpunts_values);
2211    while($causa = db_fetch_object($result)) {
2212      $descriptores[$causa->descriptor]['causas'][$causa->nid] = array(
2213        'body' => $causa->body,
2214        'nid' => $causa->nid,
2215        'title' => $causa->title,
2216        'descriptor' => $causa->descriptor,
2217      );
2218    }
2219    //se obtienen los cambios
2220    //field_descriptor_cambio_nid
2221    $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 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";
2222    $result = db_query($sql, $inpunts_values);
2223    while($meta = db_fetch_object($result)) {
2224      $descriptores[$meta->descriptor]['cambios'][$meta->nid] = array(
2225        'body' => $meta->body,
2226        'nid' => $meta->nid,
2227        'title' => $meta->title,
2228        'descriptor' => $meta->descriptor,
2229      );
2230    }
2231  }
2232  return $descriptores;
2233}
2234
2235/*
2236 * Implementation of _display_situacion_actual_listar_all_descriptores()
2237 */
2238function _display_situacion_actual_listar_all_descriptores($ente_planificador = 0, $tipo_plan = array(), $acceso = FALSE, $year = 0) {
2239  $descriptores = _get_situacion_actual_listar_all_descriptores($ente_planificador, $tipo_plan, $year);
2240  $output = '';
2241  $headers_table = array();
2242  $headers_table[] = array('data' => t('Descriptores'));
2243  $headers_table[] = array('data' => t('Categorización'));
2244  $headers_table[] = array('data' => t('Causas'));
2245  $headers_table[] = array('data' => t('Cambios de la situación actual'));
2246  $year = $year? $year : variable_get('situacional_actual_preliminar_anho_creacion', 0);
2247  if ($acceso) {
2248    $headers_table[] = array('data' => t('Acciones'));
2249  }
2250  if (count($descriptores)) {
2251    $rows = array();
2252    foreach($descriptores as $descriptor) {
2253      $row = array();
2254      $row[] = array('data' => $descriptor['body']);
2255      $clasificiacion = array();
2256      foreach($descriptor['clasificacion'] as $id) {
2257        $term_load = taxonomy_get_term($id);
2258        if ($term_load) {
2259          $clasificiacion[] = $term_load->name;
2260        }
2261      }
2262      $row[] = array('data' => theme('item_list', $clasificiacion));
2263      $causas = array();
2264      foreach ($descriptor['causas'] as $causa) {
2265        $causas[] = $causa['body'];
2266      }
2267      $output = count($causas)? theme('item_list', $causas) : t('No se han agregado causas al descriptor');
2268      $row[] = array('data' => $output);
2269      $solucion = array();
2270      foreach ($descriptor['cambios'] as $cambio) {
2271        $solucion[] = $cambio['body'];
2272      }
2273      $output = count($solucion)? theme('item_list', $solucion) : t('No se encontrarón cambios en la situación actual del descriptor');
2274
2275      $row[] = array('data' => $output);
2276      $redirect = $_GET["q"];
2277      if ($acceso && $descriptor['year'] == $year) {
2278        $acciones = array();
2279        $acciones[] = l(t('Editar Descriptor'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/descriptor', array('query' => array('destination' => $redirect)));
2280        $acciones[] = l(t('Consultar Causas'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/causas/ver', array('query' => array('destination' => $redirect)));
2281        $acciones[] = l(t('Agregar Causas'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/causas', array('query' => array('destination' => $redirect)));
2282        $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)));
2283        $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)));
2284        $acciones[] = l(t('Eliminar Descriptor'), 'planificacion/' . $ente_planificador . '/explicacion/' . $tipo_plan['plan'] . '/' . $descriptor['nid'] . '/eliminar', array('query' => array('destination' => $redirect)));
2285      }
2286      if (count($acciones)) {
2287        $row[] = array('data' => theme('item_list', $acciones));
2288      }
2289      $rows[] = $row;
2290    }
2291
2292  }
2293  else {
2294    $row = array();
2295    $row[] = array('data' => t('No se encontrarón descriptores para este ente'), 'colspan' => count($headers_table));
2296    $rows[] = $row;
2297  }
2298  return theme('table', $headers_table, $rows);
2299}
2300
2301/*
2302 * Implementation of _get_situacion_explicacion_acceso()
2303 * Obtiene el acceso de modificar descriptores
2304 */
2305function _get_situacion_explicacion_acceso_hijos($ente_planificador, $tipo_plan = 'interpretacion', $descriptor = 0) {
2306  global $user;
2307  $ente_obj = (object) $ente_planificador['level'];
2308  $ente_obj->tipo = $ente_obj->level;
2309  $ente_obj->type = 'ente_planificador';
2310  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_obj);
2311  $current_time = time();
2312  $ente = usuario_tiene_ente($user->uid);
2313  $mi_ente = user_access('admin all planificador') || ($ente && $ente->nid && $ente->nid == $ente_planificador['nid']);
2314  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))));
2315}
2316
2317/*
2318 * Implementation of _get_situacion_explicacion_acceso()
2319 * Obtiene el acceso de modificar descriptores
2320 */
2321function _get_situacion_explicacion_importar_acceso($ente_planificador, $tipo_plan = array()) {
2322  return $tipo_plan['plan'] == 'situacion_actual' && $tipo_plan['ente_type'][$ente_planificador->tipo] && _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan, 0);
2323}
2324
2325
2326
2327/*
2328 * Implementation of _get_situacion_explicacion_acceso()
2329 * Obtiene el acceso de modificar descriptores
2330 */
2331function _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan = array(), $descriptor = 0) {
2332  global $user;
2333  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan['plan'], $ente_planificador);
2334  $current_time = time();
2335  $ente = usuario_tiene_ente($user->uid);
2336  $campo = 'field_descriptores_' . $tipo_plan['short'];
2337  $mi_ente = user_access('admin all planificador') || ($ente && $ente->nid && $ente->nid == $ente_planificador->nid);
2338  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))));
2339}
2340
2341/*
2342 * Implementation of _get_situacion_actual_listar_descriptores_all()
2343 * Obtiene todos los descriptores de un ente planificador
2344 */
2345function _get_situacion_actual_listar_descriptores_all($ente_planificador, $tipo_plan = array(), $micro = 0, $year = 0) {
2346  global $user;
2347  $title = t($tipo_plan['title_long']);
2348  $contenido_ente = '';
2349  $redirect = $_GET["q"];
2350  if (isset($tipo_plan['ente_type'][$ente_planificador->tipo]) && $tipo_plan['ente_type'][$ente_planificador->tipo]) {
2351    $acceso = _get_situacion_explicacion_acceso($ente_planificador, $tipo_plan);
2352    $title = t($tipo_plan['title_ente'], array('@ente' => $ente_planificador->title));
2353    $contenido_ente = _display_situacion_actual_listar_all_descriptores($ente_planificador->nid, $tipo_plan, $acceso, $year);
2354
2355    if ($acceso) {
2356      $links[] = l(t('Agregar Descriptor'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/agregar/descriptor', array('query' => array('destination' => $redirect)));
2357      if ($tipo_plan['plan'] == 'situacion_actual') {
2358        $planns = _situacion_actual_preliminar_get_planns();
2359        $plan = $planns['version'];
2360        $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)));
2361      }
2362      if ($tipo_plan['plan'] != 'situacion_actual' && (count($ente_planificador->ente_planificador_hierarchical['children']) || user_access('admin planificador'))) {
2363        $links[] = l(t('Importar Causas usando Web semántica'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/causas', array('query' => array('destination' => $redirect)));
2364        $links[] = l(t('Importar Causas'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/causas_texto', array('query' => array('destination' => $redirect)));
2365
2366        $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)));
2367        $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)));
2368        $links[] = l(t('Importar Descriptor usando Web semántica'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/descriptores', array('query' => array('destination' => $redirect)));
2369        $links[] = l(t('Importar Descriptor'), 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/importar/descriptores_texto', array('query' => array('destination' => $redirect)));
2370      }
2371    }
2372    $contenido_ente .= '<div class="planificacion-explicacion">' . $contenido . theme('item_list', $links) . '</div>';
2373  }
2374  //se muestran las herencias de entes
2375  $links = array();
2376  if (isset($ente_planificador->ente_planificador_hierarchical[$tipo_plan['hierarchical']])) {
2377    $tipo_allow = $ente_planificador->tipo + $tipo_plan['hierarchical_ente'];
2378    $all_children = $ente_planificador->tipo < $tipo_allow;
2379    $entes = array();
2380    if ($tipo_allow > 0 && $tipo_allow <= variable_get('ente_planificador_hierarchical_count', 2)) {
2381      $entes = array();
2382      $levels = array();
2383      $hierarchical = $ente_planificador->ente_planificador_hierarchical[$tipo_plan['hierarchical']];
2384      foreach($hierarchical as $ente){
2385        $levels[$ente['level']] = $ente;
2386        if ($ente['level'] == $tipo_allow || ($all_children && $ente['level'] > $tipo_allow)) {
2387          $entes[$ente['nid']] = $ente['title'];
2388        }
2389      }
2390    }
2391    //en caso de que $tipo_allow no se encuentrem se muestra el siguiente nivel si tiene el tipo
2392    if (!count($entes) && $tipo_plan['hierarchical'] == 'fathers') {
2393      $tipo_allow += $tipo_plan['hierarchical_ente'];
2394      $encontrado = FALSE;
2395      while(!$encontrado && $tipo_allow >= 0 && $tipo_allow <= variable_get('ente_planificador_hierarchical_count', 2)) {
2396        if (isset($levels[$tipo_allow]) && isset($tipo_plan['ente_type'][$tipo_allow])) {
2397          $entes[$ente['nid']] = $ente['title'];
2398          $encontrado = TRUE;
2399        }
2400        $tipo_allow += $tipo_plan['hierarchical_ente'];
2401      }
2402    }
2403    $links = array();
2404    foreach($entes as $nid => $ente) {
2405      $contenido .= '';
2406      $contenido_hijos = '';
2407      if ($nid == $micro) {
2408        $acceso_hijo = _get_situacion_explicacion_acceso_hijos($nid, $tipo_plan['plan']);
2409        $contenido_hijos .= _display_situacion_actual_listar_all_descriptores($nid, $tipo_plan, $acceso_hijo, $year);
2410        $agregar = '';
2411        if ($acceso_hijo) {
2412          $agregar = l(t('Agregar Descriptor'), 'planificacion/' . $nid . '/explicacion/' . $tipo_plan['plan'] . '/agregar/descriptor', array('query' => array('destination' => $redirect)));
2413        }
2414        $contenido_hijos .= '<div class="planificacion-explicacion">' . $contenido_version . $agregar . '</div>';
2415      }
2416      $enlace = l($ente, 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'] . '/' . $nid);
2417      $links[] = $enlace . $contenido_hijos;
2418    }
2419  }
2420  if (count($links)) {
2421    $contenido_hijos = $ente_planificador->tipo < $tipo_allow ? '<h3>' . t('Interpretación preliminar de la explicación situacional de mis entes adscriptos') . '</h3>' : '';
2422    $contenido_hijos .= theme('item_list', $links);
2423  }
2424  drupal_set_title($title);
2425  return $contenido_ente . $contenido_hijos;
2426}
2427
2428/*
2429 * Implementation of ente_planificador_view_situacion_explicacion()
2430 * Display Versión Preliminar page
2431 */
2432function ente_planificador_view_situacion_explicacion($ente_planificador, $tipo_plan = 'interpretacion', $children = 0, $year = 0) {
2433  global $user;
2434  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
2435  $current_time = time();
2436  $fecha = FALSE;
2437  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2438    $fecha = TRUE;
2439  }
2440  if (!$fecha) {
2441    muestra_mensaje($tipo_plan, $ente_planificador);
2442  }
2443  else {
2444    $ente = usuario_tiene_ente($user->uid);
2445    if (user_access('admin all planificador') || $ente->nid == $ente_planificador->nid) {
2446      muestra_mensaje($tipo_plan, $ente_planificador, 0);
2447    }
2448  }
2449  $planns = _situacion_actual_preliminar_get_planns();
2450  $plan = $planns[$tipo_plan];
2451  $year = $year? $year : variable_get('situacional_actual_preliminar_anho_creacion', 0);
2452  $output = _get_situacion_actual_listar_descriptores_all($ente_planificador, $plan, $children, $year);
2453  return $output;
2454}
2455
2456/*
2457 * Implementation of _situacion_actual_preliminar_node_estructura()
2458 * Clona un nodo de la situación actual preliminar
2459 */
2460function _situacion_actual_preliminar_node_estructura() {
2461  return array(
2462    'ente_planificador' => array(
2463      'node_type' => array(
2464        'descriptores' => array(
2465          'field_descriptores_planificador' => 'field_descriptores_planificador',
2466        ),
2467        'causas' => array(
2468          'field_ente_planifiador' => 'field_ente_planifiador',
2469        ),
2470        'cambios' => array(
2471          'field_cambios_ente' => 'field_cambios_ente',
2472        ),
2473      ),
2474      'value_type' => 'nid',
2475    ),
2476    'link_node' => array(
2477      'node_type' => array(
2478        'descriptores' => array(
2479          'causas' => 'field_descriptores_causa',
2480          'cambios' => 'field_descriptor_cambio',
2481        ),
2482        'causas' => array(
2483          'descriptores' => 'field_descriptores_causa',
2484        ),
2485        'cambios' => array(
2486          'descriptores' => 'field_cambios_descriptor',
2487        ),
2488      ),
2489      'value_type' => 'nid',
2490    ),
2491    'year' => array(
2492      'node_type' => array(
2493        'descriptores' => array(
2494          'field_descriptores_year' => 'field_descriptores_year',
2495        ),
2496        'causas' => array(
2497          'field_causas_year' => 'field_causas_year',
2498        ),
2499        'cambios' => array(
2500        ),
2501      ),
2502      'value_type' => 'value',
2503    ),
2504  );
2505}
2506
2507/*
2508 * Implementation of _situacion_actual_preliminar_clonar()
2509 * Clona un nodo de la situación actual preliminar
2510 */
2511function _situacion_actual_preliminar_clonar($nid = 0, $nodeenlace = array()) {
2512  global $user;
2513  module_load_include('inc', 'node', 'node.pages');
2514  $arreglo = _situacion_actual_preliminar_node_estructura();
2515  $node = !is_object($nid)? node_load($nid) : $nid;
2516  $enlaces = array();
2517  $enlace_existe = array();
2518  $new_nodeenlace = array();
2519  if ($node) {
2520    $node_load = clone $node;
2521    unset($node_load->nid);
2522    unset($node_load->vid);
2523    unset($node_load->created);
2524    unset($node_load->changed);
2525    unset($node_load->revision_uid);
2526    unset($node_load->path);
2527    unset($node_load->data);
2528    unset($node_load->current_revision_id);
2529    unset($node_load->is_current);
2530    unset($node_load->num_revisions);
2531    $node_load->uid = $user->uid;
2532    $node_load->is_new = 1;
2533    foreach($arreglo as $id => $tipo) {
2534      $valor = isset($nodeenlace[$id]) ? $nodeenlace[$id] : 0;
2535      $campos = isset($tipo['node_type'][$node->type])? $tipo['node_type'][$node->type] : array();
2536      foreach($campos as $campo) {
2537        $node_load->{$campo} = array();
2538        if (!$valor  && $id == 'link_node') {
2539          foreach($node->{$campo} as $link) {
2540            if ($link[$tipo['value_type']]) {
2541              $enlaces[] = array(
2542                'value' => $link[$tipo['value_type']],
2543                'campo' => $campo,
2544              );
2545            }
2546          }
2547        }
2548        elseif($valor) {
2549          $node_load->{$campo}[][$tipo['value_type']] = $valor;
2550          $new_nodeenlace[$id] = $valor;
2551          if ($id == 'link_node') {
2552            $enlace_exist[] = array(
2553              'value' => $valor,
2554              'campo' => $campo,
2555              'node_type' => $node->type,
2556            );
2557          }
2558        }
2559      }
2560    }
2561    node_save($node_load);
2562    //si existen enlaces que agregar
2563    if ($node_load && count($enlaces)) {
2564      $new_nodeenlace['link_node'] = $node_load->nid;
2565      foreach ($enlaces as $nid) {
2566        if ($node_load->{$nid['campo']}[0]['nid'] == 0) {
2567          $node_load->{$nid['campo']} = array();
2568        }
2569
2570        $enlace = _situacion_actual_preliminar_clonar($nid['value'], $new_nodeenlace);
2571        if ($enlace && $enlace->nid) {
2572          $node_load->{$nid['campo']}[]['nid'] = $enlace->nid;
2573        }
2574      }
2575      node_save($node_load);
2576    }
2577  }
2578  return $node_load;
2579}
2580
2581
2582/*
2583 * Implementation of hook_node_info()
2584 */
2585function situacion_actual_preliminar_node_info() {
2586  return array(
2587    //se agrega el nodo causas
2588    'causas' => array(
2589      'name' => t('Causas'),
2590      'description' => '',
2591      'has_body' => TRUE,
2592      'title_label' => 'Acrónimo de la causa',
2593      'has_title' => TRUE,
2594      'body_label' => 'Causa',
2595      'module' => 'situacion_actual_preliminar',
2596    ),
2597    //se agrega el nodo descriptores
2598    'descriptores' => array(
2599      'name' => t('Descriptores'),
2600      'description' => '',
2601      'has_body' => TRUE,
2602      'title_label' => 'Acrónimo del descriptor',
2603      'has_title' => TRUE,
2604      'body_label' => 'Descriptor',
2605      'module' => 'situacion_actual_preliminar',
2606    ),
2607    //se agrega el nodo cambios en la situacion actual
2608    'cambios' => array(
2609      'name' => t('Cambios en la Situación Actual'),
2610      'description' => '',
2611      'has_body' => TRUE,
2612      'title_label' => 'Acrónimo del cambio',
2613      'has_title' => TRUE,
2614      'body_label' => 'Descripción del cambio',
2615      'module' => 'situacion_actual_preliminar',
2616    ),
2617  );
2618}
2619
2620/*
2621 * Implementation of hook_form()
2622 */
2623function situacion_actual_preliminar_form(&$node, $form_state) {
2624  return node_content_form($node, $form_state);
2625}
2626
2627/**
2628 * Implements hook_theme().
2629 */
2630function situacion_actual_preliminar_theme() {
2631  if (module_exists('views_semantic')) {
2632  return array(
2633      'situacion_actual_views_semantic' => array(
2634        'arguments' => array(
2635          'reports' => array(),
2636          'wrid' => 0,
2637          'reports_format' => 'rep',
2638        ),
2639      ),
2640    );
2641  }
2642}
2643
2644/**
2645 * Implementation of hook_views_api().
2646 */
2647function situacion_actual_preliminar_views_api() {
2648  return array(
2649    'api' => '2',
2650    'path' => drupal_get_path('module', 'situacion_actual_preliminar') . '/views',
2651  );
2652}
2653
2654/**
2655 * Implementation of hook_views_semantic_links_op_alter()
2656 */
2657function situacion_actual_preliminar_views_semantic_links_op_alter(&$links, $link) {
2658/*
2659  $links['views-semantic-op-' . $link['key']]['exportar'] = array(
2660    'name' => t('Exportar'),
2661    'link' => '#',
2662    'description' => t('Exportar contenido'),
2663    'class' => 'views-semantic-op-exportar',
2664    'target' => '_self',
2665  );
2666*/
2667  $path = drupal_get_path('module', 'situacion_actual_preliminar');
2668  drupal_add_js($path . '/js/situacion_actual_preliminar.js', 'module', 'footer');
2669}
2670
2671/**
2672 * Save values to web semantic
2673 */
2674function planificacion_cambios_js() {
2675  global $user;
2676  $ente = usuario_tiene_ente($user->uid);
2677  $values = json_decode(file_get_contents('php://input'));
2678
2679  if (!$ente->nid || (!$values || !is_object($values))) {
2680    drupal_not_found();
2681  }
2682  else {
2683    //se estrae los nodos a clonar
2684    $nids = property_exists($values, 'element_nid') ? $values->element_nid : array();
2685    $id_reference = property_exists($values, 'descriptor_nid')? $values->descriptor_nid : 0;
2686    $arreglo = array();
2687    $arreglo['ente_planificador'] = $ente->nid;
2688    $arreglo['year'] = variable_get('situacional_actual_preliminar_anho_creacion', 0);
2689    if ($id_reference) {
2690      $arreglo['link_node'] = $id_reference;
2691    }
2692    $nodos = array();
2693    foreach ($nids as $nid) {
2694      $nodos[] = _situacion_actual_preliminar_clonar($nid, $arreglo);
2695    }
2696
2697    if ($id_reference) {
2698      $descriptor = node_load($id_reference);
2699      $arreglo = _situacion_actual_preliminar_node_estructura();
2700      foreach ($nodos as $node) {
2701        $nuevo_campo = $arreglo['link_node']['node_type'][$descriptor->type][$node->type];
2702        if (empty($descriptor->{$nuevo_campo}[0]['nid']) || $descriptor->{$nuevo_campo}[0]['nid'] == 0) {
2703          $descriptor->{$nuevo_campo} = array();
2704        }
2705        $descriptor->{$nuevo_campo}[]['nid'] = $node->nid;
2706      }
2707      node_save($descriptor);
2708    }
2709    print drupal_to_js(array('data' => $nodos, 'status' => true));
2710  }
2711  exit();
2712}
2713
2714/**
2715 * Genera el ahah para el display de cada vista
2716 */
2717function situacional_actual_preliminar_views_js($proceso, $tipo) {
2718  $form_state = array('submitted' => FALSE);
2719  $form_build_id = $_POST['form_build_id'];
2720  // Add the new element to the stored form. Without adding the element to the
2721  // form, Drupal is not aware of this new elements existence and will not
2722  // process it. We retreive the cached form, add the element, and resave.
2723  $form = form_get_cache($form_build_id, $form_state);
2724
2725  $view_name = $_POST['situacion_actual_preliminar_' . $proceso . '_' . $tipo];
2726  $options = array('_none' => 'Ninguna');
2727  $view =  views_get_view($view_name);
2728  foreach ($view->display as $key => $display) {
2729    $options[$key] = $display->display_title;
2730  }
2731
2732  $form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso . '_' . $tipo] = array(
2733    '#title' => t("Seleccione el display de la vista"),
2734    '#type' => 'select',
2735    '#default_value' => variable_get('situacion_actual_preliminar_display_views_' . $proceso . '_' . $tipo, 0),
2736    '#options' => $options,
2737    '#requerid' => TRUE,
2738  );
2739
2740
2741  form_set_cache($form_build_id, $form, $form_state);
2742  $form += array(
2743    '#post' => $_POST,
2744    '#programmed' => FALSE,
2745  );
2746  // Rebuild the form.
2747  $form = form_builder($_POST['form_id'], $form, $form_state);
2748
2749  $new_form = array();
2750
2751  unset($form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso  . '_' . $tipo]['#prefix']);
2752  unset($form['situacional_actual_preliminar_views']['situacion_actual_preliminar_display_views_' . $proceso  . '_' . $tipo]['#suffix']);
2753  $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];
2754
2755  $output = drupal_render($new_form);
2756  print drupal_to_js(array('data' => $output, 'status' => true));
2757  exit();
2758}
2759
2760/*
2761 * Implementation of _ente_planificador_cambios_situacion_actual_ver()
2762 * Consultar los cambios de un descriptor
2763 */
2764function situacion_actual_premilimar_importar_datos($ente_planificador,  $tipo_plan = array(), $tipo = 'causas') {
2765  global $user;
2766  $tipos = array(
2767    'causas' => t('Causas'),
2768    'descriptores' => t('Descriptores'),
2769    'cambios' => t('Cambios de la Situación Actual'),
2770    'causas_texto' => t('Causas (Texto)'),
2771    'descriptores_texto' => t('Descriptores (Texto)'),
2772    'cambios_texto' => t('Cambios de la Situación Actual (Texto)'),
2773  );
2774  $view_id = variable_get('situacion_actual_preliminar_' . $tipo_plan['plan'] . '_' . $tipo, 0);
2775  $view = views_get_view($view_id);
2776  $display_id = variable_get('situacion_actual_preliminar_display_views_' . $tipo_plan['plan'] . '_' . $tipo, 'default');
2777  $view->set_display($display_id);
2778
2779  $title = $tipos[$tipo];
2780  drupal_set_title(t('Importar @name ("@tipo")', array('@name' => $tipo_plan['title'], '@tipo' => $title)));
2781
2782  $view->override_path = $_GET['q'];
2783  $view->pre_execute();
2784  $view->execute();
2785  $output = $view->render();
2786
2787  $url = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'planificacion/' . $ente_planificador->nid . '/explicacion/' . $tipo_plan['plan'];
2788  $links = array();
2789  $links[] = l(t('Regresar'), $url);
2790  return $output . theme('item_list', $links);
2791}
2792
2793/*
2794 * Implementation of _get_situacion_explicacion_acceso()
2795 * Obtiene el acceso de modificar descriptores
2796 */
2797function _get_situacion_explicacion_acceso_hijos_importar($ente_planificador, $tipo_plan = 'interpretacion', $tipo = 'causas') {
2798  return _get_situacion_explicacion_acceso_hijos((array) $ente_planificador, $tipo_plan) || count($ente_planificador->ente_planificador_hierarchical['children']) || user_access('admin planificador');
2799}
2800
2801/*
2802 * Implementation of ente_planificador_descriptores_importar_form()
2803 * Importar descriptores
2804 */
2805function situacional_actual_preliminar_importar_descriptor_form($form_state, $ente_planificador = 0, $nid = 0, $tipo = '', $descriptores = array()) {
2806  global $user;
2807  $form = array();
2808  $planns = _situacion_actual_preliminar_get_planns();
2809  $plan = $planns['version'];
2810  $year = variable_get('situacional_actual_preliminar_anho_creacion', 0);
2811  $form = array();
2812  $form['#import_nid'] = $nid;
2813  $form['#type_node'] = $tipo;
2814  $form['#year'] = $year;
2815  $form['#plan'] = $plan;
2816  $form['#ente_planificador'] = $ente_planificador;
2817  $form['#descriptores'] = $descriptores;
2818  $textos = array(
2819    'descriptores' => t('el Descriptor'),
2820    'causas' => t('la Causa'),
2821    'cambios' => t('el Cambio en la situación actual'),
2822
2823  );
2824  $form['#textos'] = $textos;
2825  if ($form['#ente_planificador']->nid) {
2826    if ($tipo == 'causas' || $tipo == 'cambios') {
2827      if (!count($descriptores)) {
2828        $descriptores = _get_situacion_actual_listar_all_descriptores($ente->nid, $plan, variable_get('situacional_actual_preliminar_anho_creacion', 0));
2829      }
2830      $options = array();
2831      foreach ($descriptores as $nid => $descriptor) {
2832        $options[$nid] = $descriptor['body'];
2833      }
2834      $form['descriptor'] = array(
2835        '#type' => 'select',
2836        '#title' => t('Descriptor'),
2837        '#description' => t('Seleccione el descriptor.'),
2838        '#default_value' => isset($context['target_sid']) ? $context['target_sid'] : '',
2839        '#options' => $options,
2840      );
2841    }
2842    $form['buttons']['situacion_preliminar'] = array(
2843      '#type' => 'button',
2844      '#value' => t('Importar @tipo', array('@tipo' => $form['#textos'][$form['#type_node']])),
2845      '#weight' => 20,
2846      '#prefix' => '<div id = "' . 'situacion-preliminar_' . $form['#import_nid'] . '">',
2847      '#suffix' => '</div>',
2848      '#ahah' => array(
2849        'path' => 'planificacion_importar_pdlp_js/' . $tipo .  '/' . $form['#import_nid'],
2850        'wrapper' => 'situacion-preliminar_' . $form['#import_nid'],
2851        'method' => 'replace',
2852        'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
2853      ),
2854    );
2855  }
2856  return $form;
2857}
2858
2859/*
2860 * Implementation of ente_planificador_descriptores_editar_form_submit()
2861 */
2862function situacional_actual_preliminar_importar_descriptor_form_submit($form, &$form_state) {
2863  $nidl = $form['#import_nid'];
2864  $arreglo = array();
2865  $arreglo['ente_planificador'] = $form['#ente_planificador']->nid;
2866  $arreglo['year'] = $form['#year'];
2867  $id_reference = ($form['#type_node'] == 'causas' || $form['#type_node'] == 'cambios')? $form_state['values']['descriptor'] : 0;
2868  if ($nidl) {
2869    if ($id_reference) {
2870      $arreglo['link_node'] = $id_reference;
2871    }
2872    $node_load = _situacion_actual_preliminar_clonar($nidl, $arreglo);
2873    if ($id_reference) {
2874      $descriptor = node_load($id_reference);
2875      $arreglo_l = _situacion_actual_preliminar_node_estructura();
2876      $nuevo_campo = $arreglo_l['link_node']['node_type'][$descriptor->type][$node_load->type];
2877      if (empty($descriptor->{$nuevo_campo}[0]['nid']) || $descriptor->{$nuevo_campo}[0]['nid'] == 0) {
2878        $descriptor->{$nuevo_campo} = array();
2879      }
2880      $descriptor->{$nuevo_campo}[]['nid'] = $node_load->nid;
2881      node_save($descriptor);
2882    }
2883  }
2884  drupal_set_message(t('Se importó @tipo', array('@tipo' => $form['#textos'][$form['#type_node']])));
2885}
2886
2887/*
2888 * Implementation of planificacion_importar_pdlp_js()
2889 * importa el nodo por tipo
2890 */
2891function planificacion_importar_pdlp_js($tipo = '', $nid = 0) {
2892  $form_state = array('submitted' => FALSE);
2893  $form_build_id = $_POST['form_build_id'];
2894  $form = form_get_cache($form_build_id, $form_state);
2895  $nidl = $form['#import_nid'];
2896  $arreglo = array();
2897  $arreglo['ente_planificador'] = $form['#ente_planificador']->nid;
2898  $arreglo['year'] = $form['#year'];
2899  $id_reference = ($form['#type_node'] == 'causas' || $form['#type_node'] == 'cambios') && intval($_POST['descriptor']) > 0? intval($_POST['descriptor']) : 0;
2900  if ($nidl) {
2901    if ($id_reference) {
2902      $arreglo['link_node'] = $id_reference;
2903    }
2904    $node_load = _situacion_actual_preliminar_clonar($nidl, $arreglo);
2905    if ($id_reference) {
2906      $descriptor = node_load($id_reference);
2907      $arreglo_l = _situacion_actual_preliminar_node_estructura();
2908      $nuevo_campo = $arreglo_l['link_node']['node_type'][$descriptor->type][$node_load->type];
2909      if (empty($descriptor->{$nuevo_campo}[0]['nid']) || $descriptor->{$nuevo_campo}[0]['nid'] == 0) {
2910        $descriptor->{$nuevo_campo} = array();
2911      }
2912      $descriptor->{$nuevo_campo}[]['nid'] = $node_load->nid;
2913      node_save($descriptor);
2914    }
2915  }
2916  unset($form['buttons']['submit']);
2917  form_set_cache($form_build_id, $form, $form_state);
2918  $form += array(
2919    '#post' => $_POST,
2920    '#programmed' => FALSE,
2921  );
2922  // Rebuild the form.
2923  $form = form_builder($_POST['form_id'], $form, $form_state);
2924  $texto = t('Se importó @tipo', array('@tipo' => $form['#textos'][$form['#type_node']]));
2925  print drupal_to_js(array('data' => $texto, 'status' => true));
2926  exit();
2927}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.