source: sipes/0.3-modules/ente_planificador/ente_planificador.module @ 458f6aa

stableversion-3.0
Last change on this file since 458f6aa was 458f6aa, checked in by lhernandez <lhernandez@…>, 8 años ago

se agrego la correción respecto al paginador de la lista de usuarios

  • Propiedad mode establecida a 100755
File size: 115.8 KB
Línea 
1<?php
2  /**
3  * Modulo para la gestión de los entes planificadores
4  * Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana
5  * @file ente_planificador.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 - Msc. Juan Vizcarrondo
24  * Modificado por: Msc. Juan Vizcarrondo @date 2011-04-27.
25  * Modificado por: Msc. Juan Vizcarrondo @date 2011-06-10.
26  * Modificado por: Msc. Juan Vizcarrondo @date 2011-12-05.
27  * Modificado por: Msc. Juan Vizcarrondo @date 2012-02-16.
28  * Modificado por: Ing. Luis G. Peña C @date 2012-03-15
29  * Modificado por: Msc. Juan Vizcarrondo @date 2012-03-26.
30  * Modificado por: Msc. Juan Vizcarrondo @date 2012-04-17.
31  * @date 2010-04-27 // (a&#241;o-mes-dia)
32  * @date 2015-02-06 // (a&#241;o-mes-dia)
33  * @version 0.2 // (0.1)
34  *
35  */
36
37/*
38 * entes_planificadores_obtiene_tipos
39 * Lista los tipos de entes
40 */
41function entes_planificadores_obtiene_tipos($tipo = 0) {
42  $tipos = array(
43    2 => t('Actor operativo'),
44    1 => t('Actor estratégico-táctico'),
45  );
46  drupal_alter('obtiene_tipos', $tipos);
47
48  if ($tipo && is_numeric($tipo) && $tipos[$tipo]) {
49    return $tipos[$tipo];
50  }
51  elseif($tipo) {
52    return FALSE;
53  }
54 
55  return $tipos;
56}
57
58/*
59 * ente_planificador_ente_macro()
60 * Obtiene el ente macro de un ente micro, actualmente esta funcion regresa el unico ente macro permitido en el sistema
61 * pero podria modificarse en un futuro con otro modulo invocando el hook_obtiene_macro_alter
62 */
63function ente_planificador_ente_macro($ente_planificador = 0) {
64  $actor_macro = FALSE;
65  $result = db_query("SELECT d.nid FROM {ente_planificador} AS d INNER JOIN {node} AS n ON n.nid = d.nid WHERE tipo = 1");
66  $macro = db_fetch_object($result);
67  if ($macro->nid){
68    $actor_macr0 = $macro->nid;
69  }
70  drupal_alter('obtiene_macro', $actor_macr0, $ente_planificador);
71  return $actor_macr0;
72}
73
74/*
75 * Implementation of hook_menu()
76 */
77function ente_planificador_menu() {
78  $items = array();
79  $items['administrar/entes_planificadores'] = array(
80    'title' => 'Consultar lista de actores planificadores',
81    'page callback' => 'entes_planificadores',
82    'access arguments' => array('ver planificador'),
83    'type' => MENU_NORMAL_ITEM,
84    );
85  $items['entes_planificadores/registrar'] = array(
86    'title' => 'Registrar Actores Planificadores',
87    'page callback' => 'entes_planificadores_agregar',
88    'page arguments' => array(1),
89    'access arguments' => array('admin planificador'),
90    'type' => MENU_NORMAL_ITEM,
91  );
92  $items['ente_planificador_js_util/%'] = array(
93    'title' => 'JS utilities',
94    'page callback' => 'ente_planificador_js_util',
95    'page arguments' => array(1),
96    'access arguments' => array('access content'),
97    'type' => MENU_CALLBACK,
98  );
99  $items['administrar/entes_planificadores/registrar'] = array(
100    'title' => 'Registrar Actores Planificadores',
101    'page callback' => 'entes_planificadores_agregar',
102    'page arguments' => array(1),
103    'access arguments' => array('admin planificador'),
104    'type' => MENU_NORMAL_ITEM,
105  );
106  $items['administrar/entes_planificadores/lista'] = array(
107    'title' => t('List'),
108    'type' => MENU_DEFAULT_LOCAL_TASK,
109    'weight' => -10
110  );
111  $items['node/%/datos_basicos'] = array(
112    'title' => 'Editar datos del actor planificador',
113    'page callback' => 'ente_planificador_datos_basicos',
114    'page arguments' => array(1),
115    'access callback' => 'nodo_es_ente_planificador',
116    'access arguments' => array(1),
117    'type' => MENU_LOCAL_TASK,
118  );
119  $items['node/%/usuarios'] = array(
120    'title' => 'Usuarios Asignados',
121    'page callback' => 'entes_planificadores_usuarios',
122    'page arguments' => array(1),
123    'access callback' => 'nodo_es_ente_planificador',
124    'access arguments' => array(1),
125    'type' => MENU_LOCAL_TASK,
126  );
127  $items['node/%/planificacion'] = array(
128    'title' => 'Planificación',
129    'page callback' => 'entes_planificadores_planificacion',
130    'page arguments' => array(1),
131    'access callback' => 'nodo_es_ente_planificador',
132    'access arguments' => array(1),
133    'type' => MENU_LOCAL_TASK,
134  );
135  $items['administrar_usuarios'] = array(
136    'title' => 'Consultar Listado de Usuarios',
137    'page callback' => 'entes_planificadores_listar_usuarios',
138    'access arguments' => array('admin planificador'),
139    'type' => MENU_NORMAL_ITEM,
140  );
141  $items['fechas_planificacion'] = array(
142    'title' => 'Consultar listado de fechas de las procesos de planificación',
143    'page callback' => 'ente_planificador_fecha_planificacion',
144    'access arguments' => array('ver planificador'),
145    'type' => MENU_NORMAL_ITEM,
146  );
147  $items['fechas_planificacion/envia_email'] = array(
148    'title' => 'Enviar Correo Electronico de la fecha de Planificación',
149    'page callback' => 'ente_planificador_fecha_planificacion_correo',
150    'access callback' => 'usuario_tiene_permisos',
151    'type' => MENU_NORMAL_ITEM,
152  );
153  $items['fechas_planificacion/edit'] = array(
154    'title' => 'Modificar las fechas para los procesos de planificación.',
155    'page callback' => 'ente_planificador_fecha_planificacion_edit',
156    'access arguments' => array('admin planificador'),
157    'type' => MENU_CALLBACK,
158  );
159  $items['fechas_planificacion/todas_edit'] = array(
160    'title' => 'Modificar todas las fechas para los procesos de planificación.',
161    'page callback' => 'drupal_get_form',
162    'page arguments' => array('ente_planificador_fecha_planificacion_edit_todas'),
163    'access arguments' => array('admin planificador'),
164    'type' => MENU_NORMAL_ITEM,
165  );
166  $items['fechas_planificacion/notificacion'] = array(
167    'title' => 'Fecha de notificación.',
168    'page callback' => 'drupal_get_form',
169    'page arguments' => array('ente_planificador_fecha_planificacion_edit_notificacion'),
170    'access arguments' => array('admin planificador'),
171    'type' => MENU_NORMAL_ITEM,
172  );
173  $items['admin/settings/ente_planificador'] = array(
174    'title' => t('Configuración Ente Planificador'),
175    'description' => t('Configuración del Ente Planificador.'),
176    'page callback' => 'drupal_get_form',
177    'page arguments' => array('ente_planificador_admin_settings'),
178    'access arguments' => array('admin planificador'),
179    'type' => MENU_NORMAL_ITEM,
180  );
181  $items['admin/settings/ente_planificador/view'] = array(
182    'title' => t('Configuración Ente Planificador'),
183    'type' => MENU_DEFAULT_LOCAL_TASK,
184    'weight' => -10
185  );
186  $items['admin/settings/ente_planificador/actividades'] = array(
187    'title' => t('Actividades'),
188    'page callback' => 'ente_planificador_view_actividades',
189    'access arguments' => array('admin planificador'),
190    'weight' => -8,
191    'type' => MENU_LOCAL_TASK,
192  );
193  $items['admin/settings/ente_planificador/agregar_actividades'] = array(
194    'title' => t('Agregar Actividad'),
195    'page callback' => 'drupal_get_form',
196    'page arguments' => array('ente_planificador_agregar_actividades_form'),
197    'access arguments' => array('admin planificador'),
198    'weight' => -8,
199    'type' => MENU_LOCAL_TASK,
200  );
201  $items['admin/settings/ente_planificador/actividades/%actividad_menu/edit'] = array(
202    'title' => t('Modificar'),
203    'page callback' => 'drupal_get_form',
204    'page arguments' => array('ente_planificador_edit_actividad_form',4),
205    'access arguments' => array('admin planificador'),
206    'type' => MENU_CALLBACK,
207  );
208  $items['admin/settings/ente_planificador/actividades/%actividad_menu/remove'] = array(
209    'title' => t('Modificar'),
210    'page callback' => 'drupal_get_form',
211    'page arguments' => array('ente_planificador_eliminar_actividad_form',4),
212    'access arguments' => array('admin planificador'),
213    'type' => MENU_CALLBACK,
214  );
215  $items['planificacion/%ente_planificador_menu'] = array(
216    'title' => t('Planificación'),
217    'page callback' => 'ente_planificador_view_planning',
218    'page arguments' => array(1),
219    'access arguments' => array('ver planificador'),
220    'weight' => -10,
221    'type' => MENU_CALLBACK,
222  );
223  $items['planificacion/%ente_planificador_menu/view'] = array(
224    'title' => 'View',
225    'type' => MENU_DEFAULT_LOCAL_TASK,
226    'weight' => -10
227  );
228  $items['mi_ente_planificador'] = array(
229    'title' => 'Mi ente planificador',
230    'page callback' => 'mis_entes_planificadores',
231    'access callback' => 'ente_planificador_usuario_ve_ente',
232    'type' => MENU_NORMAL_ITEM,
233  );
234  $items['mi_ente_planificador/view'] = array(
235    'title' => 'View',
236    'type' => MENU_DEFAULT_LOCAL_TASK,
237    'weight' => -10
238  );
239  $items['mi_ente_planificador/datos_basicos'] = array(
240    'title' => 'Editar datos del actor planificador',
241    'page callback' => 'mis_entes_planificadores_datos_basicos',
242    'access callback' => 'ente_planificador_usuario_ve_ente',
243    'type' => MENU_LOCAL_TASK,
244  );
245  $items['mi_ente_planificador/usuarios'] = array(
246    'title' => 'Usuarios Asignados',
247    'page callback' => 'mis_entes_planificadores_usuarios',
248    'access callback' => 'ente_planificador_usuario_ve_ente',
249    'type' => MENU_LOCAL_TASK,
250  );
251  $items['mi_ente_planificador/planificacion'] = array(
252    'title' => 'Mi planificación',
253    'page callback' => 'mis_entes_planificadores_planificacion',
254    'access callback' => 'ente_planificador_usuario_ve_ente',
255    'type' => MENU_LOCAL_TASK,
256  );
257  $items['mi_ente_planificador/planificacion/view'] = array(
258    'title' => 'View',
259    'type' => MENU_DEFAULT_LOCAL_TASK,
260    'weight' => -10
261  );
262  return $items;
263}
264
265/*
266 * Implementation of ente_planificador_usuario_ve_ente()
267 */
268function ente_planificador_usuario_ve_ente() {
269  global $user;
270  if (user_access('edit own planificador')) {
271    $ente = usuario_tiene_ente($user->uid);
272    if ($ente->nid) {
273      return TRUE;
274    }
275  }
276  return FALSE;
277}
278
279/*
280 * Implementation of mis_entes_planificadores_datos_basicos()
281 */
282function mis_entes_planificadores_datos_basicos() {
283  global $user;
284  $output = '';
285  $ente = usuario_tiene_ente($user->uid);
286  if ($ente->nid) {
287    $output .= ente_planificador_datos_basicos($ente->nid);
288  }
289  return $output;
290}
291
292/*
293 * Implementation of mis_entes_planificadores_usuarios()
294 */
295function mis_entes_planificadores_usuarios() {
296  global $user;
297  $output = '';
298  $ente = usuario_tiene_ente($user->uid);
299  if ($ente->nid) {
300    $output .= entes_planificadores_usuarios($ente->nid);
301  }
302  return $output;
303}
304
305/*
306 * Implementation of mis_entes_planificadores_planificacion()
307 */
308function mis_entes_planificadores_planificacion() {
309  global $user;
310  $output = '';
311  $ente = usuario_tiene_ente($user->uid);
312  if ($ente->nid) {
313    $ente = ente_planificador_leer($ente->nid);
314    $output .= ente_planificador_view_planning($ente);
315  }
316  return $output;
317}
318
319/**
320 * Implementation of actividad_menu_load().
321 * Menu loader callback. Load actividad.
322 */
323function actividad_menu_load($actividad) {
324  if ($actividad) {
325    $resul_act = db_query("SELECT * FROM {ente_actividad} where id_actividad = %d", $actividad);
326    $actividad = db_fetch_object($resul_act);
327    return $actividad;
328  }
329  return FALSE;
330}
331
332/*
333 * Implementation of ente_planificador_view_actividades()
334 */
335function ente_planificador_view_actividades() {
336  $header = array();
337  $header[] = array('data' => t('Name'));
338  $header[] = array('data' => t('Action'), 'colspan' => 2);
339  $actividades = ente_planificador_obtener_actividades();
340  $rows = array();
341  foreach($actividades as $id => $actividad) {
342    $row = array();
343    $row[] = array('data' => t($actividad), );
344    $row[] = array(
345      'data' => l(t('Update'), 'admin/settings/ente_planificador/actividades/' . $id . '/edit'),
346    );
347    $row[] = array(
348      'data' => l(t('Remove'),'admin/settings/ente_planificador/actividades/' . $id . '/remove'),
349    );
350    $rows[] = $row;
351  }
352  if (!count($rows)) {
353    $row = array();
354    $row[] = array(
355      'data' => t('No se encontrarón actividades'),
356      'colspan' => 3
357    );
358    $rows[] = $row;
359  }
360  return theme('table', $header, $rows);
361}
362
363/**
364 * Implementation of webforms_countries_menu_country_load().
365 * Menu loader callback. Load a country.
366 */
367function ente_planificador_menu_load($ente_planificador_menu) {
368  $ente = ente_planificador_leer($ente_planificador_menu);
369  if ($ente) {
370    return $ente;
371  }
372  return FALSE;
373}
374
375/*
376 * Implementation of ente_planificador_agregar_actividades_form()
377 */
378function ente_planificador_agregar_actividades_form(&$form_state) {
379  $form = array();
380  $form['nombre'] = array(
381    '#title' => t('Actividad'),
382    '#type' => 'textfield',
383    '#default_value' => $actividad_menu->nombre,
384    '#required' => TRUE,
385    '#maxlength' => 1024,
386  );
387  $form['submit'] = array(
388    '#type' => 'submit',
389    '#value' => t('Save Actividad'),
390    '#weight' => 40,
391  );
392  return $form;
393}
394
395/**
396 * Implementation of ente_planificador_agregar_actividades_form_submit().
397 * Save actividad values
398 */
399function ente_planificador_agregar_actividades_form_submit($form, &$form_state) {
400  db_query("INSERT INTO {ente_actividad} (nombre) VALUES ('%s')", check_plain($form_state['values']['nombre']));
401  drupal_set_message(t('Actividad %name_actividad agregada', array('%name_actividad' => $form_state['values']['nombre'])));
402  $form_state['redirect'] = 'admin/settings/ente_planificador/actividades';
403}
404
405/**
406 * Implementation of ente_planificador_edit_actividad_form().
407 * Edit a actividad data.
408 */
409function ente_planificador_edit_actividad_form(&$form_state, $actividad_menu) {
410  $form['id_actividad'] = array(
411    '#type' => 'hidden',
412    '#value' => $actividad_menu->id_actividad,
413  );
414  $form['nombre'] = array(
415    '#title' => t('Actividad'),
416    '#type' => 'textfield',
417    '#default_value' => $actividad_menu->nombre,
418    '#required' => TRUE,
419    '#maxlength' => 1024,
420  );
421  $form['submit'] = array(
422    '#type' => 'submit',
423    '#value' => t('Save Actividad'),
424    '#weight' => 40,
425  );
426  return $form;
427}
428
429/*
430 * Implementation of ente_planificador_edit_actividad_form_submit()
431 */
432function ente_planificador_edit_actividad_form_submit($form, &$form_state) {
433  db_query("UPDATE {ente_actividad} SET nombre = '%s' WHERE id_actividad = %d", check_plain($form_state['values']['nombre']), $form_state['values']['id_actividad']);
434  drupal_set_message(t('Actividad %name_actividad modificada', array('%name_actividad' => $form_state['values']['nombre'])));
435  $form_state['redirect'] = 'admin/settings/ente_planificador/actividades';
436}
437
438/*
439 * Implementation of ente_planificador_eliminar_actividad_form()
440 */
441function ente_planificador_eliminar_actividad_form(&$form_state, $actividad_menu) {
442  $form['id_actividad'] = array('#type' => 'value', '#value' => $actividad_menu->id_actividad);
443  $form['nombre'] = array('#type' => 'value', '#value' => $actividad_menu->nombre);
444  $message = t('Are you sure you want to delete actividad %name_actividad?', array('%name_actividad' => $actividad_menu->nombre));
445  $caption = '<p>'. t('This action cannot be undone.') .'</p>';
446  $return_path = 'admin/settings/ente_planificador/actividades';
447  return confirm_form($form, $message, $return_path, $caption, t('Delete'));
448}
449
450/*
451 * Implementation of ente_planificador_eliminar_actividad_form_submit()
452 */
453function ente_planificador_eliminar_actividad_form_submit($form, &$form_state) {
454  db_query("DELETE FROM {ente_actividad} WHERE id_actividad = %d", $form_state['values']['id_actividad']);
455  drupal_set_message(t('Actividad %name_actividad borrada'.$form_state['values']['id_actividad'], array('%name_actividad' => $form_state['values']['nombre'])));
456  $form_state['redirect'] = 'admin/settings/ente_planificador/actividades';
457}
458
459/*
460 * Implementation of ente_planificador_leer()
461 */
462function ente_planificador_leer($nid) {
463  if (isset($nid) && is_numeric($nid)) {
464    $ente = ente_planificador_leer_ente_planificadores($nid);
465    if ($ente->type == 'ente_planificador') {
466      return $ente;
467    }
468  }
469  return FALSE;
470}
471
472/*
473 * Implementation of ente_planificador_obtiene_resumen_planificacion()
474 */
475function ente_planificador_obtiene_resumen_planificacion($nid, $type = "all") {
476  $planificacion = array();
477  $estados = ente_planificador_status_planificacion($nid);
478  $total_suma = 0;
479  $total_ejecutado = 0; 
480  if (count($estados)) {
481    foreach($estados as $id_estado => $estado) {
482      $etapas = count($estado['value']);
483      if ($etapas) {
484        $suma = 0;
485        foreach($estado['value'] as $value) {
486          $total_suma++;
487          if ($value['value']) {
488            $suma++;           
489          }
490        }
491        $total_ejecutado += $suma;
492        $porc = ($suma * 100) / $etapas;
493        if ($type == "all") {
494          $planificacion['etapas'][] = l($estado['title'] . ' (' . round($porc, 2) . '%).', 'planificacion/' . $nid . '/' . $id_estado);
495        }
496        else {
497          $planificacion['etapas'][] = l($estado['title'] . ' (' . round($porc, 2) . '%).', 'mi_ente_planificador/planificacion/' . $id_estado);
498        }
499      }
500      $planificacion['total'] = ($total_suma > 0) ? ($total_ejecutado * 100) / $total_suma : 0;
501    }
502  }
503  return $planificacion;
504}
505
506/*
507 * Implementation of hook_planificador_block()
508 */
509function ente_planificador_block($op = 'list', $delta = 0, $edit = array()) {
510  if ($op == 'list') {
511    $blocks[0] = array(
512      'info' => t('Mi planificación'),
513      'cache' => BLOCK_CACHE_PER_USER,
514    );
515    $blocks[1] = array(
516      'info' => t('Planificación del Ente'),
517      'cache' => BLOCK_CACHE_PER_PAGE,
518    );
519    return $blocks;
520  }
521  else if ($op == 'view') {
522    switch ($delta) {
523      case 0:
524        global $user;
525        $ente = usuario_tiene_ente($user->uid);
526        if ($ente->nid) {
527          $planificacion = ente_planificador_obtiene_resumen_planificacion($ente->nid);
528          if (count($planificacion)) {
529            $output = '<p><b>' . l(t('Porcentaje de Avance'), 'mi_ente_planificador/planificacion') . ':</b> ' . round($planificacion['total'], 2) . '%</p>';
530            if (count($planificacion['etapas'])) {
531              $output .= '<ul>';
532              foreach($planificacion['etapas'] as $texto) {
533                $output .= '<li>' . $texto . '</li>';
534              }
535              $output .= '</ul>';
536            }
537            $block = array(
538              'subject' => t('Mi planificación'),
539              'content' => $output,
540            );
541          }
542        }
543        break;
544      case 1:
545        if((arg(0) == 'node' && is_numeric(arg(1))) || (arg(0) == 'planificacion' && is_numeric(arg(1)))) {
546          $ente_planificador = ente_planificador_leer_ente_planificadores(arg(1));
547          $planificacion = ente_planificador_obtiene_resumen_planificacion(arg(1));
548          if (count($planificacion)) {
549            $output = '<p><b>' . l(t('Porcentaje de Avance'), 'planificacion/' . $ente_planificador->nid) . ':</b> ' . round($planificacion['total'], 2) . '%</p>';
550            if (count($planificacion['etapas'])) {
551              $output .= '<ul>';
552              foreach($planificacion['etapas'] as $texto) {
553                $output .= '<li>' . $texto . '</li>';
554              }
555              $output .= '</ul>';
556            }
557            $block = array(
558              'subject' => t('Planificación del ente @ente', array('@ente' => $ente_planificador->title)),
559              'content' => $output,
560            );
561          }
562        }
563        break;
564    }
565    return $block;
566  }
567}
568
569/*
570 * Implementation of ente_planificador_view_planning()
571 */
572function ente_planificador_view_planning($ente_planificador) {
573  $output = '<p>' . t('Ente planificador: @ente', array('@ente' => $ente_planificador->title)) . '</p>';
574  $estados = ente_planificador_status_planificacion($ente_planificador->nid, $ente_planificador->tipo);
575  $header = array();
576  $header[] = array('data' => t('Etapa'));
577  $header[] = array('data' => t('Estado'));
578  $rows = array();
579  $total_suma = 0;
580  $total_ejecutado = 0; 
581  if (count($estados)) {
582    foreach($estados as $estado) {
583      $row = array();
584      $row[] = array(
585        'data' => '<b>' . $estado['title'] . '</b>',
586        'colspan' => '2',
587        'align' => 'center'
588      );
589      $rows[] = $row;
590      $porc = 0;
591      $etapas = count($estado['value']);
592      if ($etapas) {
593        $suma = 0;
594        foreach($estado['value'] as $value) {
595          $total_suma++;
596          $row = array();
597          $valor = $value['value'] ? t('Comenzada') : t('Por comenzar');
598          $row[] = array('data' => l($value['title'], $value['link']) ,);
599          $row[] = array('data' => $valor,);
600          $rows[] = $row;
601          if ($value['value']) {
602            $suma++;           
603          }
604        }
605        $total_ejecutado += $suma;
606        $porc = ($suma * 100) / $etapas;
607      }
608      $row = array();
609      $row[] = array(
610        'data' => '<b>' . t('Porcentaje') . '</b>',
611        'align' => 'right',
612      );
613      $row[] = array('data' => '<b>' . round($porc, 2) . ' %' . '</b>',);
614      $rows[] = $row;
615    }
616    $total_porcentaje = ($total_suma > 0) ? ($total_ejecutado * 100) / $total_suma : 0;
617    $row = array();
618    $row[] = array(
619      'data' => '<b>' . t('Porcentaje Total : ') . round($total_porcentaje, 2) . ' %</b>',
620      'colspan' => '2',
621      'align' => 'center',
622    );
623    $rows[] = $row;
624  }
625  if (!count($rows)) {
626    $row = array();
627    $row[] = array(
628      'data' => t('No se ha podido calcular el estado de planificación del ente: @ente',
629      array(
630        '@ente' => $ente_planificador->title
631      )),
632      'colspan' => '2',
633      'align' => 'center'
634    );
635    $rows[] = $row;
636  }
637  $output .= theme('table', $header, $rows);
638  return $output;
639}
640
641/*
642 * usuario_tiene_permisos
643 * Verifica si el usuario actual tiene permisos de administracion o editar todos los entes
644 */
645function usuario_tiene_permisos() {
646  global $user;
647  if ($user->ui == 1 || user_access('edit all planificador') || user_access('admin planificador')) {
648    return TRUE;
649  }
650  return FALSE;
651}
652
653/*
654 * ente_planificador_fecha_planificacion_edit_notificacion
655 * Permite editar las fechas de notificacion de planificacion
656 */
657function ente_planificador_fecha_planificacion_edit_notificacion($form_state) {
658  $procesos_status = ente_planificador_procesos('status');
659  $procesos = ente_planificador_procesos();
660  $procesos_ordenados = ente_planificador_ordena_procesos($procesos_status, $procesos);
661  $i = 0;
662  $procesos = $procesos_ordenados['normal'];
663  $procesos_status = $procesos_ordenados['status'];
664  if (is_array($procesos_status) && count($procesos_status)) {
665    foreach($procesos_status as $id => $valores) {
666      $form[$id] = array(
667        '#type' => 'fieldset',
668        '#title' => check_plain($valores['title']),
669      );
670      if (is_array($procesos[$id]) && count($procesos[$id])) {
671        foreach ($procesos[$id] as $type_url_str => $proceso) {
672          $FIPMI = variable_get('ente_planificador_' . $type_url_str  . "_cron", 0);
673          $form[$id][$type_url_str] = array(
674            '#type' => 'fieldset',
675            '#title' => t('Fecha de %name', array('%name' => $proceso['title'],)),
676          );
677          $now = time();
678          $FIPM = $FIPMI ? $FIPMI : $now;
679          $FFPM = $FIPMF ? $FIPMF : $now;
680          $f1 = explode("-", gmdate("Y-m-d", $FIPM));
681          settype($f1[0], "integer");
682          settype($f1[1], "integer");
683          settype($f1[2], "integer");
684          $form[$id][$type_url_str][$type_url_str] = array(
685            '#type' => 'date',
686            '#title' => t('Fecha de notificacion'),
687            '#default_value' => array(
688              'day' => $f1[2],
689              'month' => $f1[1],
690              'year' => $f1[0],
691            ),
692            '#description' => t('Seleccione la fecha'),
693          );
694          $i++;
695        }
696      }
697    }
698  }
699  if (!$i) {
700    global $user;
701    drupal_set_message(t('No existen procesos que planificar'));
702    drupal_goto('user/' . $user->uid);
703    return array();
704  }
705  else {
706    $form['submit'] = array(
707      '#type' => 'submit',
708      '#validate' =>array('ente_planificador_fecha_planificacion_edit_notificacion_validate'),
709      '#submit' => array('ente_planificador_fecha_planificacion_edit_notificacion_submit'),
710      '#default_value' => t("Guardar"),
711    );
712    $enlace = base_path() . 'fechas_planificacion';
713    $form['cancel'] = array(
714      '#type' => 'submit',
715      '#weight'=>'8615',
716      '#attributes' => array('onClick' => 'window.location="' . $enlace . '"; return false;'),
717      '#value' => t('Cancel'),
718    );
719    return $form;
720  }
721}
722
723/*
724 * ente_planificador_fecha_planificacion_edit_notificacion_validate
725 * Validar la informacion de modificar las fechas de notificacion de planificacion
726 */
727function ente_planificador_fecha_planificacion_edit_notificacion_validate($form, &$form_state){
728  $procesos = ente_planificador_procesos();
729  foreach ($procesos as $key => $proceso) {
730    $fn =  mktime(
731      0,
732      0,
733      0,
734      $form_state['values'][$key]['month'],
735      $form_state['values'][$key]['day'],
736      $form_state['values'][$key]['year']
737    );
738    $ff = variable_get('ente_planificador_' . $key . "_until", 0);
739    if ($ff <= $fn) {
740      form_set_error(
741        $key,
742        t('La fecha de notificación para %name debe ser mayor a la fecha de culminación @ff @fi', array(
743          '%name' => $proceso['title'],
744          '@ff' => format_date($ff),
745          '@fi' => format_date($fn),
746        ))
747      );
748    }
749  }
750}
751
752/*
753 * ente_planificador_fecha_planificacion_edit_notificacion_submit
754 * Guardar la informacion de modificar las fechas de notificacion de planificacion
755 */
756function ente_planificador_fecha_planificacion_edit_notificacion_submit($form, &$form_state){
757  $procesos = ente_planificador_procesos();
758  foreach ($procesos as $type_url_str => $proceso) {
759    $fn =  mktime(
760      0,
761      0,
762      0,
763      $form_state['values'][$type_url_str]['month'],
764      $form_state['values'][$type_url_str]['day'],
765      $form_state['values'][$type_url_str]['year']
766    );
767    variable_set('ente_planificador_' . $type_url_str . '_cron', $fn);
768  }
769  drupal_set_message(t('Se han guardado los cambios'));
770}
771
772/*
773 * ente_planificador_fecha_planificacion_edit_todas
774 * Permite editar todas las fechas de planificacion
775 */
776function ente_planificador_fecha_planificacion_edit_todas($form_state) {
777  $procesos_status = ente_planificador_procesos('status');
778  $procesos = ente_planificador_procesos();
779  $procesos_ordenados = ente_planificador_ordena_procesos($procesos_status, $procesos);
780  $i = 0;
781  $procesos = $procesos_ordenados['normal'];
782  $procesos_status = $procesos_ordenados['status'];
783  if (is_array($procesos_status) && count($procesos_status)) {
784    foreach($procesos_status as $id => $valores) {
785      $form[$id] = array(
786        '#type' => 'fieldset',
787        '#title' => check_plain($valores['title']),
788      );
789      if (is_array($procesos[$id]) && count($procesos[$id])) {
790        foreach ($procesos[$id] as $type_url_str => $proceso) {
791          $FIPMI = variable_get('ente_planificador_' . $type_url_str  . "_from", 0);
792          $FIPMF = variable_get('ente_planificador_' . $type_url_str . "_until", 0);
793          $form[$id][$type_url_str] = array(
794            '#type' => 'fieldset',
795            '#title' => t('Fecha de %name', array('%name' => $proceso['title'],)),
796          );
797          $now = time();
798          $FIPM = $FIPMI ? $FIPMI : $now;
799          $FFPM = $FIPMF ? $FIPMF : $now;
800          $f1 = explode("-", gmdate("Y-m-d", $FIPM));
801          settype($f1[0], "integer");
802          settype($f1[1], "integer");
803          settype($f1[2], "integer");
804          $form[$id][$type_url_str][$type_url_str . '_from'] = array(
805            '#type' => 'date',
806            '#title' => t('Fecha de Inicio'),
807            '#default_value' => array(
808              'day' => $f1[2],
809              'month' => $f1[1],
810              'year' => $f1[0],
811            ),
812            '#description' => t('Seleccione la fecha'),
813          );
814          $f1 = explode("-", gmdate("Y-m-d", $FFPM));
815          settype($f1[0], "integer");
816          settype($f1[1], "integer");
817          settype($f1[2], "integer");
818          $form[$id][$type_url_str][$type_url_str . '_until'] = array(
819            '#type' => 'date',
820            '#title' => t('Fecha de Culminación'),
821            '#default_value' => array(
822              'day' => $f1[2],
823              'month' => $f1[1],
824              'year' => $f1[0],
825            ),
826            '#description' => t('Seleccione la fecha'),
827          );
828          $i++;
829        }
830      }
831    }
832  }
833  if (!$i) {
834    global $user;
835    drupal_set_message(t('No existen procesos que planificar'));
836    drupal_goto('user/' . $user->uid);
837    return array();
838  }
839  else {
840    $form['submit'] = array(
841      '#type' => 'submit',
842      '#validate' =>array('ente_planificador_fecha_planificacion_edit_todas_validate'),
843      '#submit' => array('ente_planificador_fecha_planificacion_edit_todas_submit'),
844      '#default_value' => t("Guardar"),
845    );
846    $enlace = base_path() . 'fechas_planificacion';
847    $form['cancel'] = array(
848      '#type' => 'submit',
849      '#weight'=>'8615',
850      '#attributes' => array('onClick' => 'window.location="' . $enlace . '"; return false;'),
851      '#value' => t('Cancel'),
852    );
853    return $form;
854  }
855}
856
857/*
858 * ente_planificador_fecha_planificacion_edit_todas_validate
859 * Validar la informacion de modificar todas las fechas de planificacion
860 */
861function ente_planificador_fecha_planificacion_edit_todas_validate($form, &$form_state){
862  $procesos = ente_planificador_procesos();
863  foreach ($procesos as $key => $proceso) {
864    $fi =  mktime(
865      0,
866      0,
867      0,
868      $form_state['values'][$key . '_from']['month'],
869      $form_state['values'][$key . '_from']['day'],
870      $form_state['values'][$key . '_from']['year']
871    );
872    $ff =  mktime(
873      0,
874      0,
875      0,
876      $form_state['values'][$key . '_until']['month'],
877      $form_state['values'][$key . '_until']['day'],
878      $form_state['values'][$key . '_until']['year']
879    );
880    if ($ff <= $fi) {
881      form_set_error(
882        $key . '_from',
883        t('La fecha de culminación para %name debe ser mayor a la fecha de inicio @ff @fi', array(
884          '%name' => $proceso['title'],
885          '@ff' => format_date($ff),
886          '@fi' => format_date($fi),
887        ))
888      );
889    }
890  }
891}
892
893/*
894 * ente_planificador_fecha_planificacion_edit_todas_submit
895 * Guardar la informacion de modificar todas las fechas de planificacion
896 */
897function ente_planificador_fecha_planificacion_edit_todas_submit($form, &$form_state){
898  $procesos = ente_planificador_procesos();
899  foreach ($procesos as $type_url_str => $proceso) {
900    $fi =  mktime(
901      0,
902      0,
903      0,
904      $form_state['values'][$type_url_str . '_from']['month'],
905      $form_state['values'][$type_url_str . '_from']['day'],
906      $form_state['values'][$type_url_str . '_from']['year']
907    );
908    $ff =  mktime(
909      0,
910      0,
911      0,
912      $form_state['values'][$type_url_str . '_until']['month'],
913      $form_state['values'][$type_url_str . '_until']['day'],
914      $form_state['values'][$type_url_str . '_until']['year']
915    );
916    variable_set('ente_planificador_' . $type_url_str . '_from', $fi);
917    variable_set('ente_planificador_' . $type_url_str . '_until', $ff);
918  }
919  drupal_set_message(t('Se han guardado los cambios'));
920}
921
922/*
923 * Implementation of hook_cron()
924 */
925function ente_planificador_cron() {
926  $procesos_cron = array();
927  $now = time();
928  $procesos = ente_planificador_procesos();
929  $cuerpoMi = t("Fechas de Planificación") . "\n";
930  foreach ($procesos as $type_url_str => $name) {
931    $FIPMC = variable_get('ente_planificador_' . $type_url_str . "_cron", 0);
932    $FIPMI = variable_get('ente_planificador_' . $type_url_str . "_from", 0);
933    $FIPMF = variable_get('ente_planificador_' . $type_url_str . "_until", 0);
934    if ($FIPMI) {
935      $FIPMI = format_date($FIPMI);
936    }
937    else {
938      $FIPMI = t("N/A");
939    }
940    if ($FIPMF) {
941      $FIPMF = format_date($FIPMF);
942    }
943    else {
944      $FIPMF = t("N/A");
945    }
946    $cuerpoMi .= ' ' . t(check_plain($name)) . " : " . t("Fecha de Inicio: ") . $FIPMI . t("Fecha de Culminación: ") . $FFPMF . "\n";
947    if ($FIPMC +3600 < $now && $FIPMC > now) {
948      $procesos_cron[] = $type_url_str;
949    }
950  }
951  if (!count($procesos_cron)) {
952    return;
953  }
954  $default_from = variable_get('site_mail', ini_get('sendmail_from'));
955  $emails = array();
956  $plan = array();
957  $result = db_query("select u.mail, e.nid from {users} u, {ente_user_planificador} e where e.usuario = u.uid AND status > 1");
958  while($usuarios = db_fetch_object($result)) {
959    $emails[$usuarios->nid][] = $usuarios->email;
960  }
961  foreach($emails as $id => $value) {
962    $planificacion = ente_planificador_obtiene_resumen_planificacion($id);
963    if ($planificacion['total'] >= 100) {
964      unset($emails[$id]);
965    }
966    else {
967      $plan[$id] = $planificacion['total'];
968    }
969  }
970  $cuerpo = t(
971    'Estimado usuario le recordamos que la fecha de planificación para los procesos (@procesos) se encuentra llegando a su fin',
972    array(
973      '@procesos' => implode(',', $procesos_cron)
974    )
975  ) . "\n";
976  foreach($emails as $id => $value) {
977    $text_emails = implode(',', $value);
978    $cuerpo1 = t('Su ente ha alcanzado hasta la fecha un porcentaje de avance de @avance %', array('@avance' => $plan[$id])) . "\n";
979    $cuerpoF = $cuerpo . $cuerpo1 . $cuerpoMi;
980    $message = array(
981      'to' => $text_emails,
982      'subject' => t('Fechas de Planificación'),
983      'body' => $cuerpo1,
984      'headers' => array('From' => $default_from),
985    );
986    drupal_mail_send($message);
987  }
988  drupal_set_message(t("Se han enviado los correo"));
989}
990
991
992/*
993 * ente_planificador_fecha_planificacion_correo
994 * Enviar correo electronico de las fechas de planificacion
995 */
996function ente_planificador_fecha_planificacion_correo() {
997  $result = db_query("select u.mail from {users} u, {ente_user_planificador} e where e.usuario = u.uid AND status > 0");
998  $emails = array();
999  while($usuarios = db_fetch_object($result)) {
1000    $emails[] = $usuarios->mail;
1001  }
1002  if (!count($emails)) {
1003    drupal_goto('fechas_planificacion');
1004    return;
1005  }
1006  $text_emails = implode(',',$emails);
1007  $default_from = variable_get('site_mail', ini_get('sendmail_from'));
1008  $cuerpo = t('Estimado usuario a continuación le enviamos las fechas de Inicio y culminación de las distintas etapas de planificación') . "\n";
1009  $cuerpoMi = t("Fechas de Planificación") . "\n";
1010  $procesos = ente_planificador_procesos();
1011  $procesos_status = ente_planificador_procesos('status');
1012  $procesos = ente_planificador_procesos();
1013  $procesos_ordenados = ente_planificador_ordena_procesos($procesos_status, $procesos);
1014  $i = 0;
1015  $procesos = $procesos_ordenados['normal'];
1016  $procesos_status = $procesos_ordenados['status'];
1017  if (is_array($procesos_status) && count($procesos_status)) {
1018    foreach($procesos_status as $id => $valores) {
1019      $cuerpoMi .= t('Etapa') . ' ' . check_plain($valores['title']) . "\n";
1020      if (is_array($procesos[$id]) && count($procesos[$id])) {
1021        foreach ($procesos[$id] as $type_url_str => $proceso) {
1022          $FIPMI = variable_get('ente_planificador_' . $type_url_str . "_from", 0);
1023          $FIPMF = variable_get('ente_planificador_' . $type_url_str . "_until", 0);
1024          if ($FIPMI) {
1025            $FIPMI = format_date($FIPMI);
1026          }
1027          else {
1028            $FIPMI = t("N/A");
1029          }
1030          if ($FIPMF) {
1031            $FIPMF = format_date($FIPMF);
1032          }
1033          else {
1034            $FIPMF = t("N/A");
1035          }
1036          $cuerpoMi .= ' ' . t(check_plain($proceso['title'])) . " : " . t("Fecha de Inicio: ") . $FIPMI . t("Fecha de Culminación: ") . $FIPMF . "\n";
1037        }
1038      }
1039    }
1040  }
1041  $cuerpo .= $cuerpoMi;
1042  $message = array(
1043    'to' => $text_emails,
1044    'subject' => t('Fechas de Planificación'),
1045    'body' => $cuerpo,
1046    'headers' => array('From' => $default_from),
1047  );
1048  drupal_mail_send($message);
1049  drupal_set_message(t("Se ha enviado el correo: !usuarios_emails", array('!usuarios_emails' => theme('item_list', $emails))));
1050  drupal_goto('fechas_planificacion');
1051}
1052
1053/*
1054 * ente_planificador_fecha_planificacion_edit
1055 * Editar una fecha de planificacion
1056 */
1057function ente_planificador_fecha_planificacion_edit($type_node = '') {
1058  $procesos = ente_planificador_procesos();
1059  if (isset($procesos[$type_node])) {
1060    return drupal_get_form('ente_planificador_fecha_planificacion_edit_form', $type_node);
1061  }
1062  return NULL;
1063}
1064
1065/*
1066 * ente_planificador_fecha_planificacion_edit_form
1067 * Editar una fecha de planificacion
1068 */
1069function ente_planificador_fecha_planificacion_edit_form($form_state, $type_node = NULL) {
1070  $procesos = ente_planificador_procesos();
1071  $tipos_fecha = array(
1072    'from' => t('Inicio'),
1073    'until' => t('Fin'),
1074  );
1075  $FIPMI = variable_get('ente_planificador_' . $type_node . "_from", 0);
1076  $f1 = explode("-", gmdate("Y-m-d", $FIPMI));
1077  settype($f1[0], "integer");
1078  settype($f1[1], "integer");
1079  settype($f1[2], "integer");
1080  $FIPMF = variable_get('ente_planificador_' . $type_node . "_until", 0);
1081  $f2 = explode("-", gmdate("Y-m-d", $FIPMF));
1082  settype($f2[0], "integer");
1083  settype($f2[1], "integer");
1084  settype($f2[2], "integer");
1085  $form = array();
1086  $form['type_page_node'] = array(
1087    '#type' => 'hidden',
1088    '#default_value' => $type_node,
1089  );
1090  $form['from'] = array(
1091    '#type' => 'date',
1092    '#title' => t('Modificar la fecha de inicio para %name', array('%name' => $procesos[$type_node]['title'])),
1093    '#default_value' => array(
1094      'day' => $f1[2],
1095      'month' => $f1[1],
1096      'year' => $f1[0],
1097      ),
1098    '#description' => t('Seleccione la fecha'),
1099    );
1100  $form['until'] = array(
1101    '#type' => 'date',
1102    '#title' => t('Modificar la fecha de culminación para %name', array('%name' => $procesos[$type_node]['title'])),
1103    '#default_value' => array(
1104      'day' => $f2[2],
1105      'month' => $f2[1],
1106      'year' => $f2[0],
1107      ),
1108    '#description' => t('Seleccione la fecha'),
1109    );
1110    $form['submit'] = array(
1111      '#type' => 'submit',
1112      '#default_value' => t("Guardar"),
1113    );
1114    $enlace = base_path() . 'fechas_planificacion';
1115   $form['cancel'] = array(
1116     '#type' => 'submit',
1117     '#weight'=>'8615',
1118     '#attributes' => array('onClick' => 'window.location="' . $enlace . '"; return false;'),
1119     '#value' => t('Cancel'),
1120   );
1121  return $form;
1122}
1123
1124/*
1125 * ente_planificador_fecha_planificacion_edit_form_validate
1126 * Validar una fecha de planificacion
1127 */
1128function ente_planificador_fecha_planificacion_edit_form_validate($form, &$form_state) {
1129  $key = $form_state['values']['type_page_node'];
1130  $procesos = ente_planificador_procesos();
1131  if (isset($procesos[$key])) {
1132    $fi =  mktime(0, 0, 0, $form_state['values']['from']['month'], $form_state['values']['from']['day'], $form_state['values']['from']['year']);
1133    $ff =  mktime(0, 0, 0, $form_state['values']['until']['month'], $form_state['values']['until']['day'], $form_state['values']['until']['year']);
1134    if ($ff <= $fi) {
1135      form_set_error('until', t('La fecha de culminación para %name debe ser mayor a la fecha de inicio @ff @fi', array('%name' => $procesos[$key], '@ff' => format_date($ff), '@fi' => format_date($fi), )));
1136    }
1137  }
1138  else {
1139    form_set_error('until', t('La fecha final para %name debe ser mayor a la inicial @ff @fi', array('%name' => $name, '@ff' => format_date($ff), '@fi' => format_date($fi), )));
1140    drupal_set_message(t("Ocurrio un error al intentar almacenar la fecha"));
1141    drupal_goto('fechas_planificacion');
1142  }
1143}
1144
1145/*
1146 * ente_planificador_fecha_planificacion_edit_form_submit
1147 * Guardar una fecha de planificacion
1148 */
1149function ente_planificador_fecha_planificacion_edit_form_submit($form, &$form_state) {
1150  $fi =  mktime(
1151    0,
1152    0,
1153    0,
1154    $form_state['values']['from']['month'],
1155    $form_state['values']['from']['day'],
1156    $form_state['values']['from']['year']
1157  );
1158  $ff =  mktime(
1159    0,
1160    0,
1161    0,
1162    $form_state['values']['until']['month'],
1163    $form_state['values']['until']['day'],
1164    $form_state['values']['until']['year']
1165  );
1166  $key = $form_state['values']['type_page_node'];
1167  $procesos = ente_planificador_procesos();
1168  variable_set('ente_planificador_' . $key . '_from', $fi);
1169  variable_set('ente_planificador_' . $key . '_until', $ff);
1170  drupal_set_message(t("Actualizadas las fechas para %name", array('%name' => $procesos[$key]['title'])));
1171  drupal_goto('fechas_planificacion');
1172}
1173
1174/*
1175 * Implementation of ente_planificador_procesos()
1176 * Lista los procesos de la planificacion
1177 */
1178function ente_planificador_procesos($type = 'normal') {
1179  $procesos = array();
1180  drupal_alter('ente_procesos', $procesos, $type);
1181  return $procesos;
1182}
1183
1184/*
1185 * Implementation of ente_planificador_ordena_procesos()
1186 * Ordena los procesos por pesos(weight)
1187 */
1188function ente_planificador_ordena_procesos($procesos_status, $procesos) {
1189  $nuevo_proceso = array();
1190  $reemplazo = array();
1191  //se añade cada uno de los procesos a su categoría con su peso
1192  if (is_array($procesos) && count($procesos)) {
1193    foreach($procesos as $id => $arreglo) {
1194      $nuevo_proceso[$arreglo['proceso']][$arreglo['weight']][$id] = $arreglo;
1195    }
1196    foreach($nuevo_proceso as $id => $arreglo) {
1197      ksort($nuevo_proceso[$id]);
1198    }
1199    foreach($nuevo_proceso as $id => $valores) {
1200      foreach($valores as $valor) {
1201        foreach ($valor as $ids => $proceso) {
1202          $reemplazo[$id][$ids] = $proceso;
1203        }
1204      }
1205    }
1206  }
1207  $nuevo_proceso = $reemplazo;
1208  $indices = array();
1209  $reemplazo = array();
1210  if (is_array($procesos_status) && count($procesos_status)) {
1211    foreach($procesos_status as $id => $arreglo) {
1212      $indices[$arreglo['weight']][] = $id;
1213    }
1214    ksort($indices);
1215    foreach($indices as $weight => $valores) {
1216      foreach($valores as $valor) {
1217        $reemplazo[$valor] = $procesos_status[$valor];
1218      }
1219    }
1220  }
1221  $procesos_status = $reemplazo;
1222  return array(
1223    'normal' => $nuevo_proceso,
1224    'status' => $procesos_status,
1225  );
1226}
1227
1228/*
1229 * ente_planificador_fecha_planificacion
1230 * Mostrar las fechas de planificacion
1231 */
1232function ente_planificador_fecha_planificacion($type = '') {
1233  $view = FALSE;
1234  if (user_access('admin planificador')) {
1235    $view = TRUE;
1236  }
1237  $header[] = array('data' => t('Name'));
1238  $header[] = array('data' => t('Fecha de Inicio'));
1239  $header[] = array('data' => t('Fecha de Culminación'));
1240  if ($view) {
1241    $header[] = array('data' => t('Operación'));
1242  }
1243  $procesos_status = ente_planificador_procesos('status');
1244  $procesos = ente_planificador_procesos();
1245  $procesos_ordenados = ente_planificador_ordena_procesos($procesos_status, $procesos);
1246  $procesos_status = $procesos_ordenados['status'];
1247  $nuevo_proceso = $procesos_ordenados['normal'];
1248  $rows = array();
1249  $fechas_agregar = TRUE;
1250  if (is_array($procesos_status) && count($procesos_status)) {
1251    foreach($procesos_status as $id => $valores) {
1252      $row = array();
1253      $row[] = array('data' => '<b>' . $procesos_status[$id]['title'] . '</b>', 'colspan' => 4, 'align' => 'center');
1254      $rows[] = $row;
1255      if (is_array($nuevo_proceso[$id]) && count($nuevo_proceso[$id])) {
1256        foreach ($nuevo_proceso[$id] as $type_url_str => $proceso) {
1257          $FIPMI = variable_get('ente_planificador_' . $type_url_str . "_from", 0);
1258          $FIPMF = variable_get('ente_planificador_' . $type_url_str . "_until", 0);
1259          if ($view) {
1260            if ($FIPMI) {
1261              $fechas_agregar = FALSE;
1262              $FIPMI = format_date($FIPMI);
1263            }
1264            else {
1265              $FIPMI = t("N/A");
1266            }
1267            if ($FIPMF) {
1268              $fechas_agregar = FALSE;
1269              $FIPMF = format_date($FIPMF);
1270            }
1271            else {
1272              $FIPMF = t("N/A");
1273            }
1274          }
1275          else {
1276            if ($FIPMI) {
1277              $fechas_agregar = FALSE;
1278              $FIPMI = format_date($FIPMI);
1279            }
1280            else {
1281              $FIPMI = t("N/A");
1282            }
1283            if ($FIPMF) {
1284              $fechas_agregar = FALSE;
1285              $FIPMF = format_date($FIPMF);
1286            }
1287            else {
1288              $FIPMF = t("N/A");
1289            }
1290          }
1291          $row = array();
1292          $row[] = array('data' => t(check_plain($proceso['title'])), );
1293          $row[] = array('data' => $FIPMI, );
1294          $row[] = array('data' => $FIPMF, );
1295          if ($view) {
1296            $row[] = array('data' => l(t('Modificar'), 'fechas_planificacion/edit/' . $type_url_str), );
1297          }
1298          $rows[] = $row;
1299        }
1300      }
1301    }
1302  }
1303  $fechas_display = TRUE;
1304  if (!count($rows)) {
1305    $row = array();
1306    $row[] = array('data' => t('No se encontrarón fechas para planificar'), 'colspan' => 4);
1307    $rows[] = $row;
1308    $fechas_display = FALSE;
1309  }
1310  $aux = "";
1311  if (user_access('admin planificador') && $fechas_display) {
1312    if ($fechas_agregar) {
1313      $aux = l(t("Agregar las fechas para los procesos de planificación."), 'fechas_planificacion/todas_edit');
1314    }
1315    $aux .= '<br>' . l(t("Enviar Correo Electrónico a los entes planificadores"), 'fechas_planificacion/envia_email');
1316    $aux .= '<br>' . l(t("Fecha para reportar mensaje de alerta respecto al registro o modificación de información"), 'fechas_planificacion/notificacion');
1317  }
1318  return theme('table', $header, $rows).$aux;
1319}
1320
1321/*
1322 * ente_planificador_admin_settings
1323 * Configurar entes planificadores
1324 */
1325function ente_planificador_admin_settings() {
1326  $form = array();
1327  $roles = user_roles(TRUE);
1328  unset($roles[2]);
1329  if (count($roles)) {
1330    $form['ActorPlanificadorMacro'] = array(
1331      '#type' => 'select',
1332      '#title' => t('Rol para el Actor estratégico-táctico'),
1333      '#default_value' => variable_get('ActorPlanificadorMacro', 2),
1334      '#options' => $roles,
1335      '#description' => t('Seleccione el rol para el Actor estratégico-táctico'),
1336    );
1337    $form['ActorPlanificadorMicro'] = array(
1338      '#type' => 'select',
1339      '#title' => t('Rol para el Actor operativo'),
1340      '#default_value' => variable_get('ActorPlanificadorMicro', 2),
1341      '#options' => $roles,
1342      '#description' => t('Seleccione el rol para el Actor operativo'),
1343    );
1344    return system_settings_form($form);
1345  }
1346}
1347
1348/*
1349 * entes_planificadores_listar_usuarios
1350 * Listar todos los usuarios asociados a entes planificadores
1351 */
1352function entes_planificadores_listar_usuarios() {
1353  global $user;
1354  $step = 10;
1355  $output = '';
1356  $ente = NULL;
1357  $Lista_entes = array();
1358  $sqlcount = "select count(u.uid) from {users} u, {ente_user_planificador} up, {node} n where u.uid = up.usuario and up.nid =n.nid";
1359  $sql = "select n.title, n.nid, u.name, u.nombres, u.apellidos, u.cedula, u.uid from {users} u, {ente_user_planificador} up, {node} n where u.uid = up.usuario and up.nid =n.nid";
1360  $headers_table[] = array('data' => t('Nombre de Usuario'), 'sort' => 'asc', 'field' => 'u.name');
1361  $headers_table[] = array('data' => t('Nombres'), 'sort' => 'asc', 'field' => 'u.nombres');
1362  $headers_table[] = array('data' => t('Apellidos'), 'sort' => 'asc', 'field' => 'u.apellidos');
1363  $headers_table[] = array('data' => t('Cédula de Identidad'), 'sort' => 'asc', 'field' => 'u.cedula');
1364  $headers_table[] = array('data' => t('Ente Planificador'), 'sort' => 'asc', 'field' => 'n.title');
1365  $headers_table[] = array('data' => t('Consultar'));
1366  $headers_table[] = array('data' => t('Modificar'));
1367  $headers_table[] = array('data' => t('Eliminar'));
1368  $sql.= tablesort_sql($headers_table);
1369  $result = pager_query($sql, $step, 0, $sqlcount,$user->uid);
1370  while($ente = db_fetch_object($result)) {
1371    $Lista_entes[] = array(
1372      'name'=>l($ente->name, 'user/' . $ente->uid, array('html' => true, 'query' => 'destination=administrar_usuarios')),
1373      'nombres' => l($ente->nombres, 'user/' . $ente->uid, array('html' => true, 'query' => 'destination=administrar_usuarios')),
1374      'apellidos' => l($ente->apellidos, 'user/' . $ente->uid, array('html' => true, 'query' => 'destination=administrar_usuarios')),
1375      'cedula'=>l($ente->cedula, 'user/' . $ente->uid, array('html' => true, 'query' => 'destination=administrar_usuarios')),
1376      'ente' => l($ente->title, 'node/' . $ente->nid, array('html' => true, 'query' => 'destination=administrar_usuarios')),
1377      'consultar' => l(t("Consultar"), 'user/' . $ente->uid, array('html' => true, 'query' => 'destination=administrar_usuarios')),
1378      'modificar' => l(t("Modificar"), 'user/' . $ente->uid . "/edit", array('html' => true, 'query' => 'destination=administrar_usuarios')),
1379      'eliminar' => l(t("Eliminar"), 'user/' . $ente->uid . "/delete", array('html' => true, 'query' => 'destination=administrar_usuarios')),
1380    );
1381  }
1382  if (sizeof($Lista_entes)) {
1383    $output.= theme('table', $headers_table, $Lista_entes);
1384    $output .= theme('pager', NULL);
1385  }
1386  else {
1387    $output.= '<p>' . t('No se encontraron usuarios en el sistema') . '</p>';
1388  }
1389  return $output;
1390}
1391
1392/*
1393 * mis_entes_planificadores
1394 * Listar todos los entes planificadores asociados al usuario actual
1395 */
1396function mis_entes_planificadores() {
1397  global $user;
1398  $step = 10;
1399  $output = '';
1400  $ente = usuario_tiene_ente($user->uid);
1401  if ($ente->nid) {
1402    $ente = ente_planificador_leer($ente->nid);
1403    $output .= node_view($ente);
1404    $estados = ente_planificador_status_planificacion($ente->nid, $ente->tipo);
1405    $header = array();
1406    $header[] = array('data' => t('Etapa'));
1407    $header[] = array('data' => t('Estado'));
1408    $rows = array();
1409    $total_suma = 0;
1410    $total_ejecutado = 0; 
1411    if (count($estados)) {
1412      foreach($estados as $estado) {
1413        $row = array();
1414        $row[] = array(
1415          'data' => '<b>' . $estado['title'] . '</b>',
1416          'colspan' => '2',
1417          'align' => 'center'
1418        );
1419        $rows[] = $row;
1420        $porc = 0;
1421        $etapas = count($estado['value']);
1422        if ($etapas) {
1423          $suma = 0;
1424          foreach($estado['value'] as $value) {
1425            $total_suma++;
1426            $row = array();
1427            $valor = $value['value'] ? t('Si') : t('No');
1428            $row[] = array('data' => l($value['title'], $value['link']),);
1429            $row[] = array('data' => $valor,);
1430            $rows[] = $row;
1431            if ($value['value']) {
1432              $suma++;           
1433            }
1434          }
1435          $total_ejecutado += $suma;
1436          $porc = ($suma * 100) / $etapas;
1437        }
1438        $row = array();
1439        $row[] = array(
1440          'data' => '<b>' . t('Porcentaje') . '</b>',
1441          'align' => 'right',
1442        );
1443        $row[] = array(
1444          'data' => '<b>' . round($porc, 2) . ' %' . '</b>',
1445        );
1446        $rows[] = $row;
1447      }
1448      $total_porcentaje = ($total_suma > 0) ? ($total_ejecutado * 100) / $total_suma : 0;
1449      $row = array();
1450      $row[] = array(
1451        'data' => '<b>' . t('Porcentaje Total : ') . round($total_porcentaje, 2) . ' %</b>',
1452        'colspan' => '2',
1453        'align' => 'center',
1454      );
1455      $rows[] = $row;
1456    }
1457    if (!count($rows)) {
1458      $row = array();
1459      $row[] = array(
1460        'data' => t('No se ha podido calcular el estado de planificación del ente: @ente',
1461          array(
1462            '@ente' => $ente_planificador->title
1463          )
1464        ),
1465        'colspan' => '2',
1466        'align' => 'center'
1467      );
1468      $rows[] = $row;
1469    }
1470  }
1471  $output .= theme('table', $header, $rows);
1472  $ente = NULL;
1473  $Lista_entes = array();
1474  $sqlcount = "SELECT count(u1.nid) FROM {node} n, {ente_user_planificador} u1  WHERE u1.usuario = %d AND u1.nid = n.nid";
1475  $sql = "SELECT n.title, n.nid FROM {node} n, {ente_user_planificador} u1  WHERE u1.usuario = %d AND u1.nid = n.nid";
1476  $headers_table[] = array(
1477    'data' => t('Ente Planificador'),
1478    'sort' => 'asc',
1479    'field' => 'n.title'
1480  );
1481  $headers_table[] = array(
1482    'data' => t('Consultar')
1483  );
1484  $headers_table[] = array(
1485    'data' => t('Modificar')
1486  );
1487  $sql.= tablesort_sql($headers_table);
1488  $result = pager_query($sql, $step, 0, $sqlcount,$user->uid);
1489  while($ente = db_fetch_object($result)) {
1490    $Lista_entes[] = array(
1491      'ente' => l($ente->title, 'node/' . $ente->nid, array('html' => true, 'query' => 'destination=mienteplanificador')),
1492      'consultar' => l(t("Consultar"), 'node/' . $ente->nid, array('html' => true, 'query' => 'destination=mienteplanificador')),
1493      'modificar' => l(t("Modificar"), 'node/edit/' . $ente->nid, array('html' => true, 'query' => 'destination=mienteplanificador')),
1494    );
1495  }
1496  if (sizeof($Lista_entes)) {
1497    $output.= theme('table', $headers_table, $Lista_entes);
1498    $output .= theme('pager', NULL);
1499  }
1500  else {
1501    $output.= '<p>' . t('No se encontraron entes asignados al usuario') . '</p>';
1502  }
1503  return $output;
1504}
1505
1506/*
1507 * entes_planificadores_agregar
1508 * Agregar un ente planificador
1509 */
1510function entes_planificadores_agregar() {
1511  drupal_goto('node/add/ente-planificador' , 'destination=administrar/entes_planificadores');
1512}
1513
1514/*
1515 * entes_planificadores_obtener_filtros
1516 * Generar filtros
1517 */
1518function entes_planificadores_obtener_filtros($filtro = array()) {
1519  $filters['nombre'] = array(
1520    '#type' => 'textfield',
1521    '#title' => t('Nombre'),
1522    '#size' => 20,
1523  );
1524  $filters['razon_social'] = array(
1525    '#type' => 'textfield',
1526    '#title' => t('Razón Social'),
1527    '#size' => 20,
1528  );
1529  $filters['rif'] = array(
1530    '#type' => 'textfield',
1531    '#title' => t('RIF'),
1532    '#size' => 20,
1533    '#maxlength' => 12,
1534  );
1535  $filters['direccion'] = array(
1536    '#type' => 'textfield',
1537    '#title' => t('Dirección'),
1538    '#size' => 20,
1539    '#maxlength' => 243,
1540  );
1541  $filters['ciudad'] = array(
1542    '#type' => 'textfield',
1543    '#title' => t('Ciudad'),
1544    '#size' => 20,
1545    '#maxlength' => 243,
1546  );
1547  //Se buscan las entidades
1548  $entidades = ente_planificador_obtener_lista_entidad();
1549  $estado = "01";
1550  if ($filtro['estado']) {
1551    $estado = $filtro['estado'];
1552  }
1553  $filters['estado'] = array(
1554    '#type' => 'select',
1555    '#title' => t('Estado').$form['estado'],
1556    '#options' => $entidades,
1557    '#ahah' => array(
1558      'event' => 'change',
1559      'path' => 'ente_planificador_js_util/municipio_select',
1560      'wrapper' => 'edit-municipio-wrapper',
1561      'method' => 'replace',
1562    ),
1563  );
1564  $municipio = $filtro['municipio'];
1565  $parroquia = $filtro['parroquia'];
1566  $filters['municipio'] = ente_planificador_obtener_form_municipio(
1567    t('Municipio'),
1568    $municipio,
1569    t('seleccione el municipio.'),
1570    $estado,
1571    $display = 'name',
1572    TRUE
1573  );
1574  $filters['parroquia'] = ente_planificador_obtener_form_parroquia(t('Parroquia'), $parroquia, t('seleccione la parroquia.'), $municipio, TRUE);
1575  $filters['municipio']['#required'] = FALSE;
1576  $filters['parroquia']['#required'] = FALSE;
1577  //Se buscan las actividades
1578  $actividades = ente_planificador_obtener_actividades();
1579  $filters['actividad'] = array(
1580    '#type' => 'select',
1581    '#title' => t('Actividades'),
1582    '#default_value' => $ente_planificador->actividad,
1583    '#options' => $actividades,
1584    '#description' => t('Seleccione una actividad.'),
1585  );
1586  return $filters;
1587}
1588
1589/*
1590 * ente_planificador_datos_basicos
1591 * Obtener formulario de los datos basicos
1592 */
1593function ente_planificador_datos_basicos($nid = '') {
1594  $output = '';
1595  $output .= drupal_get_form('ente_planificador_datos_basicos_forma', $nid);
1596  return $output;
1597}
1598
1599/*
1600 * ente_planificador_datos_basicos_forma
1601 * Obtener formulario de los datos basicos
1602 */
1603function ente_planificador_datos_basicos_forma(&$form_state, $nid = NULL) {
1604  $ente_planificador = NULL;
1605  if (is_numeric($nid)) {
1606    $ente_planificador = ente_planificador_leer_ente_planificadores($nid);
1607  }
1608  $form = array();
1609  if ($ente_planificador) {
1610    $form['ente_planificador_nid'] = array(
1611      '#type' => 'hidden',
1612      '#default_value' => $ente_planificador->nid,
1613    );
1614    $form['razon_social'] = array(
1615      '#type' => 'textfield',
1616      '#title' => t('Razón Social'),
1617      '#default_value' => $ente_planificador->razon_social,
1618      '#size' => 20,
1619      '#description' => t("Introduzca la Razón Social"),
1620      '#required' => TRUE,
1621    );
1622    $form['rif'] = array(
1623      '#type' => 'textfield',
1624      '#title' => t('RIF'),
1625      '#default_value' => $ente_planificador->rif,
1626      '#size' => 20,
1627      '#maxlength' => 12,
1628      '#description' => t("Introduzca el RIF"),
1629      '#required' => TRUE,
1630    );
1631    $form['direccion'] = array(
1632      '#type' => 'textfield',
1633      '#title' => t('Dirección'),
1634      '#default_value' => $ente_planificador->direccion,
1635      '#size' => 20,
1636      '#maxlength' => 243,
1637      '#description' => t("Introduzca la dirección"),
1638      '#required' => TRUE,
1639    );
1640    $form['ciudad'] = array(
1641      '#type' => 'textfield',
1642      '#title' => t('Ciudad'),
1643      '#default_value' => $ente_planificador->ciudad,
1644      '#size' => 20,
1645      '#maxlength' => 243,
1646      '#description' => t("Introduzca la ciudad"),
1647      '#required' => TRUE,
1648    );
1649    //Se buscan las entidades
1650    $entidades = ente_planificador_obtener_lista_entidad();
1651    if ($ente_planificador->estado) {
1652      $estado = $ente_planificador->estado;
1653    }
1654    else {
1655      $estado = '01';
1656    }
1657    $form['estado'] = array(
1658      '#type' => 'select',
1659      '#title' => t('Estado').$form['estado'],
1660      '#default_value' => $estado,
1661      '#options' => $entidades,
1662      '#description' => t('seleccione el estado.'),
1663      '#required' => TRUE,
1664      '#ahah' => array(
1665        'event' => 'change',
1666        'path' => 'ente_planificador_js_util/municipio_select',
1667        'wrapper' => 'edit-municipio-wrapper',
1668        'method' => 'replace',
1669      ),
1670    );
1671    if (!$ente_planificador->municipio) {
1672      $municipio = '0101';
1673    }
1674    else {
1675      $municipio = $ente_planificador->municipio;
1676    }
1677    $form['municipio'] = ente_planificador_obtener_form_municipio(t('Municipio'), $ente_planificador->municipio, t('seleccione el municipio.'), $estado, $display = 'name', TRUE);
1678    $form['parroquia'] = ente_planificador_obtener_form_parroquia(t('Parroquia'), $ente_planificador->parroquia, t('seleccione la parroquia.'), $ente_planificador->municipio, name, TRUE);
1679    $node_type = content_types('ente_planificador');
1680    $fields = $node_type['fields'];
1681    $field_form = array();
1682    if (is_array($fields) && count($fields)) {
1683      foreach($fields as $field_id => $field) {
1684        if (variable_get('ente_planificador_' . $field_id, FALSE)) {
1685          $field_form[] = $field_id;
1686        }
1687      }
1688    }
1689    $form['#ente_planificador_fields_datos'] = $field_form;
1690    if (is_array($field_form) && count($field_form)) {
1691      module_load_include('inc', 'content', 'includes/content.node_form');
1692      $form['#node'] = $ente_planificador;
1693      foreach ($field_form as $field_id) {
1694        $field = content_fields($field_id, 'ente_planificador');
1695        $form['#field_info'][$field_id] = $field;
1696        $form += (array) content_field_form($form, $form_state, $field);
1697      }
1698    }
1699    //Se buscan las actividades
1700    $actividades = ente_planificador_obtener_actividades();
1701    $form['actividad'] = array(
1702      '#type' => 'select',
1703      '#title' => t('Actividades'),
1704      '#default_value' => $ente_planificador->actividad,
1705      '#options' => $actividades,
1706      '#description' => t('Seleccione una actividad.'),
1707      '#multiple' => TRUE,
1708      '#required' => TRUE,
1709    );
1710    //add taxonomy if exist
1711    if (module_exists('taxonomy')) {
1712      if (!isset($ente_planificador->taxonomy)) {
1713        $terms = empty($ente_planificador->nid) ? array() : taxonomy_node_get_terms($ente_planificador);
1714      }
1715      else {
1716        // After a preview or form reload, the terms must be converted to objects.
1717        reset($ente_planificador->taxonomy);
1718        if (!is_object(current($ente_planificador->taxonomy))) {
1719          $ente_planificador->taxonomy = taxonomy_preview_terms($ente_planificador);
1720        }
1721        $terms = $ente_planificador->taxonomy;
1722      }
1723      $c = db_query(db_rewrite_sql("SELECT v.* FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $ente_planificador->type);
1724      while ($vocabulary = db_fetch_object($c)) {
1725        if ($vocabulary->tags) {
1726          if (isset($form_state['node_preview'])) {
1727            // Typed string can be changed by the user before preview,
1728            // so we just insert the tags directly as provided in the form.
1729            $typed_string = $ente_planificador->taxonomy['tags'][$vocabulary->vid];
1730          }
1731          else {
1732            $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
1733          }
1734          if ($vocabulary->help) {
1735            $help = filter_xss_admin($vocabulary->help);
1736          }
1737          else {
1738            $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
1739          }
1740          $form['taxonomy']['tags'][$vocabulary->vid] = array('#type' => 'textfield',
1741            '#title' => $vocabulary->name,
1742            '#description' => $help,
1743            '#required' => $vocabulary->required,
1744            '#default_value' => $typed_string,
1745            '#autocomplete_path' => 'taxonomy/autocomplete/'. $vocabulary->vid,
1746            '#weight' => $vocabulary->weight,
1747            '#maxlength' => 1024,
1748          );
1749        }
1750        else {
1751          // Extract terms belonging to the vocabulary in question.
1752          $default_terms = array();
1753          foreach ($terms as $term) {
1754            // Free tagging has no default terms and also no vid after preview.
1755            if (isset($term->vid) && $term->vid == $vocabulary->vid) {
1756              $default_terms[$term->tid] = $term;
1757            }
1758          }
1759          $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), filter_xss_admin($vocabulary->help));
1760          $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
1761          $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
1762        }
1763      }
1764      if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
1765        if (count($form['taxonomy']) > 1) {
1766          // Add fieldset only if form has more than 1 element.
1767          $form['taxonomy'] += array(
1768            '#type' => 'fieldset',
1769            '#title' => t('Vocabularies'),
1770            '#collapsible' => TRUE,
1771            '#collapsed' => FALSE,
1772          );
1773        }
1774        $form['taxonomy']['#weight'] = 8;
1775        $form['taxonomy']['#tree'] = TRUE;
1776      }
1777    }
1778    $form['buttons']['#weight'] = 100;
1779    $form['buttons']['submit'] = array(
1780      '#type' => 'submit',
1781      '#default_value' => t("Agregar los datos basicos del ente"),
1782      '#weight' => 100,
1783    );
1784  }
1785  if ($ente_planificador) {
1786    $enlace = base_path() . 'node/' . $ente_planificador->nid;
1787  }
1788  else {
1789    $enlace = base_path() . 'administrar/entes_planificadores';
1790  }
1791  return $form;
1792}
1793
1794/*
1795 * ente_planificador_datos_basicos_forma
1796 * Validar formulario de los datos basicos
1797 */
1798function ente_planificador_datos_basicos_forma_validate($form, &$form_state) {
1799  $form_values = $form_state['values'];
1800  if (!preg_match("/^(V|E|P|J|G){1}-([0-9]){8}-([0-9]){1}$/",$form_values['rif']) && !preg_match("/^(V|E){1}-([0-9]){8}$/",$form_values['rif'])) {
1801    form_set_error('rif', t('El formato del rif debe tener el siguiente formato G-00000000-0.'));
1802  }
1803  if (!($form_values['municipio'] > 0)) {
1804    form_set_error('municipio', t('Debe seleccionar un municipio.'));
1805  }
1806  if (!($form_values['parroquia'] > 0)) {
1807    form_set_error('parroquia', t('Debe seleccionar una parroquia.'));
1808  }
1809}
1810
1811/*
1812 * ente_planificador_datos_basicos_forma_submit
1813 * Guardar formulario de los datos basicos
1814 */
1815function ente_planificador_datos_basicos_forma_submit($form, &$form_state) {
1816  $form_values = $form_state['values'];
1817  $resultado1 =db_query("select nid from {ente_planificador} where nid = %d", $form_values['ente_planificador_nid']);
1818  $entes = db_fetch_object($resultado1);
1819  if ($entes->nid) {
1820    $result = db_query("update {ente_planificador} set razon_social = '%s', rif = '%s', direccion = '%s', estado = %d, municipio = %d, parroquia = %d, ciudad = '%s' where nid = %d", check_plain($form_values['razon_social']), check_plain($form_values['rif']), check_plain($form_values['direccion']), $form_values['estado'], $form_values['municipio'], $form_values['parroquia'], check_plain($form_values['ciudad']), $form_values['ente_planificador_nid']);
1821  }
1822  else {
1823    $result = db_query("INSERT INTO {ente_planificador} (nid, razon_social, rif, direccion, estado, municipio, parroquia, ciudad) VALUES (%d,'%s', '%s', '%s', %d, %d, %d, '%s', '%s')", $form_values['ente_planificador_nid'], check_plain($form_values['razon_social']), check_plain($form_values['rif']), check_plain($form_values['direccion']), $form_values['estado'], $form_values['municipio'], $form_values['parroquia'], check_plain($form_values['ciudad']));
1824  }
1825  $result = db_query("delete from {ente_actividad_ente} where nid = %d", $form_values['ente_planificador_nid']);
1826  $cant = count($form_values['actividad']);
1827  if ($cant) {
1828    foreach ($form_values['actividad'] as $actividad) {
1829      if ($actividad) {
1830        db_query("insert into {ente_actividad_ente} (nid, actividad) values (%d, %d)", $form_values['ente_planificador_nid'],  $actividad);
1831      }
1832    }
1833  }
1834  //add extra cck fields
1835  $field_form = $form['#ente_planificador_fields_datos'];
1836  module_load_include('inc', 'node', 'node.pages');
1837  node_object_prepare($node_load);
1838  $node_load = ente_planificador_leer_ente_planificadores($form_values['ente_planificador_nid']);
1839  if (isset($form_state['values']['taxonomy'])) {
1840    $node_load->taxonomy = $form_state['values']['taxonomy'];
1841  }
1842  if (is_array($field_form) && count($field_form)) {
1843    foreach ($field_form as $field_id) {
1844      if (isset($form_state['values'][$field_id]) && is_array($form_state['values'][$field_id])) {
1845        foreach($form_state['values'][$field_id] as $id => $value) {
1846          if (is_numeric($id) && isset($form_state['values'][$field_id][$id]['_error_element'])) {
1847            unset($form_state['values'][$field_id][$id]['_error_element']);
1848          }
1849        }
1850        $node_load->{$field_id} = $form_state['values'][$field_id];
1851      }
1852    }
1853  }
1854  $node_load->log = t('Modificados los datos del actor planificador');
1855  $node_load->revision = 1;
1856  node_save($node_load);
1857  drupal_set_message(t("Se agrego la información de datos basicos"));
1858  drupal_goto('node/' . $form_values['ente_planificador_nid']);
1859}
1860
1861/*
1862 * nodo_es_ente_planificador
1863 * identifica si el nodo es ente planificador
1864 */
1865function nodo_es_ente_planificador($nid = 0) {
1866  global $user;
1867  if ((user_access('edit all planificador')) || (user_access('admin planificador')) || (user_access('edit own planificador'))) {
1868    if (is_numeric($nid)) {
1869      $ente_planificador = ente_planificador_leer_ente_planificadores($nid);
1870      if ($ente_planificador->type == "ente_planificador") {
1871        if ((user_access('edit all planificador')) || (user_access('admin planificador'))) {
1872          return TRUE;
1873        }
1874        if ((user_access('edit own planificador'))) {
1875          if (!$ente_planificador->usuarios[$user->uid]) {
1876            return FALSE;
1877          }
1878        }
1879        return TRUE;
1880      }
1881    }
1882  }
1883  return FALSE;
1884}
1885
1886/*
1887 * entes_planificadores
1888 * Listar entes planificador
1889 */
1890function entes_planificadores() {
1891  $output = '';
1892  $step = 10;
1893  $sqlcount = "SELECT count(n.nid) from {node} n, {node_revisions} rv  where n.vid = rv.vid AND (n.type in ('ente_planificador')) AND (n.status <> 0)";
1894  $sql = "SELECT n.nid as nid, n.title as title from {node} n, {node_revisions} rv  where n.vid = rv.vid AND (n.type in ('ente_planificador')) AND (n.status <> 0)";
1895  $headers_table[] = array('data' => t('Ente Planificador'), 'sort' => 'asc', 'field' => 'n.title');
1896    if ((user_access('edit all planificador'))||(user_access('admin planificador'))) {
1897      $headers_table[] = array('data' => t('Usuarios'));
1898      $headers_table[] = array('data' => t('Modificar'));
1899      $headers_table[] = array('data' => t('Datos Basicos'));
1900      $headers_table[] = array('data' => t('eliminar'));
1901  }
1902  $sql.= tablesort_sql($headers_table);
1903  $result = pager_query($sql, $step, 0, $sqlcount);
1904  while($entes = db_fetch_object($result)) {
1905    $arregloente['title'] = l($entes->title, 'node/' . $entes->nid);
1906    if ((user_access('edit all planificador')) || (user_access('admin planificador'))) {
1907      $arregloente['usuarios'] = l(t('Agregar usuarios al actor planificador'), 'admin/user/user/create/' . $entes->nid);
1908      $arregloente['editar'] = l(t('Modificar'), 'node/' . $entes->nid.'/edit', array('html' => true, 'query' => 'destination=administrar/entes_planificadores'));
1909      $arregloente['datos_basicos'] = l(t('Editar datos del actor planificador'), 'node/' . $entes->nid . '/datos_basicos', array('html' => true, 'query' => 'destination=administrar/entes_planificadores'));
1910      $arregloente['eliminar'] = l(t('Eliminar'), 'node/' . $entes->nid.'/delete', array('html' => true, 'query' => 'destination=administrar/entes_planificadores'));
1911    } 
1912    $Lista_entes[] = $arregloente;
1913    unset($arregloente);
1914  }
1915  if (sizeof($Lista_entes)) {
1916    $output.= theme('table', $headers_table, $Lista_entes);
1917    $output .= theme('pager', NULL);
1918  }
1919  else {
1920    $output.= '<p>' . t('No se encontraron entes planificadores registrados en el sistema') . '</p>';
1921  }
1922  return $output;
1923}
1924
1925/*
1926 * ente_planificador_js_util
1927 * Genera las repuestas ajax de municipios y parroquias
1928 */
1929function ente_planificador_js_util($func) {
1930  switch ($func) {
1931    case 'municipio_select':
1932      $entidad_id = intval($_POST['estado']) > 0 ? intval($_POST['estado']) : 0;
1933      if ($entidad_id<10) {
1934        $entidad_id = "0" . $entidad_id;
1935      }
1936      $title = isset($_POST['title']) ? check_plain($_POST['title']) : NULL;
1937      $display = isset($_POST['display']) ? check_plain($_POST['display']) : 'name';
1938      $select = ente_planificador_obtener_form_municipio(t('Municipio'), NULL, t('seleccione el municipio.'), $entidad_id, 'name', TRUE);
1939      $output = ahah_render($select, 'municipio');
1940      print drupal_to_js(array('data' => $output, 'status' => true));
1941      exit();
1942      break;
1943    case 'parroquia_select':
1944      $muncipio_id = intval($_POST['municipio']) > 0 ? intval($_POST['municipio']) : 0;
1945      if ($muncipio_id<1000) {
1946        $muncipio_id = "0" . $muncipio_id;
1947      }
1948      $title = isset($_POST['title']) ? check_plain($_POST['title']) : NULL;
1949      $display = isset($_POST['display']) ? check_plain($_POST['display']) : 'name';
1950      $select = ente_planificador_obtener_form_parroquia(t('Parroquia'), NULL, t('seleccione la parroquia.'), $muncipio_id, 'name', TRUE);
1951      $output = ahah_render($select, 'parroquia');
1952      print drupal_to_js(array('data' => $output, 'status' => true));
1953      exit();
1954  }
1955  print $output;
1956  exit();
1957}
1958
1959/**
1960 * ahah_render...
1961 */
1962function ahah_render($fields, $name) {
1963  $form_state = array('submitted' => FALSE);
1964  $form_build_id = $_POST['form_build_id'];
1965  // Add the new element to the stored form. Without adding the element to the
1966  // form, Drupal is not aware of this new elements existence and will not
1967  // process it. We retreive the cached form, add the element, and resave.
1968  $form = form_get_cache($form_build_id, $form_state);
1969  $form[$name] = $fields;
1970  form_set_cache($form_build_id, $form, $form_state);
1971  $form += array(
1972    '#post' => $_POST,
1973    '#programmed' => FALSE,
1974  );
1975  // Rebuild the form.
1976  $form = form_builder($_POST['form_id'], $form, $form_state);
1977  // Render the new output.
1978  $new_form = $form[$name];
1979  return drupal_render($new_form);
1980}
1981
1982/*
1983 * usuario_tiene_ente
1984 * retorna los entes que tiene un usuario
1985 */
1986function usuario_tiene_ente($uid) {
1987  $ente = db_fetch_object(db_query("SELECT n.title, n.nid FROM {node} n, {ente_user_planificador} u1  WHERE u1.usuario = %d AND u1.nid = n.nid", $uid));
1988  return $ente;
1989}
1990
1991/*
1992 * Implementation of hook_perm
1993 */
1994function ente_planificador_perm() {
1995  return array(
1996    'ver planificador',
1997    'edit own planificador',
1998    'edit all planificador',
1999    'admin planificador',
2000    'admin all planificador',
2001  );
2002}
2003
2004/*
2005 * Implementation of hook_node_info
2006 */
2007function ente_planificador_node_info() {
2008  return array(
2009    'ente_planificador' => array(
2010      'name' => t('Ente Planificador'),
2011      'description' => t('Ente Planificador'),
2012      'has_body'    => FALSE,
2013      'has_title'    => TRUE,
2014      'module'      => 'ente_planificador',
2015    ),
2016  );
2017}
2018
2019/*
2020 * Implementation of hook_node_load
2021 */
2022function ente_planificador_load($node) {
2023  $additions = db_fetch_object(db_query('SELECT * FROM {ente_planificador} WHERE nid = %d', $node->nid));
2024  //se obtienen los usuarios del ente planificador
2025  if ($additions->estado && $additions->estado < 10) {
2026    $additions->estado = '0' . $additions->estado;
2027  }
2028  if ($additions->municipio && $additions->municipio < 1000) {
2029    $additions->municipio = '0' . $additions->municipio;
2030  }
2031  if ($additions->parroquia && $additions->parroquia < 100000) {
2032    $additions->parroquia = '0' . $additions->parroquia;
2033  }
2034  $array_usuario = array();
2035  $additions1 = db_query('SELECT p.usuario, u.mail FROM {ente_user_planificador} p, {users} u WHERE nid = %d and p.usuario = u.uid', $node->nid);
2036  while ($usuarios = db_fetch_object($additions1)) {
2037    $array_usuario[$usuarios->usuario] = $usuarios->mail;
2038  }
2039  $array_actividades = array();
2040  $additions1 = db_query('SELECT actividad FROM {ente_actividad_ente} WHERE nid = %d', $node->nid);
2041  while ($actividad = db_fetch_object($additions1)) {
2042    $array_actividades[] = $actividad->actividad;
2043  }
2044  $additions->usuarios = $array_usuario;
2045  $additions->actividad = $array_actividades;
2046  return $additions;
2047}
2048
2049/*
2050 * Implementation of hook_form
2051 */
2052function ente_planificador_form(&$node, $form_state) {
2053  $form = array();
2054  $form['title'] = array(
2055    '#type' => 'textfield',
2056    '#title' => t('Nombre del ente planificador'),
2057    '#default_value' => $node->title,
2058    '#size' => 20,
2059    '#description' => t("Introduzca el nombre del ente planificador"),
2060    '#required' => TRUE,
2061  );
2062  $tipos_entes = entes_planificadores_obtiene_tipos();
2063  //SOLO DEJE A UN ENTE SER ENTE PLANIFICADOR MACRO
2064  if (db_result(db_query("SELECT nid FROM {ente_planificador} where tipo = '1'")) > 0) {
2065    unset($tipos_entes[1]);
2066  }
2067  if (!$node->nid) {
2068    $form['tipo'] = array(
2069      '#type' => 'select',
2070      '#title' => t('Tipo de rol'),
2071      '#default_value' => $node->tipo,
2072      '#options' => $tipos_entes,
2073      '#description' => t("Seleccione el tipo de rol desempeñado por el actor planificador"),
2074      '#required' => TRUE,
2075    );
2076  }
2077  return $form;
2078}
2079
2080/*
2081 * hook_form_alter
2082 */
2083function ente_planificador_form_alter(&$form, $form_state, $form_id) {
2084  if ($form_id == 'user_profile_form' && arg(2) == 'chgpwd' && user_access('administer users')) {
2085    global $user;
2086    if ($form['_account']['#value']->uid != $user->uid) {
2087      unset($form['account']['passold']);
2088
2089    }
2090  }
2091  if ($form_id == 'user_pass_reset') {
2092    $form['user_pass_reset'] = array(
2093      '#type' => 'hidden',
2094      '#value' => TRUE,
2095    );
2096  }
2097  if ($form_id == 'views_exposed_form') {
2098    $form['submit']['#value'] = t("Buscar");
2099  }
2100  if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-planificacionM-page-1') {
2101    $form['nid']['#type'] = 'select';
2102    $entes_options = obtener_ente_planificador();
2103    $entes_options[''] = t("Seleccione");
2104    $form['nid']['#options'] = $entes_options;
2105    unset($form['nid']['#size']);
2106  }
2107  if ($form['#node']->type == 'ente_planificador') {
2108    //just remove cck fields in datos basicos
2109    if ($form_id == 'ente_planificador_node_form'){
2110      if (isset($form['taxonomy'])) {
2111        $form['taxonomy']['#access'] = FALSE;
2112      }
2113      $node_type = content_types('ente_planificador');
2114      $fields = $node_type['fields'];
2115      $field_form = array();
2116      if (is_array($fields) && count($fields)) {
2117        foreach($fields as $field_id => $field) {
2118          if (variable_get('ente_planificador_' . $field_id, FALSE)) {
2119            if (isset($form[$field_id])) {
2120              $form[$field_id]['#access'] = FALSE;
2121            }
2122          }
2123        }
2124      }
2125    }
2126    unset($form['buttons']['preview']);
2127    $form['buttons']['cancel'] = array(
2128      '#type' => 'submit',
2129      '#weight'=>'8120',
2130      '#attributes' => array('onClick' => 'window.location="' . base_path() . $_GET['destination'] . '"; return false;'),
2131      '#value' => t('Cancel'),
2132    );
2133  }
2134  // Deshabilitando los campos Vision y Misión del Ente
2135  $form['field_ente_vision']['#access'] = FALSE;
2136  $form['field_ente_mision']['#access'] = FALSE;$form['field_ente_vision']['#access'] = FALSE;
2137  switch ($form_id) {
2138    case 'user_profile_form':
2139      if (arg(0) == 'user' && is_numeric(arg(1)) && arg(2) == 'edit') {
2140        $form['account']['pass']['#access'] = FALSE;
2141        $form['account']['status']['#access'] = FALSE;
2142        $form['#ente_planificador_load'] = FALSE;
2143        if (isset($form['_account']['#value']->uid) && $form['_account']['#value']->entes[0]['nid']) {
2144          $ente_planificador = ente_planificador_leer_ente_planificadores($form['_account']['#value']->entes[0]['nid']);
2145          $form['#ente_planificador_load'] = $ente_planificador;
2146          if ($ente_planificador) {
2147            if ($ente_planificador->nid) {
2148              $form['destination']['#value'] = 'node/' . $ente_planificador->nid . "/usuarios";
2149            }
2150            if ($ente_planificador) {
2151              if($ente_planificador->tipo && $ente_planificador->tipo == 2) {
2152                $variable_get = 'ActorPlanificadorMicro';
2153              }
2154              if($ente_planificador->tipo && $ente_planificador->tipo == 1) {
2155                $variable_get = 'ActorPlanificadorMacro';
2156              }
2157              if (sizeof($form['account']['roles']['#options'])) {
2158                foreach($form['account']['roles']['#options'] as $a => $b) {
2159                  if (($a != variable_get($variable_get, 2))) {
2160                    unset($form['account']['roles']['#options'][$a]);
2161                  }
2162                }
2163              }
2164            }
2165            //$form['account']['status']['#access'] = FALSE;
2166            //$form['account']['status']['#type'] = "hidden";
2167            $form['account']['notify']['#value'] = 1;
2168            $form['account']['notify']['#type'] = "hidden";
2169            $form['locale']['#type'] = "hidden";
2170            $form['locale']['language']['#type'] = "hidden";
2171            $enlace = base_path() . 'node/' . $ente_planificador->nid;
2172          }
2173        }
2174      }
2175      //eliminar la confirmación de password si el usuario olvido la contraseña
2176      if (isset($_SESSION['nuevo_password']) && $_SESSION['nuevo_password']) {
2177        $form['account']['passold']['#access'] = FALSE;
2178      }
2179      unset($form['timezone']);
2180      $form['locale']['#type'] = "hidden";
2181      $form['locale']['language']['#type'] = "hidden";
2182      $form['cancel'] = array(
2183        '#type' => 'submit',
2184        '#weight'=>'961500000',
2185        '#attributes' => array('onClick' => 'window.location="' . base_path() . $_GET['destination'] . '"; return false;'),
2186        '#value' => t('Cancel'),
2187      );
2188    break;
2189    case 'user_register':
2190        $form['account']['status']['#access'] = FALSE;
2191      if (variable_get('genpass_mode',0) == 2) {
2192        $form['account']['pass']['#type'] = 'hidden';
2193      }
2194      $ente_planificador = FALSE;       
2195      if (arg(4) && is_numeric(arg(4))) {
2196        $ente_planificador = ente_planificador_leer_ente_planificadores(arg(4));
2197      }
2198      $form['#ente_planificador_load'] = FALSE;
2199      if ($ente_planificador) {
2200        $form['#ente_planificador_load'] = $ente_planificador;
2201        if ($ente_planificador->nid) {
2202          $form['destination']['#value'] = 'node/' . $ente_planificador->nid . "/usuarios";
2203        }
2204        if ($ente_planificador) {
2205          if($ente_planificador->tipo && $ente_planificador->tipo == 2) {
2206            $variable_get = 'ActorPlanificadorMicro';
2207          }
2208          if($ente_planificador->tipo && $ente_planificador->tipo == 1) {
2209            $variable_get = 'ActorPlanificadorMacro';
2210          }
2211          if (sizeof($form['account']['roles']['#options'])) {
2212            foreach($form['account']['roles']['#options'] as $a => $b) {
2213              if (($a != variable_get($variable_get, 2))) {
2214                unset($form['account']['roles']['#options'][$a]);
2215              }
2216            }
2217            $form['account']['roles']['#default_value'] = array(variable_get($variable_get, 2));
2218          }
2219        }
2220        $form['account']['status']['#access'] = FALSE;
2221        $form['account']['status']['#type'] = "hidden";
2222        $form['account']['notify']['#value'] = 1;
2223        $form['account']['notify']['#type'] = "hidden";
2224        $form['locale']['#type'] = "hidden";
2225        $form['locale']['language']['#type'] = "hidden";
2226        $enlace = base_path() . 'node/' . $ente_planificador->nid;
2227        if (isset($form['account']) && is_array($form['account']) && !$form_state['post']) {
2228          if (trim($form['account']['name']['#value']) == "") {
2229            $regex = '#[^()]*\((([^()]+|(?R))*)\)[^()]*#';
2230            $replacement = '\1';
2231            $texto_aux = preg_replace($regex, $replacement, $ente_planificador->title);
2232            if (!$texto_aux) {
2233              $texto_aux = 'ente' . $ente_planificador->nid;
2234            }
2235            $sqlcount = db_query("select count(u.uid) as cantidad from {users} u");
2236            $ente = db_fetch_object($sqlcount);
2237            $ente->cantidad++;
2238            $texto_aux.=$ente->cantidad;
2239            $form['account']['name']['#value'] = $texto_aux;
2240          }
2241        }
2242      }
2243      else {
2244        $enlace = base_path() . 'administrar/entes_planificadores';
2245      }
2246      $form['cancel'] = array(
2247        '#type' => 'submit',
2248        '#weight'=>'8615',
2249        '#attributes' => array('onClick' => 'window.location="' . $enlace . '"; return false;'),
2250        '#value' => t('Cancel'),
2251      );
2252    break;
2253  }
2254}
2255
2256/*
2257 * ente_planificador_form_cancel
2258 * Redireccionar al momento de cancelar
2259 */
2260function ente_planificador_form_cancel(){
2261  drupal_goto(‘destinationpage’);
2262}
2263
2264/**
2265 * ente_planificador_obtener_form_municipio...
2266 * Retorna el select de municipios...
2267 */
2268function ente_planificador_obtener_form_municipio($title = NULL, $default = NULL, $description = NULL, $entidad_id = "", $display = 'name', $required = FALSE) {
2269  $municipios = ente_planificador_obtener_lista_municipio($entidad_id);
2270  $disabled = FALSE;
2271  if (count($municipios) == 1) {
2272    $municipios = array(-1 => t('Not applicable'));
2273  }
2274  return array(
2275    '#type' => 'select',
2276    '#title' => $title,
2277    '#default_value' => $default,
2278    '#options' => $municipios,
2279    '#description' => $description,
2280    '#required' => $required,
2281    '#disabled' => isset($municipios[-1]) ? TRUE : FALSE,
2282    '#suffix' => '<span class="municipio-throbber"></span>',
2283    '#ahah' => array(
2284      'event' => 'change',
2285      'path' => 'ente_planificador_js_util/parroquia_select',
2286      'wrapper' => 'edit-parroquia-wrapper',
2287      'method' => 'replace',
2288      'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
2289    ),
2290  );
2291}
2292
2293/**
2294 * ente_planificador_obtener_form_parroquia...
2295 * Retorna el select de parroquias...
2296 */
2297function ente_planificador_obtener_form_parroquia($title = NULL, $default = NULL, $description = NULL, $municipio_id = "", $display = 'name', $required = FALSE) {
2298  $parroquias = ente_planificador_obtener_lista_parroquia($municipio_id);
2299  $disabled = FALSE;
2300  if (count($parroquias) == 1) {
2301    $parroquias = array(-1 => t('Not applicable'));
2302  }
2303  return array(
2304    '#type' => 'select',
2305    '#title' => $title,
2306    '#default_value' => $default,
2307    '#options' => $parroquias,
2308    '#description' => $description,
2309    '#required' => $required,
2310    '#disabled' => isset($parroquias[-1]) ? TRUE : FALSE,
2311    '#suffix' => '<span class="parroquia-throbber"></span>',
2312  );
2313}
2314
2315/**
2316 * ente_planificador_obtener_lista_parroquia...
2317 * Retorna una lista de parroquias...
2318 */
2319function ente_planificador_obtener_lista_parroquia($municipio = 0) {
2320  $parroquias = array('0' => "Seleccione");
2321  if ($municipio) {
2322    $municipioL = ente_planificador_obtener_municipio($municipio);
2323    if ($municipioL->codigo) {
2324      $resul_act = db_query("SELECT codigo, nombre FROM {parroquia} where municipio = '%s'", $municipioL->codigo);
2325      while ($parroquia = db_fetch_object($resul_act)) {
2326        $parroquias[$parroquia->codigo] = $parroquia->nombre;
2327      }
2328      if ($parroquias) {
2329        return $parroquias;
2330      }
2331    }
2332  }
2333  return $parroquias;
2334}
2335
2336/**
2337 * ente_planificador_obtener_municipio...
2338 * Retorna un municipio...
2339 */
2340function ente_planificador_obtener_municipio($municipio = 0) {
2341  if ($municipio) {
2342    $resul_act = db_query("SELECT codigo, nombre FROM {municipio} where codigo = '%s'", $municipio);
2343    $municipio = db_fetch_object($resul_act);
2344  }
2345  return $municipio;
2346}
2347
2348/**
2349 * ente_planificador_obtener_parroquia...
2350 * Retorna un parroquia...
2351 */
2352function ente_planificador_obtener_parroquia($parroquia = 0) {
2353  if ($parroquia) {
2354    $resul_act = db_query("SELECT codigo, nombre FROM {parroquia} where codigo = '%s'", $parroquia);
2355    $parroquia = db_fetch_object($resul_act);
2356  }
2357  return $parroquia;
2358}
2359
2360/**
2361 * ente_planificador_obtener_entidad...
2362 * Retorna una entidad...
2363 */
2364function ente_planificador_obtener_entidad($entidad = "") {
2365  $entidadL = NULL;
2366  if ($entidad) {
2367    $resul_act = db_query("SELECT codigo, nombre FROM {entidad} where codigo = '%s'", $entidad);
2368    $entidadL = db_fetch_object($resul_act);
2369  }
2370  return $entidadL;
2371}
2372
2373/**
2374 * ente_planificador_obtener_lista_municipio...
2375 * Retorna una lista de muncipios...
2376 */
2377function ente_planificador_obtener_lista_municipio($entidad = "") {
2378  $municipios = array(0 => "Seleccione");
2379  if ($entidad) {
2380    $entidadL = ente_planificador_obtener_entidad($entidad);
2381    if ($entidadL->codigo) {
2382      $resul_act = db_query("SELECT codigo, nombre FROM {municipio} where entidad = '%s'", $entidad);
2383      while ($municipio = db_fetch_object($resul_act)) {
2384        $municipios[$municipio->codigo] = $municipio->nombre;
2385      }
2386      if ($municipios) {
2387        return $municipios;
2388      }
2389    }
2390  }
2391  return $municipios;
2392}
2393
2394/**
2395 * ente_planificador_obtener_lista_entidad...
2396 * Retorna una lista de entidades...
2397 */
2398function ente_planificador_obtener_lista_entidad() {
2399  $resul_act = db_query('SELECT codigo, nombre FROM {entidad}');
2400  while ($entidad = db_fetch_object($resul_act)) {
2401    $entidades[$entidad->codigo] = $entidad->nombre;
2402  }
2403  return $entidades;
2404}
2405
2406/**
2407 * ente_planificador_obtener_actividades...
2408 * Retorna una lista de actividades...
2409 */
2410function ente_planificador_obtener_actividades() {
2411  $actividades = array();
2412  $resul_act = db_query('SELECT id_actividad, nombre FROM {ente_actividad} ORDER BY nombre');
2413  while ($actividad = db_fetch_object($resul_act)) {
2414    $actividades[$actividad->id_actividad] = $actividad->nombre;
2415  }
2416  return $actividades;
2417}
2418
2419/**
2420 * ente_planificador_obtener_municipio...
2421 * Retorna un municipio...
2422 */
2423function ente_planificador_obtener_actividad($actividad = 0) {
2424  if ($actividad) {
2425    $resul_act = db_query("SELECT nombre FROM {ente_actividad} where id_actividad = '%s'", $actividad);
2426    $actividad = db_fetch_object($resul_act);
2427  }
2428  return $actividad->nombre;
2429}
2430
2431/*
2432 * Implementation of hook_insert
2433 */
2434function ente_planificador_insert($node) {
2435  //$node->tipo = !isset($node->tipo) ? 2 : $node->tipo;
2436  if ($node->tipo) {
2437    db_query("INSERT INTO {ente_planificador} (nid, tipo) VALUES (%d, %d)", $node->nid, $node->tipo);
2438    $update = array();
2439    $inputs = array();
2440    if (isset($node->razon_social) && trim($node->razon_social) != '') {
2441      $update[] = "razon_social = '%s'";
2442      $inputs[] = check_plain(trim($node->razon_social));
2443    }
2444    if (isset($node->rif) && trim($node->rif) != '' && preg_match("/^(V|E|P|J|G){1}-([0-9]){8}-([0-9]){1}$/",$node->rif) && preg_match("/^(V|E){1}-([0-9]){8}$/",$node->rif)) {
2445      $update[] = "rif = '%s'";
2446      $inputs[] = check_plain(trim($node->rif));
2447    }
2448    if (isset($node->direccion) && trim($node->direccion)) {
2449      $update[] = "direccion = '%s'";
2450      $inputs[] = check_plain(trim($node->direccion));
2451    }
2452    if (isset($node->ciudad) && trim($node->ciudad) != '') {
2453      $update[] = "ciudad = '%s'";
2454      $inputs[] = check_plain(trim($node->ciudad));
2455    }
2456    if (isset($node->estado) && $node->estado) {
2457      $update[] = "estado = %d";
2458      $inputs[] = $node->estado;
2459    }
2460    if (isset($node->municipio) && $node->municipio) {
2461      $update[] = "municipio = %d";
2462      $inputs[] = $node->municipio;
2463    }
2464    if (isset($node->parroquia) && $node->parroquia) {
2465      $update[] = "parroquia = %d";
2466      $inputs[] = $node->parroquia;
2467    }
2468    if (count($update)) {
2469      $inputs[] = $node->nid;
2470      $result = db_query("update {ente_planificador} set " . implode(', ', $update) . " where nid = %d", $inputs);
2471    }
2472  }
2473}
2474
2475/*
2476 * Implementation of hook_update
2477 */
2478function ente_planificador_update($node) {
2479  if ($node->nid && $node->tipo) {
2480    db_query("UPDATE {ente_planificador} SET tipo = %d WHERE nid = %d", $node->tipo, $node->nid);
2481  }
2482}
2483
2484/*
2485 * Implementation of hook_delete
2486 */
2487function ente_planificador_delete($node) {
2488  // Notice that we're matching all revision, by using the node's nid.
2489  if ($node->nid) {
2490    db_query('DELETE FROM {ente_planificador} WHERE nid = %d', $node->nid);
2491    db_query('DELETE FROM {ente_actividad_ente} WHERE nid = %d', $node->nid);
2492  }
2493}
2494
2495/*
2496 * Implementation of hook_view
2497 */
2498function ente_planificador_view($node,$teaser,$page) {
2499  $node = node_prepare($node, $teaser);
2500  $node->content['title1'] = array(
2501    '#prefix'=>'<p align="center"><b>',
2502    '#value' => "<b>" . t('Nombre del ente planificador:') . "</b> " . check_plain($node->title) . "<br>",
2503    '#weight' => -2,
2504    '#suffix'=>'</b></p>',
2505  );
2506  $node->content['tipo'] = array(
2507    '#value' => "<p><b>" . t('Tipo de Actor Planificador:') . "</b> " . entes_planificadores_obtiene_tipos($node->tipo) . "</b></p>",
2508    '#weight' => -1,
2509  );
2510  //Se añade la estadistica vista al nodo
2511  $fecha = time();
2512  if ($node->razon_social) {
2513    $node->content['Razon_social'] = array(
2514      '#value' => "<b>" . t('Razón Social:') . "</b> " . check_plain($node->razon_social) . "<br>",
2515      '#weight' => 0,
2516    );
2517  }
2518  if ($node->razon_rif) {
2519    $node->content['RIF'] = array(
2520      '#value' => "<b>" . t('RIF:') . "</b> " . check_plain($node->rif) . "<br>",
2521      '#weight' => 1,
2522    );
2523  }
2524  if ($node->direccion) {
2525    $node->content['direccion'] = array(
2526      '#value' => "<b>" . t('Dirección:') . "</b> " . check_plain($node->direccion) . "<br>",
2527      '#weight' => 2,
2528    );
2529  }
2530  if ($node->ciudad) {
2531    $node->content['ciudad'] = array(
2532      '#value' => "<b>" . t('Ciudad:') . "</b> " . check_plain($node->ciudad) . "<br>",
2533      '#weight' => 6,
2534    );
2535  }
2536  if ($node->estado) {
2537    $estado = ente_planificador_obtener_entidad($node->estado);
2538    $node->content['estado'] = array(
2539      '#prefix'=>'<p align="center"><b>' . t('Domicilio Fiscal') . '</b></p>',
2540      '#value' => "<b>" . t('Estado:') . "</b> " . $estado->nombre . "<br>",
2541      '#weight' => 3,
2542    );
2543  }
2544  if ($node->municipio) {
2545    $municipio = ente_planificador_obtener_municipio($node->municipio);
2546    $node->content['municipio'] = array(
2547      '#value' => "<b>" . t('Municipio:') . "</b> " . $municipio->nombre . "<br>",
2548      '#weight' => 4,
2549    );
2550  }
2551  if ($node->parroquia) {
2552    $parroquia = ente_planificador_obtener_parroquia($node->parroquia);
2553    $node->content['parroquia'] = array(
2554      '#value' => "<b>" . t('Parroquia:') . "</b> " . $parroquia->nombre . "<br>",
2555      '#weight' => 5,
2556    );
2557  }
2558  $actividad = $node->actividad;
2559  for($i=0;$i<sizeof($actividad);$i++) {
2560    $actividad[$i] = ente_planificador_obtener_actividad($actividad[$i]);
2561  }
2562  if (sizeof($actividad)) {
2563    $actidades = count($actividad) > 1 ? implode(' , ', $actividad) . '': $actividad[0];
2564  }
2565  else {
2566    $actidades = t("No seleccionada");
2567  }
2568  $node->content['actividad'] = array(
2569    '#prefix'=>'<p align="center"><b>' . t('Actividades del Ente') . '</b></p>',
2570    '#value' => "<b>" . t('Actividad:') . "</b> ( " . $actidades . " )<br>",
2571    '#weight' => 6,
2572  );
2573  return $node;
2574}
2575
2576/*
2577 * Implementation of hook_access
2578 */
2579function ente_planificador_access($op, $node, $account) {
2580  if ($op == 'view') {
2581    return user_access('ver planificador');
2582  }
2583  if ($op == 'create') {
2584    return ((user_access('edit all planificador'))||(user_access('admin planificador')));
2585  }
2586  if ($op == 'update') {
2587    if (user_access('edit all planificador') ||user_access('admin planificador') || (user_access('edit own planificador') && ($account->uid == $node->usuarios[$account->uid]))) {
2588      return TRUE;
2589    }
2590  }
2591  if ($op == 'delete') {
2592    return ((user_access('edit all planificador'))||(user_access('admin planificador')));
2593  }
2594}
2595
2596/*
2597 * obtener_ente_planificador
2598 * retorna una lista de entes planificadores publicados
2599*/
2600function obtener_ente_planificador() {
2601  $resultado = db_query("select nid, title from {node} where type='ente_planificador' and status = 1");
2602  while ($ente = db_fetch_object($resultado)) {
2603    $entes[$ente->nid] = $ente->title;
2604  }
2605  if (!sizeof($entes)) {
2606    $entes = array(0 => "Seleccione");
2607  }
2608  return $entes;
2609}
2610
2611/*
2612 * obtener_mis_ente_planificador
2613 * retorna una lista de mis entes planificadores publicados
2614*/
2615function obtener_mis_ente_planificador($uid = 0) {
2616  if ($uid) {
2617    $resultado = db_query("select n.nid, n.title, p.rif,p.direccion from {node} n,{ente_user_planificador} u, {ente_planificador} p  where u.usuario = %d and u.nid = n.nid and n.type='ente_planificador' and u.nid = p.nid and n.status = 1", $uid);
2618    while ($ente = db_fetch_object($resultado)) {
2619      $entes[] = array('title' => $ente->title, 'nid' => $ente->nid, 'rif' => $ente->rif, 'direccion' => $ente->direccion);
2620    }
2621  }
2622  return $entes;
2623}
2624
2625/*
2626 * Implementation of hook_user
2627 */
2628function ente_planificador_user($op, &$edit, &$user, $category = NULL) {
2629  switch ($op) {
2630    case 'login':
2631    $_REQUEST['destination'] = 'principal';
2632    if (isset($edit['nuevo_password']) && $edit['nuevo_password']) {
2633      $_SESSION['nuevo_password'] = TRUE;
2634    }
2635    break;
2636    case 'load':
2637      $entes = obtener_mis_ente_planificador($user->uid);
2638      $user->entes = $entes;
2639    break;
2640    case 'validate':
2641      if(array_key_exists('passold', $edit)) {
2642        if($user->pass!=md5($edit['passold'])) {
2643          form_set_error('passold', t('La contraseña actual no coincide con la suministrada.'));
2644        }
2645      }
2646      if($edit['submit'] != t('Change Password') && array_key_exists('cedula', $edit) && !array_key_exists('passold', $edit)) {
2647        if(!preg_match("/^(V|E){1}([0-9]){8}$/",$edit['cedula'])) {
2648          form_set_error('cedula', t('La cédula de identidad debe tener el formato V00000000 sin puntos.'));
2649        }
2650      }
2651    break;
2652    case 'view':
2653      $entes = array();
2654        $contenido = '<p align="justify"><b>' . t("Correo Electrónico") . ':</b> ' . $user->mail . '</p>';
2655      if ($user->nombres) {
2656        $contenido = '<p align="justify"><b>' . t("Nombres") . ':</b> ' . $user->nombres . '</p>';
2657      }
2658      if ($user->apellidos) {
2659        $contenido .= '<p align="justify"><b>' . t("Apellidos") . ':</b> ' . $user->apellidos . '</p>';
2660      }
2661      if ($user->cedula) {
2662        $contenido .= '<p align="justify"><b>' . t("Cédula de Identidad") . ':</b> ' . $user->cedula . '</p>';
2663      }
2664      $header = array(
2665        array('data' => t('Ente Planificador')),
2666        array('data' => t('RIF')),
2667        array('data' => t('Dirección')),
2668      );
2669      for ($i=0;$i<sizeof($user->entes);$i++) {
2670        $entes[]= array(l($user->entes[$i]['title'], 'node/' . $user->entes[$i]['nid']), $user->entes[$i]['rif'], $user->entes[$i]['direccion']);
2671      }
2672      if (sizeof($entes)>0) {
2673        $contenido .= theme('table', $header, $entes);
2674      }
2675      $user->content['user_picture']=array('user_picture' => array ('#value' =>$contenido, '#weight' => -10 ));
2676    break;
2677    case 'insert':
2678      if(array_key_exists('entes', $edit) && $edit['entes']) {
2679        $rolenames = user_roles();
2680        $ente_planificador = ente_planificador_leer_ente_planificadores($edit['entes']);
2681        if ($ente_planificador->tipo) {
2682          if($ente_planificador->tipo && $ente_planificador->tipo == 2) {
2683            $variable_get = 'ActorPlanificadorMicro';
2684          }
2685          if($ente_planificador->tipo && $ente_planificador->tipo == 1) {
2686            $variable_get = 'ActorPlanificadorMacro';
2687          }
2688          $edit['roles'][2] = $rolenames[2];
2689          if ($rolenames[variable_get($variable_get, 2)]) {
2690            //$edit['roles'][variable_get($variable_get, 2)] = $rolenames[variable_get($variable_get, 2)];
2691          }
2692          db_query("delete from {ente_user_planificador} where usuario = %d",$edit['uid']);
2693          $result = db_query("insert into {ente_user_planificador} (nid, usuario) values (%d,%d)", $edit['entes'], $edit['uid']);
2694        }
2695      }
2696    break;
2697    case 'update':
2698
2699      if(array_key_exists('entes', $edit) && $edit['entes']) {
2700        db_query("delete from {ente_user_planificador} where usuario = %d", $user->uid);
2701        $result = db_query("insert into {ente_user_planificador} (nid, usuario) values (%d,%d)", $edit['entes'], $user->uid);
2702      }
2703      $result = db_query("update {users} set nombres = '%s', apellidos = '%s', cedula = '%s' where uid = %d", $edit['nombres'], $edit['apellidos'], $edit['cedula'], $user->uid);
2704    break;
2705    case 'form':
2706      // CHECK THAT USER UPDATE NO ANONYMOUS
2707      if ($user->uid > 0) {
2708        $form['usuario_planificacion']= array(
2709          '#type' => 'fieldset',
2710          '#title' => t("Datos del usuario"),
2711        );
2712/*
2713        if (user_access('admin all planificador')) {
2714          $entes = obtener_ente_planificador();
2715          if (user_access('administer users')) {
2716            $entes[0] = t('No asignar ente');
2717          }
2718          $default_entes = $user->entes[0]['nid'] ? $user->entes[0]['nid'] : 0;
2719          $form['usuario_planificacion']['entes'] = array(
2720            '#type' => 'select',
2721            '#title' => t('Entes'),
2722            '#default_value' => $default_entes,
2723            '#options' => $entes,
2724            '#weight' => 3,
2725          );
2726        }
2727*/
2728        $form['usuario_planificacion']['nombres'] = array(
2729          '#type' => 'textfield',
2730          '#title' => t('Nombres'),
2731          '#default_value' => $user->nombres,
2732          '#size' => 60,
2733          '#maxlength' => 244,
2734          '#description' => t('Introduzca los nombres del actor'),
2735          '#required'       => TRUE,
2736          '#weight' => 4,
2737        );
2738        $form['usuario_planificacion']['apellidos'] = array(
2739          '#type' => 'textfield',
2740          '#title' => t('Apellidos'),
2741          '#default_value' => $user->apellidos,
2742          '#size' => 60,
2743          '#maxlength' => 244,
2744          '#description' => t('Introduzca los apellidos del actor'),
2745          '#required'       => TRUE,
2746          '#weight' => 5,
2747        );
2748        $form['usuario_planificacion']['cedula'] = array(
2749          '#type' => 'textfield',
2750          '#title' => t('Cédula de Identidad'),
2751          '#default_value' => $user->cedula,
2752          '#size' => 60,
2753          '#maxlength' => 244,
2754          '#description' => t('Introduzca la Cédula de Identidad'),
2755          '#required'       => TRUE,
2756          '#weight' => 6,
2757        );
2758        return $form;
2759      }
2760    break;
2761    case 'register':
2762      // CHECK THAT USER UPDATE NO ANONYMOUS
2763      // DISPLAY ELEMENT FORM TO SELECT TO USE INTRANET
2764      if (user_access('admin planificador')) {
2765        $ente_planificador = object;
2766        if (arg(4) && is_numeric(arg(4))) {
2767          $ente_planificador = ente_planificador_leer_ente_planificadores(arg(4));
2768        }
2769        if ($ente_planificador->nid) {
2770          $form['actor_planificacion']['entes'] = array(
2771            '#type' => 'hidden',
2772            '#default_value' => $ente_planificador->nid,
2773          );
2774        }
2775/*
2776      else {
2777        $entes = obtener_ente_planificador();
2778        if (user_access('administer users')) {
2779          $entes[0] = t('No asignar ente');
2780        }
2781        $form['entes'] = array(
2782          '#type' => 'select',
2783          '#title' => t('Entes'),
2784          '#default_value' => 0,
2785          '#options' => $entes,
2786        );
2787      }
2788*/
2789    }
2790    return $form;
2791    break;
2792  }
2793}
2794
2795/*
2796 * Implementation of entes_planificadores_planificacion()
2797 */
2798function entes_planificadores_planificacion($planificador = 0) {
2799  drupal_goto('planificacion/' . $planificador);
2800}
2801
2802/*
2803 * entes_planificadores_usuarios
2804 * Mostrar usuarios de un ente planificador
2805 */
2806function entes_planificadores_usuarios($planificador = 0) {
2807  $ente_planificador = ente_planificador_leer_ente_planificadores($planificador);
2808  $output = '';
2809  $step = 10;
2810  if ($ente_planificador->nid && $ente_planificador->type == 'ente_planificador') {
2811    $sqlcount = "SELECT count(u.uid) FROM {users} u, {ente_user_planificador} u1  WHERE u1.usuario = %d AND u1.uid = u.uid";
2812    $sql = "SELECT u.uid, u.name, u.nombres, u.apellidos, u.cedula, u.mail FROM {users} u, {ente_user_planificador} u1  WHERE u1.nid = %d AND u1.usuario = u.uid";
2813    $headers_table[] = array(
2814      'data' => t('Nombre de usuario'),
2815      'sort' => 'asc',
2816      'field' => 'u.name'
2817    );
2818    $headers_table[] = array(
2819      'data' => t('Nombres'),
2820      'field' => 'u.nombres'
2821    );
2822    $headers_table[] = array(
2823      'data' => t('Apellidos') ,
2824      'field' => 'u.apellidos'
2825    );
2826    $headers_table[] = array(
2827      'data' => t('Cédula de Identidad'),
2828      'field' => 'u.cedula'
2829    );
2830    $headers_table[] = array(
2831      'data' => t('Correo electrónico'),
2832      'field' => 'u.mail'
2833    );
2834    $sql.= tablesort_sql($headers_table);
2835    $result = pager_query($sql, $step, 0, $sqlcount, $ente_planificador->nid);
2836    while($usuario = db_fetch_object($result)) {
2837      if (trim($usuario->nombres) == "") {
2838        $usuario->nombres = "N/A";
2839      }
2840      if (trim($usuario->apellidos) == "") {
2841        $usuario->apellidos = "N/A";
2842      }
2843      if (trim($usuario->cedula) == "") {
2844        $usuario->cedula = "N/A";
2845      }
2846      $Lista_usuarios[] = array(
2847        'usuario'=>l($usuario->name, 'user/' . $usuario->uid),
2848        'nombres' => $usuario->nombres,
2849        'apellidos' => $usuario->pellidos,
2850        'cedula' => $usuario->cedula,
2851        'mail' => $usuario->mail
2852      );
2853    }
2854    if (sizeof($Lista_usuarios)) {
2855      $output.= theme('table', $headers_table, $Lista_usuarios);
2856      $output .= theme('pager', NULL);
2857    }
2858    else {
2859      $output .= '<p>' . t('No se encontraron usuarios asignados en el planificadores registrados en el sistema') . '</p>';
2860    }
2861    if ((user_access('edit all planificador'))||(user_access('admin planificador'))) {
2862      $output .= '<p>' . l(t('Agregar usuarios al actor planificador'), 'admin/user/user/create/' . $ente_planificador->nid) . "</p>";
2863    }
2864    return $output;
2865  }
2866  else {
2867    drupal_set_message(t("Ente planificador no encontrado"));
2868    drupal_goto('entes_planificadores'); 
2869  }
2870}
2871
2872/**
2873 * Implementation of hook_views_api().
2874 */
2875function ente_planificador_views_api() {
2876  return array(
2877    'api' => '2.0',
2878    'path' => drupal_get_path('module', 'ente_planificador') . '/views',
2879  );
2880}
2881
2882/*
2883 * planificacion_submenu_interfaz
2884 * Generar el menu de explicación situacional
2885 */
2886function ente_planificador_status_planificacion($nid, $tipo = 2) {
2887  $procesos_status = array();
2888  $orden = array();
2889  if (is_numeric($nid)) {
2890    $ente_planificador = ente_planificador_leer_ente_planificadores($nid);
2891    if ($ente_planificador->type == "ente_planificador") {
2892      $procesos = ente_planificador_procesos('status');
2893      $procesos_ordenados = ente_planificador_ordena_procesos($procesos, array());
2894      $procesos = $procesos_ordenados['status'];
2895      if (count($procesos)) {
2896        foreach($procesos as $id => $proceso) {
2897          $proceso_status = array();
2898          foreach (module_list() as $module) {
2899            if ($data = module_invoke($module, 'status_planificacion_' . $id, $nid, $tipo)) {
2900              $proceso_status = array_merge_recursive($data, $proceso_status);
2901            }
2902          }
2903          $procesos_status[$id]['value'] = $proceso_status;
2904          $procesos_status[$id]['title'] = $proceso['title'];
2905        }
2906      }
2907    }
2908  }
2909  foreach($procesos_status as $id => $arreglo) {
2910    $indices = array();
2911    foreach($arreglo['value'] as $ids => $valor) {
2912      $weight = isset($valor['weight']) ? $valor['weight'] : 0;
2913      $indices[$weight][] = $ids;
2914    }
2915    ksort($indices);
2916    $reemplazo = array();
2917    foreach($indices as $ids => $valores) {
2918      foreach($valores as $valor) {
2919
2920        $reemplazo[$valor] = $procesos_status[$id]['value'][$valor];
2921      }
2922    }
2923    unset($procesos_status[$id]['value']);
2924    $procesos_status[$id]['value'] = $reemplazo;
2925  }
2926  return $procesos_status;
2927}
2928
2929/*
2930 * planificacion_submenu_interfaz
2931 * Generar el menu de explicación situacional
2932 */
2933function planificacion_submenu_interfaz() {
2934  $submenu = array();
2935  $smenu = array();
2936  $i = 0;
2937  $submenu[$i] = array(
2938    'name'=> t("Explicación situacional"),
2939    'description' => t("Explicación situacional"),
2940    'call' => "explicacion_situacional"
2941  );
2942  $aux_menu = array();
2943  foreach (module_list() as $module) {
2944    if ($data = module_invoke($module, 'items_menu_planificacion_' . $submenu[$i]['call'])) {
2945      $aux_menu = array_merge_recursive($data, $aux_menu);
2946    }
2947  }
2948  $smenu[$i] = $aux_menu;
2949  $i++;
2950  unset($aux_menu);
2951  // LOAD THE REST OF MENUS
2952  foreach (module_list() as $module) {
2953    if ($data = module_invoke($module, 'menu_planificacion', $valores)) {
2954      $submenu[$i] = $data;
2955      $aux_menu = array();
2956      foreach (module_list() as $module) {
2957        if ($data1 = module_invoke($module, 'items_menu_planificacion_' . $submenu[$i]['call'])) {
2958          $aux_menu = array_merge_recursive($data1, $aux_menu);
2959        }
2960      }
2961    $i++;
2962    unset($aux_menu);
2963    }
2964  }
2965  return theme('planificacion_submenu_interfaz', $submenu, $smenu);
2966}
2967
2968/*
2969 * ente_planificador_theme
2970 * Theme de la funcion de ente planificacion
2971 */
2972function ente_planificador_theme() {
2973  $theme['planificacion_submenu_interfaz']= array('arguments' => array($menuD => array(), $smenuD => array()));
2974  return $theme;
2975}
2976
2977/*
2978 * theme_planificacion_submenu_interfaz
2979 * Plantilla de ente planificacion
2980 */
2981function theme_planificacion_submenu_interfaz($menuD, $smenuD) {
2982  $output = '';
2983  if (sizeof($menuD) > 0) {
2984    $output .='<div class="admin clear-block"><div class="clear-block">';
2985    for ($i=0;$i<sizeof($menuD);$i++) {
2986      if (($menuD[$i]['name']) && ($menuD[$i]['description'])) {
2987        $output .= '<div class="admin-panel">';
2988        $output .= '<h3>';
2989        $output .= $menuD[$i]['name'];
2990        $output .= '</h3>';
2991        $output .= '<div class="body">';
2992        $output .= '<p class="description">';
2993        $output .= $menuD[$i]['description'];
2994        $output .= '</p>';
2995        $output .= '<dl class="admin-list">';
2996        for ($j = 0; $j < sizeof($smenuD[$i]); $j++) {
2997          if (($smenuD[$i][$j]['name']) && ($smenuD[$i][$j]['path']) && ($smenuD[$i][$j]['description'])) {
2998            $output .= '<dt>' . l($smenuD[$i][$j]['name'], $smenuD[$i][$j]['path']) . '</a></dt><dd>' . $smenuD[$i][$j]['description'] . '</dd>';
2999          }
3000        }
3001        $output .= '</dl>';
3002        $output .= '</div></div>';
3003      }
3004    }
3005    $output .= '</div></div>';
3006  }
3007  return $output;
3008}
3009
3010/*
3011 * access_ente_planificador
3012 * Verifica si el usuario tiene acceso al ente planificador
3013 */
3014function access_ente_planificador($type_url_str = "", $user = object) {
3015  global $user;
3016  if ($user->uid != 1 && !sizeof($user->entes)) {
3017    return FALSE;
3018  }
3019  if ($user->uid !=1) {
3020    $ente_planificador = ente_planificador_leer_ente_planificadores($user->entes);
3021    $type_url_str1 = $type_url_str;
3022    $type_url_str = str_replace('_', '-', $type_url_str);
3023    $fecha_tipo[1]['FI'] = "FIPMA";
3024    $fecha_tipo[1]['FF'] = "FFPMA";
3025    $fecha_tipo[2]['FI'] = "FIPMI";
3026    $fecha_tipo[2]['FF'] = "FFPMI";
3027    $validFI = variable_get('ente_planificador_' . $type_url_str . $fecha_tipo[$ente_planificador->tipo]['FI'], 0);
3028    $validFF = variable_get('ente_planificador_' . $type_url_str . $fecha_tipo[$ente_planificador->tipo]['FF'], 0);
3029    $current_time = time();
3030    if ($validFI && $current_time < $validFI) {
3031      return FALSE;
3032    }
3033    elseif ($validFF && $current_time > $validFF + 86399) {
3034      return FALSE;
3035    }
3036    else {
3037       return TRUE;
3038    }
3039  }
3040  return TRUE;
3041}
3042
3043/*
3044 * muestra_mensaje
3045 * Desplegar mensaje al usuario de acuerdo al tiempo de planificacion
3046 */
3047function muestra_mensaje($type_url_str = "", $ente_planficador = 0, $expire = 1, $mensaje = '') {
3048  $mi_fecha = ente_planificador_user_acceso_proceso($type_url_str, $ente_planficador);
3049  $procesos = ente_planificador_procesos();
3050  $tipos = entes_planificadores_obtiene_tipos();
3051  $tipo = is_numeric($ente_planficador) ? $ente_planficador: $ente_planficador->tipo;
3052  $new_mensaje = '';
3053  if (!$mensaje) {
3054    if ($expire) {
3055      $new_mensaje = t($procesos[$type_url_str]['message_expire'], array('%tipo_ente' => $tipos[$tipo], '%fecha' => format_date($mi_fecha[0]), '%fecha1' => format_date($mi_fecha[1] + 86399)));
3056     
3057    }
3058    else {
3059      $new_mensaje = t($procesos[$type_url_str]['message'], array('%tipo_ente' => $tipos[$tipo], '%fecha' => format_date($mi_fecha[0]), '%fecha1' => format_date($mi_fecha[1] + 86399)));
3060
3061    }
3062  }
3063  else {
3064    $new_mensaje = $mensaje;
3065  }
3066  $conf = array(
3067    'plan_tipo' => $type_url_str,
3068    'ente_planificador' => $ente_planficador,
3069    'expire' => $expire,
3070    'mensaje' => $mensaje,
3071  );
3072  drupal_alter('ente_planificador_muestra_mensaje', $new_mensaje, $conf);
3073  drupal_set_message($new_mensaje, 'status', FALSE);
3074}
3075
3076/*
3077function muestra_mensaje($type_url_str = "", $ente_tipo = 0, $expire = 1) {
3078  $mi_fecha = ente_planificador_user_acceso_proceso($type_url_str, $ente_tipo);
3079  $procesos = ente_planificador_procesos();
3080  $tipos = entes_planificadores_obtiene_tipos();
3081  if ($expire) {
3082    drupal_set_message(
3083      t($procesos[$type_url_str]['message_expire'],
3084        array(
3085          '%tipo_ente' => $tipos[$ente_tipo],
3086          '%fecha' => format_date($mi_fecha[0]),
3087          '%fecha1' => format_date($mi_fecha[1] + 86399)
3088        )
3089      )
3090    );
3091  }
3092  else {
3093    drupal_set_message(
3094      t($procesos[$type_url_str]['message'],
3095        array(
3096          '%tipo_ente' => $tipos[$ente_tipo],
3097          '%fecha' => format_date($mi_fecha[0]),
3098          '%fecha1' => format_date($mi_fecha[1] + 86399)
3099        )
3100      )
3101    );
3102  }
3103}
3104*/
3105/*
3106 * ente_planificador_user_acceso_proceso
3107 * Devuelve la fechas permitidas para un proceso de planificacion
3108 */
3109
3110function ente_planificador_user_acceso_proceso($proceso = '', $ente_planificador = 0) {
3111  $fechas = array();
3112  $etapas = array('from', 'until');
3113  if ($proceso) {
3114    foreach ($etapas as $etapa) {
3115      $fechas[] = variable_get('ente_planificador_' . $proceso . '_' . $etapa, 0);
3116    }
3117  }
3118  $conf = array(
3119    'proceso' => $proceso,
3120    'ente_planificador' => $ente_planificador,
3121  );
3122  drupal_alter('ente_planificador_proceso_user_acceso', $fechas, $conf);
3123  return $fechas;
3124}
3125
3126/*
3127function ente_planificador_user_acceso_proceso($proceso = '', $tipo) {
3128  $fechas = array();
3129  $etapas = array('from', 'until');
3130  if ($proceso) {
3131    foreach ($etapas as $etapa) {
3132      $fechas[] = variable_get('ente_planificador_' . $proceso . '_' . $etapa, 0);
3133    }
3134  }
3135  drupal_alter('user_acceso_proceso', $fechas, $proceso, $tipo);
3136  return $fechas;
3137}
3138*/
3139/**
3140 * Implementation of hook_form_FORM_ID_alter(): content_field_edit_form.
3141 */
3142function ente_planificador_form_content_field_edit_form_alter(&$form, $form_state) {
3143  if ($form['#field']['type_name'] == 'ente_planificador') {
3144    $form['widget']['ente_planificador'] = array(
3145      '#title' => 'ente planificador',
3146      '#type' => 'checkbox',
3147      '#default_value' => variable_get('ente_planificador_' . $form['#field']['field_name'], FALSE),
3148      '#return_value' => '1',
3149    );
3150    $form['#submit'][] = 'ente_planificador_content_field_edit_form_submit';
3151  }
3152}
3153
3154/*
3155 * Implementation of ente_planificador_content_field_edit_form_submit()
3156 */
3157function ente_planificador_content_field_edit_form_submit($form, &$form_state) {
3158  variable_set('ente_planificador_' . $form_state['values']['field_name'], $form_state['values']['ente_planificador']);
3159}
3160
3161/**
3162 * Implementation of hook_theme_registry_alter()
3163 */
3164function ente_planificador_theme_registry_alter(&$theme_registry) {
3165  if (!empty($theme_registry['content_view_multiple_field'])) {
3166    $theme_registry['content_view_multiple_field']['function'] = 'ente_planificador_content_view_multiple_field';
3167  }
3168}
3169
3170/*
3171 * Implementation of ente_planificador_content_view_multiple_field()
3172 */
3173function ente_planificador_content_view_multiple_field($items, $field, $values) {
3174  $output = '';
3175  $i = 0;
3176  foreach ($items as $item) {
3177    if (!empty($item) || $item == '0') {
3178      $tipo = $i % 2 ? 'odd' : 'even';
3179      $output .= '<div class="field-item field-item-'. $i .' field-label-inline-' . $tipo . '">'. $item .'</div>';
3180      $i++;
3181    }
3182  }
3183  return $output;
3184}
3185
3186/**
3187 * Implementation of hook_feeds_node_processor_targets_alter().
3188 *
3189 * @see FeedsNodeProcessor::getMappingTargets()
3190 */
3191function ente_planificador_feeds_node_processor_targets_alter(&$targets, $content_type) {
3192  if ($content_type == 'ente_planificador') {
3193    $targets['tipo'] = array(
3194      'name' => t('Tipo de ente planificador'),
3195      'callback' => 'ente_planificador_feeds_set_target',
3196    );
3197    $targets['razon_social'] = array(
3198      'name' => t('Razón social del ente planificador'),
3199      'callback' => 'ente_planificador_values_feeds_set_target',
3200    );
3201    $targets['rif'] = array(
3202      'name' => t('Rif del ente planificador'),
3203      'callback' => 'ente_planificador_values_feeds_set_target',
3204    );
3205    $targets['direccion'] = array(
3206      'name' => t('Direccion del ente planificador'),
3207      'callback' => 'ente_planificador_values_feeds_set_target',
3208    );
3209    $targets['ciudad'] = array(
3210      'name' => t('Ciudad del ente planificador'),
3211      'callback' => 'ente_planificador_values_feeds_set_target',
3212    );
3213    $targets['estado'] = array(
3214      'name' => t('Entidad del ente planificador'),
3215      'callback' => 'ente_planificador_estado_feeds_set_target',
3216    );
3217  }
3218}
3219
3220/**
3221 * Callback for mapping. Here is where the actual mapping happens.
3222 *
3223 * When the callback is invoked, $target contains the name of the field the
3224 * user has decided to map to and $value contains the value of the feed item
3225 * element the user has picked as a source.
3226 */
3227function ente_planificador_feeds_set_target($node, $target, $value) {
3228  if (!entes_planificadores_obtiene_tipos($value)) {
3229    $value = 2;
3230  }
3231  $node->tipo = $value;
3232}
3233
3234function ente_planificador_values_feeds_set_target($node, $target, $value) {
3235  if (trim($value) != '') {
3236    $node->{$target} = $value;
3237  }
3238}
3239
3240function ente_planificador_estado_feeds_set_target($node, $target, $value) {
3241  if (is_string($value) && $value !== '') {
3242    $resul_act = db_query("SELECT codigo, nombre FROM {entidad} where codigo = '%s'", $value);
3243    $entidadL = db_fetch_object($resul_act);
3244    if ($entidadL) {
3245      $node->estado = (int) $entidadL->codigo;
3246    }
3247    else {
3248      $resul_act = db_query("SELECT codigo, nombre FROM {entidad} where nombre = '%s'", $value);
3249      $entidadL = db_fetch_object($resul_act);
3250      if ($entidadL) {
3251        $node->estado = (int) $entidadL->codigo;
3252      }
3253    }
3254  }
3255}
3256
3257
3258/**
3259 * Implementation of hook_feeds_node_processor_targets_alter().
3260 *
3261 * @see FeedsNodeProcessor::getMappingTargets()
3262 */
3263function ente_planificador_feeds_user_processor_targets_alter(&$targets) {
3264  $targets['ente'] = array(
3265    'name' => t('Asignar ente planificador al usuario'),
3266    'callback' => 'ente_planificador_asigna_ente_feeds_set_target',
3267  );
3268}
3269
3270
3271function ente_planificador_asigna_ente_feeds_set_target(&$account, $target, $value) {
3272  if (trim($value) != '') {
3273    $resul_act = db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = 'ente_planificador'", $value);
3274    $ente = db_fetch_object($resul_act);
3275    if ($ente && $ente->nid) {
3276     $account->entes = $ente->nid;
3277    }
3278  }
3279}
3280
3281/**
3282 * Implementation of ente_planificador_leer_ente_planificadores().
3283 *
3284 * funcion para evitar la leida muchas veces de un ente planificador
3285 */
3286function ente_planificador_leer_ente_planificadores($ente_planificador = 0) {
3287  static $ente_planificadores;
3288  if (!isset($ente_planificadores)) {
3289    $ente_planificadores = array();
3290  }
3291  $ente_planificador_leido = 0;
3292  if (is_numeric($ente_planificador)) {
3293    if (isset($ente_planificadores[$ente_planificador])) {
3294      $ente_planificador_leido = $ente_planificadores[$ente_planificador];
3295    }
3296    else {
3297      $ente_planificador_leido = node_load($ente_planificador);
3298      if ($ente_planificador_leido->type == 'ente_planificador') {
3299        $ente_planificadores[$ente_planificador] = $ente_planificador_leido;
3300      }
3301      else {
3302        $ente_planificador_leido = 0;
3303      }
3304    }
3305  }
3306  if ($ente_planificador && $ente_planificador->nid) {
3307    $ente_planificadores[$ente_planificador->nid] = $ente_planificador;
3308    $ente_planificador_leido = $ente_planificador;
3309  }
3310  return $ente_planificador_leido;
3311}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.