source: sipes/0.3-modules/ente_planificador/ente_planificador.module @ eb502b4

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

se modifico el menu de planificacion para que no mostrara el progreso de las distintas etapas

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