source: sipp/0.3-stable-modules/proyectos_operativos/proyectos_operativos.module @ 0ca2241

0.3-stable
Last change on this file since 0ca2241 was 0ca2241, checked in by José Gregorio Puentes <jpuentes@…>, 9 años ago

Se agrego la redireccion en el cambio de estado de la lista de proyectos

  • Propiedad mode establecida a 100755
File size: 211.0 KB
Línea 
1<?php
2  /**
3  * Sistema Integral de Planificación y Presupuesto (SIPP)
4  * @file proyectos_operativos.module
5  * Drupal part Module to Sistema Integral de Planificación y Presupuesto (SIPP)
6  * Copyright 2013 Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana (CENDITEL)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  * @author Cenditel Merida - Msc. Juan Vizcarrondo
23  * @date 2013-02-04 // (a&#241;o-mes-dia)
24  * @version 0.1 // (0.1)
25  *
26  */
27
28/*
29 * Implementation of hook_node_info()
30 */
31function proyectos_operativos_node_info() {
32  return array(
33    'proyectos_operativos' => array(
34      'name' => t('Proyectos Operativos'),
35      'description' => '',
36      'has_title' => TRUE,
37      'title_label' => 'Nombre del proyecto',
38      'has_body' => FALSE,
39      'body_label' => 'Cuerpo',
40      'module' => 'proyectos_operativos',
41    ),
42  );
43}
44
45/*
46 * Implementation of hook_form()
47 */
48function proyectos_operativos_form(&$node, $form_state) {
49  return node_content_form($node, $form_state);
50}
51
52/*
53 * Implementation of hook_access()
54 */
55function proyectos_operativos_access($op, $node, $account) {
56  if ($op == 'view') {
57    return user_access('ver planificador');
58  }
59  if ($op == 'create') {
60    return user_access('admin planificador');
61  }
62  if ($op == 'update') {
63    return user_access('admin planificador');
64  }
65  if ($op == 'delete') {
66    return user_access('admin planificador');
67  }
68}
69
70/*
71 * Implementation of hook_ente_procesos_alter()
72 */
73function proyectos_operativos_ente_procesos_alter(&$procesos, $type) {
74  if ($type == 'status') {
75    $procesos['proyectos_operativos'] = array(
76      'title' => t('Proyectos Operativos'),
77      'description' => t('Definición de Proyectos Direccionales'),
78      'weight' => -9,
79    );
80  }
81  else {
82    $procesos['proyectos_operativos_formular'] = array(
83      'title' => t('Formular Proyectos Operativos'),
84      'description' => t('Permite agregar, modificar y eliminar los Proyectos Operativos'),
85      'message' => 'Se podrá registrar y/o modificar las Proyectos Operativos desde %fecha hasta la fecha %fecha1',
86      'message_expire' => 'Registrar y/o modificar las Proyectos Operativos no se encuentra disponible, se podra realizar desde %fecha hasta la fecha %fecha1)',
87      'weight' => 3,
88      'proceso' => 'proyectos_operativos',
89    );
90  }
91}
92
93/*
94 * Implementation of acciones_centralizadas_status_planificacion_acciones_centralizadas()
95 */
96function proyectos_operativos_status_planificacion_proyectos_operativos($ente_planificador, $tipo = 2) {
97  $datos_proyectos_operativos_status = array();
98  $tipo_plan = 'proyectos_operativos_formular';
99  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador->tipo);
100  $new_ente_planificador = node_load($ente_planificador);
101  $year = variable_get('proyectos_operativos_anho_creacion', 0);
102  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
103  $result = db_query("SELECT ac.nid FROM {proyectos_operativos} AS ac INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND year = %d AND w.sid = %d", $ente_planificador, $year, $estado_aprobado);
104  $proyectos_operativos = db_fetch_object($result);
105  //se verifica que exista la planificacion, si existe al menos los datos de familiarizacion fueron ingresados
106  $datos_proyectos_operativos_status['proyectos_operativos_formular']['value'] = isset($proyectos_operativos->nid) ? 1 : 0;
107  $datos_proyectos_operativos_status['proyectos_operativos_formular']['title'] = t('Registrar Proyectos Operativos para el año @year', array('@year' => $year));
108  $datos_proyectos_operativos_status['proyectos_operativos_formular']['link'] = 'proyectos_operativos';
109  $datos_proyectos_operativos_status['proyectos_operativos_formular']['mylink'] = 'proyectos_operativos';
110  $datos_proyectos_operativos_status['proyectos_operativos_formular']['weight'] = -10;
111  return $datos_proyectos_operativos_status;
112}
113
114/**
115 * Menu access control callback. Determine access to Workflow tab.
116 */
117function _proyectos_operativos_edita_datos_generales_access($node = NULL) {
118  $acceso = _proyectos_operativos_access_editar($node);
119  if (!$acceso) {
120    return FALSE;
121  }
122  return TRUE;
123}
124
125/*
126 * Implementation of hook_nodeapi()
127 */
128function proyectos_operativos_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
129  switch ($op) {
130    case 'insert':
131      if ($node->type == 'proyectos_operativos') {
132        $year = variable_get('proyectos_operativos_anho_creacion', 0) ? variable_get('proyectos_operativos_anho_creacion', 0) : date("Y");
133        db_query('INSERT INTO {proyectos_operativos} (nid, year, ente) VALUES (%d, %d, %d)', $node->nid, $year, $node->field_proyecto_ente[0]['nid']);
134      }
135    break;
136    case 'update':
137      if ($node->type == 'proyectos_operativos') {
138        $result = db_query("SELECT ente FROM {proyectos_operativos} WHERE nid = %d", $node->nid);
139        $proyectos_operativos = db_fetch_array($result);
140        //print_r($proyectos_operativos);
141        if ($proyectos_operativos && $proyectos_operativos['ente'] != $node->field_proyecto_ente[0]['nid']){
142          db_query('update {proyectos_operativos} set ente = %d WHERE nid = %d', $node->field_proyecto_ente[0]['nid'], $node->nid);
143        }
144      }
145    break;
146    case 'load':
147      if ($node->type == 'proyectos_operativos') {
148        $titulo = isset($node->field_proyecto_titulo[0]['value']) && trim($node->field_proyecto_titulo[0]['value']) != '' ? $node->field_proyecto_titulo[0]['value'] : $node->title;
149        $node->titulo_asignado = $titulo;
150        $result = db_query("SELECT year FROM {proyectos_operativos} WHERE nid = %d", $node->nid);
151        if (!($proyectos_operativos = db_fetch_array($result))){
152          $year = variable_get('proyectos_operativos_anho_creacion', 0) ? variable_get('proyectos_operativos_anho_creacion', 0) : date("Y");
153          db_query('INSERT INTO {proyectos_operativos} (nid, year, ente) VALUES (%d, %d, %d)', $node->nid, $year, $node->field_proyecto_ente[0]['nid']);
154          $result = db_query("SELECT year FROM {proyectos_operativos} WHERE nid = %d", $node->nid);
155          $proyectos_operativos = db_fetch_array($result);
156        }
157        $node->anhoproyectos_operativos = $proyectos_operativos['year'];
158      }
159      elseif ($node->type == 'accion_especifica') {
160        $titulo = isset($node->field_accion_titulo[0]['value']) && trim($node->field_accion_titulo[0]['value']) != '' ? $node->field_accion_titulo[0]['value'] : $node->title;
161        $node->titulo_asignado = $titulo;
162      }
163    break;
164    case 'delete':
165      //eliminar todas las ae del proyecto
166      foreach($node->field_proyecto_accion_esp as $accion) {
167        if ($accion['nid']) {
168          node_delete($accion['nid']);
169        }
170      }
171      db_query('DELETE FROM {proyectos_operativos} WHERE nid = %d', $node->nid);
172    break;
173    case 'view':
174      if ($node->type == 'proyectos_operativos') {
175        module_load_include('inc', 'workflow', 'workflow.pages');
176        $output = '<div class="field-label"><b>' . t('Flujo de Trabajo') . ':</b>&nbsp;</div>';
177        $wid = workflow_get_workflow_for_type($node->type);
178        $states_per_page = variable_get('workflow_states_per_page', 20);
179        $result = db_query("SELECT sid, state FROM {workflow_states} WHERE status = 1 ORDER BY sid");
180        while ($data = db_fetch_object($result)) {
181          $states[$data->sid] = check_plain(t($data->state));
182        }
183        $deleted_states = array();
184        $result = db_query("SELECT sid, state FROM {workflow_states} WHERE status = 0 ORDER BY sid");
185        while ($data = db_fetch_object($result)) {
186          $deleted_states[$data->sid] = check_plain(t($data->state));
187        }
188        $current = workflow_node_current_state($node);
189        // theme_workflow_current_state() must run state through check_plain().
190        $output .= '<p>'. t('Current state: !state', array('!state' => theme('workflow_current_state', $states[$current]))) . "</p>\n";
191        $result = db_query("SELECT h.*, u.name FROM {workflow_node_history} h LEFT JOIN {users} u ON h.uid = u.uid WHERE nid = %d ORDER BY hid DESC", $node->nid);
192        $rows = array();
193        while ($history = db_fetch_object($result)) {
194          if ($history->sid == $current && !isset($deleted_states[$history->sid]) && !isset($current_themed)) {
195          // Theme the current state differently so it stands out.
196          $state_name = theme('workflow_current_state', $states[$history->sid]);
197          // Make a note that we have themed the current state; other times in the history
198          // of this node where the node was in this state do not need to be specially themed.
199          $current_themed = TRUE;
200          }
201          elseif (isset($deleted_states[$history->sid])) {
202            // The state has been deleted, but we include it in the history.
203            $state_name = theme('workflow_deleted_state', $deleted_states[$history->sid]);
204            $footer_needed = TRUE;
205          }
206          else {
207            // Regular state.
208            $state_name = check_plain(t($states[$history->sid]));
209          }
210          if (isset($deleted_states[$history->old_sid])) {
211            $old_state_name = theme('workflow_deleted_state', $deleted_states[$history->old_sid]);
212            $footer_needed = TRUE;
213          }
214          else {
215            $old_state_name = check_plain(t($states[$history->old_sid]));
216          }
217          $rows[] = theme('workflow_history_table_row', $history, $old_state_name, $state_name);
218        }
219        $output .= theme('workflow_history_table', $rows, !empty($footer_needed));
220        $node->content['proyectos_operativos_flujo'] = array(
221          '#value' => $output,
222          '#weight' => 100,
223        );
224      }
225      elseif ($node->type == 'accion_especifica') {
226        $node->title = $node->titulo_asignado;
227      }
228    break;
229  }
230}
231
232/**
233 * Implementation of _proyectos_operativos_edita_datos_indicadores_access()
234 * Menu access control callback. Determina si un proyecto tiene acceso a indicadores.
235 */
236function _proyectos_operativos_edita_datos_indicadores_access($node = NULL) {
237  global $user;
238  $acceso = _proyectos_operativos_access_editar($node);
239  if (!$acceso) {
240    return FALSE;
241  }
242  return $node->field_proyecto_og[0]['value'];
243}
244
245/**
246 * Implementation of _proyectos_operativos_edita_datos_ae_access()
247 * Menu access control callback. Determina si un proyecto tiene acceso a acciones especificas.
248 */
249function _proyectos_operativos_edita_datos_ae_access($node = NULL) {
250  global $user;
251  $acceso = _proyectos_operativos_access_editar($node);
252  if (!$acceso) {
253    return FALSE;
254  }
255  return $node->field_proyecto_unidadm[0]['value'];
256}
257
258/**
259 * Implementation of _proyectos_operativos_edita_datos_financieros_access()
260 * Menu access control callback. Determina si un proyecto tiene acceso a los datos financieros.
261 */
262function _proyectos_operativos_edita_datos_financieros_access($node = NULL) {
263  if (!_proyectos_operativos_edita_datos_ae_access($node)) {
264    return FALSE;
265  }
266  foreach($node->field_proyecto_accion_esp as $accion) {
267    if ($accion['nid'] && $nid != $accion['nid']) {
268      $accion_load = node_load($accion['nid']);
269      if ($accion_load && $accion_load->type == 'accion_especifica') {
270        if ($accion_load->field_accion_esp_programacion[0]['tid']) {
271          foreach($accion_load->field_accion_esp_programacion as $programacion) {
272            foreach($programacion as $id_value => $mesp){
273              if ($id_value != 'tid') {
274                $montos +=$mesp;
275              }
276            }
277          }
278        }
279        $acciones_especificas[$accion_load->nid] = $accion_load;
280        $porcentajes[$accion_load->field_accion_esp_ponderacion[0]['value']] = 1;
281        $ejecucion += $accion_load->field_accion_esp_ponderacion[0]['value'];
282      }
283    }
284    elseif($nid = $accion['nid']) {
285      $acciones_especificas[$ae->nid] = $ae;
286    }
287  }
288  $monto_restante = $node->field_proyecto_monto_anual[0]['value'] - $montos;
289  $et = 100 - $ejecucion;
290  return (($monto_restante == 0) && ($et == 0));
291}
292
293
294/**
295 * Implementation of _proyectos_operativos_ver_datos_wk_access()
296 * Menu access control callback. Determina si un usuario tiene acceso al flujo de trabajo
297 */
298function _proyectos_operativos_ver_datos_wk_access($node = NULL) {
299  return  (user_access('ver planificador') && $node->type == 'proyectos_operativos');
300}
301
302/**
303 * Implementation of _proyectos_operativos_ver_datos_wk_access()
304 * Menu access control callback. Determina si un usuario tiene acceso a editar el flujo de trabajo
305 */
306function _proyectos_operativos_edita_datos_wk_access($node = NULL) {
307  global $user;
308  $fecha = FALSE;
309  $ente = usuario_tiene_ente($user->uid);
310  if ($ente->nid == $ente_planificador->nid) {
311    $fecha = TRUE;
312  }
313  elseif (!user_access('admin planificador')) {
314    $fecha = FALSE;
315  }
316  $accesso = workflow_node_tab_access($node);
317  return $fecha && $accesso && _proyectos_operativos_edita_datos_financieros_access($node);
318}
319
320/**
321 * Implementation of _proyectos_operativos_edita_datos_agregar()
322 * Menu access control callback. Determina si un usuario tiene acceso a crear un nuevo proyecto
323 */
324function _proyectos_operativos_edita_datos_agregar() {
325  global $user;
326  $current_time = time();
327  $tipo_plan = 'proyectos_operativos_formular';
328  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
329  $fecha = FALSE;
330  $ente = usuario_tiene_ente($user->uid);
331  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
332    $fecha = TRUE;
333  }
334  if ($fecha) {
335    if ($ente->nid) {
336      $fecha = TRUE;
337    }
338    elseif (!user_access('admin planificador')) {
339      $fecha = FALSE;
340    }
341  }
342  return $fecha;
343}
344
345/**
346 * Implementation of _proyectos_operativos_access_editar()
347 * Menu access control callback. Determina si un usuario tiene acceso a editar un proyecto
348 */
349function _proyectos_operativos_access_editar($node) {
350  global $user;
351  $estado_aprobado = variable_get('proyectos_operativos_state_aprobado', NULL);
352  $estado_naprobado = variable_get('proyectos_operativos_state_naprobado', NULL);
353  if ($node->_workflow == $estado_aprobado || $node->_workflow == $estado_naprobado) {
354    return FALSE;
355  }
356  if ($node->anhoproyectos_operativos != variable_get('proyectos_operativos_anho_creacion', 0)) {
357    return FALSE;
358  }
359  $ente_planificador = node_load($node->field_proyecto_ente[0]['nid']);
360  $current_time = time();
361  $tipo_plan = 'proyectos_operativos_formular';
362  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
363  $fecha = FALSE;
364  $ente = usuario_tiene_ente($user->uid);
365  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
366    $fecha = TRUE;
367  }
368  if ($fecha) {
369    if ($ente->nid == $ente_planificador->nid) {
370      $fecha = TRUE;
371    }
372    elseif (!user_access('admin planificador')) {
373      $fecha = FALSE;
374    }
375  }
376  $roles_perm = TRUE;
377  if ($fecha && !user_access('admin planificador')) {
378    $roles_perm = FALSE;
379    $roles_allow = variable_get('proyectos_operativos_state_m_' . $node->_workflow, array());
380    $roles = array_keys($user->roles);
381    if (count($roles)) {
382      foreach($roles as $rol) {
383        if($roles_allow[$rol]) {
384          $roles_perm = TRUE;
385        }
386      }
387    }
388  }
389  return $fecha && $roles_perm;
390}
391
392/*
393 * Implementation of hook_menu()
394 */
395function proyectos_operativos_menu() {
396  $items = array();
397  //consultar proyectos operativos
398  $items['proyectos_operativos'] = array(
399    'title' => t('Proyectos Operativos'),
400    'page callback' => 'proyectos_operativos_search_ac_display',
401    'access arguments' => array('ver planificador'),
402    'type' => MENU_NORMAL_ITEM,
403  );
404  $items['proyectos_operativos/default'] = array(
405    'title' => t('Proyectos Operativos'),
406    'type' => MENU_DEFAULT_LOCAL_TASK,
407    'weight' => -10
408  );
409  $items['proyectos_operativos/default/proyectos'] = array(
410    'title' => t('Lista de Proyectos Operativos'),
411    'page callback' => 'proyectos_operativos_search_ac_display',
412    'access arguments' => array('ver planificador'),
413    'type' => MENU_DEFAULT_LOCAL_TASK,
414    'weight' => -10
415  );
416  $items['proyectos_operativos/default/entramite'] = array(
417    'title' => t('Lista de Proyectos Operativos sin Aprobar'),
418    'page callback' => 'proyectos_operativos_search_ac_display_not_approved',
419    'access arguments' => array('ver planificador'),
420    'type' => MENU_LOCAL_TASK,
421    'weight' => -9
422  );
423  //editar proyectos operativos (basicos)
424  $items['proyectosopedit/%proyectosop'] = array(
425    'title callback' => 'node_page_title',
426    'title arguments' => array(1),
427    'page callback' => 'drupal_get_form',
428    'page arguments' => array('proyectos_operativos_proyecto_basico_form', 1),
429    'access callback' => '_proyectos_operativos_access_editar',
430    'access arguments' => array(1),
431    'type' => MENU_CALLBACK,
432  );
433  $items['proyectosopedit/%proyectosop/basicos'] = array(
434    'title' =>  t('Datos Básicos'),
435    'type' => MENU_DEFAULT_LOCAL_TASK,
436    'weight' => -10
437  );
438  //editar proyectos operativos (generales)
439  $items['proyectosopedit/%proyectosop/generales'] = array(
440    'title' => t('Datos Generales'),
441    'page callback' => 'drupal_get_form',
442    'page arguments' => array('proyectos_operativos_proyecto_generales_form', 1),
443    'access callback' => '_proyectos_operativos_edita_datos_generales_access',
444    'access arguments' => array(1),
445    'weight' => -7,
446    'type' => MENU_LOCAL_TASK,
447  );
448  //editar proyectos operativos (indicadores)
449  $items['proyectosopedit/%proyectosop/indicadores'] = array(
450    'title' => t('Indicadores del Proyecto'),
451    'page callback' => 'drupal_get_form',
452    'page arguments' => array('proyectos_operativos_proyecto_indicadores_form', 1),
453    'access callback' => '_proyectos_operativos_edita_datos_indicadores_access',
454    'access arguments' => array(1),
455    'weight' => -6,
456    'type' => MENU_LOCAL_TASK,
457  );
458  //editar proyectos operativos (acciones especificas)
459  $items['proyectosopedit/%proyectosop/ae'] = array(
460    'title' => t('Acciones Especificas'),
461    'page callback' => '_proyectos_operativos_proyecto_ae',
462    'page arguments' => array(1),
463    'access callback' => '_proyectos_operativos_edita_datos_ae_access',
464    'access arguments' => array(1),
465    'weight' => -5,
466    'type' => MENU_LOCAL_TASK,
467  );
468  $items['proyectosopedit/%proyectosop/ae/ver'] = array(
469    'title' =>  t('Acciones Especificas'),
470    'type' => MENU_DEFAULT_LOCAL_TASK,
471    'weight' => -10
472  );
473  //editar proyectos operativos (editar acciones especificas)
474  $items['proyectosopedit/%proyectosop/ae/%accion_especifical/edit'] = array(
475    'title' => t('Editar'),
476    'page callback' => '_proyectos_operativos_proyecto_ae',
477    'page arguments' => array(1, 3),
478    'access callback' => '_proyectos_operativos_edita_datos_ae_access',
479    'access arguments' => array(1),
480    'weight' => -4,
481    'type' => MENU_LOCAL_TASK,
482  );
483  //editar proyectos operativos (borrar acciones especificas)
484  $items['proyectosopedit/%proyectosop/ae/%accion_especifical/remove'] = array(
485    'title' => t('Eliminar'),
486    'page callback' => 'drupal_get_form',
487    'page arguments' => array('proyectos_operativos_remove_ac_form', 1, 3),
488    'access callback' => '_proyectos_operativos_edita_datos_ae_access',
489    'access arguments' => array(1),
490    'weight' => -4,
491    'type' => MENU_LOCAL_TASK,
492  );
493  //editar proyectos operativos (datos financieros)
494  $items['proyectosopedit/%proyectosop/finacieros'] = array(
495    'title' => t('Datos Financieros'),
496    'page callback' => '_proyectos_operativos_proyecto_financieros',
497    'page arguments' => array(1),
498    'access callback' => '_proyectos_operativos_edita_datos_financieros_access',
499    'access arguments' => array(1),
500    'weight' => -4,
501    'type' => MENU_LOCAL_TASK,
502  );
503  //ver ficha del proyecto
504  $items['proyectosopedit/%proyectosop/ficha'] = array(
505    'title' => t('Ficha'),
506    'page callback' => '_proyectos_operativos_proyecto_ficha_proyecto',
507    'page arguments' => array(1),
508    'access callback' => '_proyectos_operativos_edita_datos_financieros_access',
509    'access arguments' => array(1),
510    'weight' => -3,
511    'type' => MENU_LOCAL_TASK,
512  );
513  //consulta proyecto operativo
514  $items['proyectosopedit/%proyectosop/ver'] = array(
515    'title' => 'Ver',
516    'page callback' => '_proyectos_operativos_proyecto_regresa_ver',
517    'page arguments' => array(1),
518    'access callback' => '_proyectos_operativos_ver_datos_wk_access',
519    'access arguments' => array(1),
520    'type' => MENU_LOCAL_TASK
521  );
522  //agregar proyecto operativo
523  $items['agregarproyectosop'] = array(
524    'title' => t('Agregar Proyecto'),
525    'page callback' => '_proyectos_operativos_proyecto_agregar_proyecto',
526    'access callback' => '_proyectos_operativos_edita_datos_agregar',
527    'weight' => -7,
528    'type' => MENU_NORMAL_ITEM,
529  );
530  //consulta proyecto operativo
531  $items['proyectosop/%proyectosop'] = array(
532    'title' => t('Ver'),
533    'page callback' => '_proyectos_operativos_proyecto_campos',
534    'page arguments' => array(1),
535    'access callback' => '_proyectos_operativos_ver_datos_wk_access',
536    'access arguments' => array(1),
537    'weight' => -7,
538    'type' => MENU_CALLBACK,
539  );
540  $items['proyectosop/%proyectosop/ver'] = array(
541    'title' =>  t('Ver'),
542    'type' => MENU_DEFAULT_LOCAL_TASK,
543    'weight' => -10
544  );
545  $items['proyectosop/%proyectosop/ficha'] = array(
546    'title' => t('Ficha'),
547    'page callback' => '_proyectos_operativos_proyecto_ficha_proyecto',
548    'page arguments' => array(1),
549    'access callback' => '_proyectos_operativos_ver_datos_wk_access',
550    'access arguments' => array(1),
551    'weight' => -6,
552    'type' => MENU_LOCAL_TASK,
553  );
554  //consulta proyecto operativo (accion especificas)
555  $items['proyectosop/%proyectosop/ae'] = array(
556    'title' => t('Acciones Especificas'),
557    'page callback' => '_list_proyectos_operativos_proyecto_ae',
558    'page arguments' => array(1),
559    'access callback' => '_proyectos_operativos_ver_datos_wk_access',
560    'access arguments' => array(1),
561    'weight' => -5,
562    'type' => MENU_LOCAL_TASK,
563  );
564  $items['proyectosop/%proyectosop/ae/%accion_especifical/ver'] = array(
565    'title' => t('Consultar Acción Específica'),
566    'page callback' => 'node_view',
567    'page arguments' => array(3),
568    'access callback' => '_proyectos_operativos_ver_datos_wk_access',
569    'access arguments' => array(1),
570    'weight' => -4,
571    'type' => MENU_LOCAL_TASK,
572  );
573  //editar proyectos operativos (borrar acciones especificas)
574  $items['proyectosop/%proyectosop/ae/%accion_especifical/remove'] = array(
575    'title' => t('Eliminar'),
576    'page callback' => 'drupal_get_form',
577    'page arguments' => array('proyectos_operativos_remove_ac_form', 1, 3),
578    'access callback' => '_proyectos_operativos_edita_datos_ae_access',
579    'access arguments' => array(1),
580    'weight' => -4,
581    'type' => MENU_CALLBACK,
582  );
583  //consulta proyecto operativo (datos financieros)
584  $items['proyectosop/%proyectosop/finacieros'] = array(
585    'title' => t('Datos Financieros'),
586    'page callback' => '_proyectos_operativos_proyecto_financieros',
587    'page arguments' => array(1),
588    'access callback' => '_proyectos_operativos_ver_datos_wk_access',
589    'access arguments' => array(1),
590    'weight' => -4,
591    'type' => MENU_LOCAL_TASK,
592  );
593  //consulta proyecto operativo (flujo de trabajo)
594  $items['proyectosop/%proyectosop/workflow'] = array(
595    'title' => t('Workflow'),
596    'page callback' => '_proyectos_operativos_proyecto_ver_workflow',
597    'page arguments' => array(1),
598    'access callback' => '_proyectos_operativos_edita_datos_wk_access',
599    'access arguments' => array(1),
600    'weight' => -4,
601    'type' => MENU_LOCAL_TASK,
602  );
603  //editar proyecto operativo
604  $items['proyectosop/%proyectosop/edit'] = array(
605    'title' => t('Edit'),
606    'page callback' => '_proyectos_operativos_proyecto_editar',
607    'page arguments' => array(1),
608    'access callback' => '_proyectos_operativos_access_editar',
609    'access arguments' => array(1),
610    'weight' => -3,
611    'type' => MENU_LOCAL_TASK,
612  );
613  //editar proyecto operativo
614  $items['proyectosop/%proyectosop/remove'] = array(
615    'title' => t('Eliminar'),
616    'page callback' => 'drupal_get_form',
617    'page arguments' => array('proyectos_operativos_remove_proyectosop_form', 1),
618    'access callback' => '_proyectos_operativos_access_editar',
619    'access arguments' => array(1),
620    'weight' => -3,
621    'type' => MENU_LOCAL_TASK,
622  );
623
624
625  //configuracion proyectos operativos
626  $items['admin/settings/ente_planificador/proyectos_operativos'] = array(
627    'title' => t('Proyectos Operativos'),
628    'page callback' => 'drupal_get_form',
629    'page arguments' => array('proyectos_operativos_admin_settings'),
630    'access arguments' => array('admin planificador'),
631    'weight' => -6,
632    'type' => MENU_LOCAL_TASK,
633    'file' => 'proyectos_operativos.admin.inc',
634  );
635  $items['proyectos_operativos_proyecto_generales_agrega_talento_js_util'] = array(
636    'title' => 'JS utilities',
637    'page callback' => 'proyectos_operativos_proyecto_generales_agrega_talento_js_util',
638    'access arguments' => array('ver planificador'),
639    'type' => MENU_CALLBACK,
640  );
641  if (module_exists('workflow')) {
642    //configuracion proyectos operativos
643    $items['admin/settings/ente_planificador/proyectos_operativos/worflow/color'] = array(
644      'title' => t('Workflow Status Color'),
645      'page callback' => 'drupal_get_form',
646      'page arguments' => array('proyectos_operativos_admin_workflow_color_settings'),
647      'access arguments' => array('admin planificador'),
648      'weight' => -6,
649      'type' => MENU_LOCAL_TASK,
650      'file' => 'proyectos_operativos.admin.inc',
651    );
652  }
653  return $items;
654}
655
656/**
657 * Implementation of _proyectos_operativos_proyecto_financieros().
658 * Ver datos financieros (proyectos operativos).
659 */
660function _proyectos_operativos_proyecto_ficha_proyecto($proyecto = 0) {
661  drupal_set_title(t('Ficha del Proyecto'));
662  return theme('proyectos_operativos_ficha_proyecto', $proyecto);
663
664}
665
666/*
667 * proyectos_operativos_proyecto_generales_agrega_talento_js_util
668 * Generates AJAX responses of talento humano
669 */
670function proyectos_operativos_proyecto_generales_agrega_talento_js_util($tipo) {
671  $arreglov['talento'] = array(
672    'field_proyecto_institucionth' => 'field_proyecto_institucionth',
673    'field_proyecto_nombres_a' => 'field_proyecto_nombres_a',
674    'field_proyecto_cargo_th' => 'field_proyecto_cargo_th',
675    'field_proyecto_rol_th' => 'field_proyecto_rol_th',
676    'field_proyecto_esfuerzo' => 'field_proyecto_esfuerzo',
677    'field_proyecto_formacion' => 'field_proyecto_formacion',
678  );
679  $arreglov['capacidades'] = array(
680    'field_proyecto_institucion_alc' => 'field_proyecto_institucion_alc',
681    'field_proyecto_infraestructura' => 'field_proyecto_infraestructura',
682    'field_proyecto_equipos' => 'field_proyecto_equipos',
683    'field_proyecto_insumos' => 'field_proyecto_insumos',
684    'field_proyectos_servicios' => 'field_proyectos_servicios',
685  );
686  $arreglov['beneficiario'] = array(
687    'field_proyecto_beneficiario' => 'field_proyecto_beneficiario',
688    'field_proyectos_masculino_d' => 'field_proyectos_masculino_d',
689    'field_proyectos_femenino_d' => 'field_proyectos_femenino_d',
690    'field_proyectos_masculino_i' => 'field_proyectos_masculino_i',
691    'field_proyectos_femenino_i' => 'field_proyectos_femenino_i',
692  );
693  if (array_key_exists($tipo, $arreglov)) {
694    $arreglo = $arreglov[$tipo];
695  }
696  else {
697    drupal_not_found();
698  }
699  $cantidad = intval($_POST['cantidad_' . $tipo]) > 0 ? intval($_POST['cantidad_' . $tipo]) : 0;
700  $form_state = array('submitted' => FALSE);
701  $form_build_id = $_POST['form_build_id'];
702  // Add the new element to the stored form. Without adding the element to the
703  // form, Drupal is not aware of this new elements existence and will not
704  // process it. We retreive the cached form, add the element, and resave.
705  $form = form_get_cache($form_build_id, $form_state);
706  $node_type = content_types('proyectos_operativos');
707  $fields = $node_type['fields'];
708  foreach($arreglo as $field_id => $field) {
709    $fields_extra_form1[] = $field_id;
710    $prefixC .= '<th>' . $fields[$field_id]['widget']['label'] . '</th>';
711  }
712  $cantidad++;
713  if ($tipo == 'talento' || $tipo == 'capacidades') {
714    for ($i = 0; $i < $cantidad; $i++) {
715      $prefix = '';
716      if ($i == 0) {
717        $prefix = '<table align="center"><tr>' . $prefixC . '</tr><tr><td>';
718      }
719      else {
720        $prefix .= '<tr><td>';
721      }
722      $aux = '';
723      $aui = '';
724      foreach($arreglo as $field_id => $field) {
725        $new_form[$field_id . '_' . $i] = array(
726          '#type' => 'textfield',
727          '#size' => 10,
728          '#maxlength' => 255,
729          '#prefix' => $prefix,
730          '#suffix' => '</td>',
731        );
732        if ($field_id == 'field_proyecto_esfuerzo') {
733          $form[$field_id . '_' . $i]['#element_validate'] = array('proyectos_operativos_number_integer_validate2',);
734        }
735        $aux = $field_id;
736        $aui = $i;
737        $prefix = '<td>';
738      }
739      $new_form[$aux . '_' . $aui]['#suffix'] .= '</tr>';
740    }
741    $new_form[$aux . '_' . $aui]['#suffix'] .= '</table>';
742    $new_form['cantidad_' . $tipo] = array('#type' => 'hidden', '#value' => $cantidad);
743  }
744  elseif($tipo == 'beneficiario') {
745    $prefixC .= '<th>' . t('Total') . '</th>';
746    $vid = variable_get('proyectos_operativos_extra_bene', 0);
747    //$terms = taxonomy_get_tree($vid);
748    $tree = taxonomy_get_tree($vid);
749    $options = array();
750    $options[''] = t('Seleccionar');
751    if ($tree) {
752      foreach ($tree as $term) {
753        $options[$term->name] = $term->name;
754      }
755    }
756    for ($i = 0; $i < $cantidad; $i++) {
757      $subtotal = 0;
758      $prefix = '';
759      if ($i == 0) {
760        $prefix = '<table align="center"><tr>' . $prefixC . '</tr><tr><td>';
761      }
762      else {
763        $prefix .= '<tr><td>';
764      }
765      $aux = '';
766      $aui = '';
767      foreach($arreglo as $field_id => $field) {
768        $_POST[$field_id . '_' . $i] = str_replace('.', '', $_POST[$field_id . '_' . $i]);
769        $valor = intval($_POST[$field_id . '_' . $i]) > 0 ? intval($field_id . '_' . $i) : 0;
770        if ($field_id == 'field_proyecto_beneficiario') {
771          $new_form[$field_id . '_' . $i] = array(
772            '#type' => 'select',
773            '#default_value' => $valor,
774            '#options' => $options,
775            '#prefix' => $prefix,
776            '#suffix' => '</td>',
777          );
778        }
779        else {
780          $new_form[$field_id . '_' . $i] = array(
781            '#type' => 'textfield',
782            '#default_value' => $valor,
783            '#size' => 10,
784            '#maxlength' => 255,
785            '#prefix' => $prefix,
786            '#suffix' => '</td>',
787          );
788        }
789        if ($field_id != 'field_proyecto_beneficiario') {
790          if (!isset($total_arreglo[$field_id])) {
791            $total_arreglo[$field_id] = 0;
792          }
793          $subtotal += (int) $valor;
794          $totales += (int) $valor;
795          $total_arreglo[$field_id] += (int) $valor;
796          $sumas['beneficiarios']['beneficiario_' . $i] = 'beneficiario_' . $i;
797          $new_form[$field_id . '_' . $i]['#element_validate'] = array('proyectos_operativos_number_integer_validate2',);
798          $new_form[$field_id . '_' . $i]['#attributes'] = array('class' => 'number beneficiario_' . $i . ' todosbeneficiarios beneficiarios_' . $field_id, 'onchange' => "sumabeneficiario('beneficiario_$i');sumabeneficiario('todosbeneficiarios');sumabeneficiario('beneficiarios_$field_id');");
799        }
800        $aux = $field_id;
801        $aui = $i;
802        $prefix = '<td align="center">';
803      }
804      $new_form[$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiario_' . $i . '_total">' . $subtotal . '</div></td>';
805      $new_form[$aux . '_' . $aui]['#suffix'] .= '</tr>';
806    }
807    $new_form[$aux . '_' . $aui]['#suffix'] .= '<tr align="right"><td><b>' . t('TOTAL') . '</b></td>';
808    foreach($arreglo as $field_id => $field) {
809      if ($field_id != 'field_proyecto_beneficiario') {
810        $sumas['beneficiarios']['beneficiarios_' . $field_id] = 'beneficiarios_' . $field_id;
811        $new_form[$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiarios_' . $field_id . '_total">' . $total_arreglo[$field_id] . '</div></td>';
812      }
813    }
814    $sumas['beneficiarios']['todosbeneficiarios'] = 'todosbeneficiarios';
815    $sumas['beneficiarios']['empleos_generados'] = 'empleos_generados';
816    $new_form[$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="todosbeneficiarios_total">' . $totales . '</div></td></tr>';
817    $new_form[$aux . '_' . $aui]['#suffix'] .= '</table>';
818    $new_form['cantidad_' . $tipo] = array('#type' => 'hidden', '#value' => $cantidad);
819  }
820  $form[$tipo] = $new_form;
821  form_set_cache($form_build_id, $form, $form_state);
822  $form += array(
823    '#post' => $_POST,
824    '#programmed' => FALSE,
825  );
826  // Rebuild the form.
827  $form = form_builder($_POST['form_id'], $form, $form_state);
828  // Render the new output.
829  $new_form = $form[$tipo];
830  unset($new_form['#prefix'], $new_form['#suffix']); // Prevent duplicate wrappers.
831  $output = drupal_render($new_form);
832  print drupal_to_js(array('data' => $output, 'status' => true));
833  exit();
834}
835
836/**
837 * Implementation of proyectos_operativos_remove_ac_form()
838 * Eliminar accion especifica
839 */
840function proyectos_operativos_remove_ac_form($form_state, $node = 0, $ac = 0) {
841  $form = array();
842  $form['#node'] = $node;
843  $form['#ac'] = $ac;
844  $message = t('Esta seguro de eliminar la acción especifica @nombre?', array('@nombre' => $ac->titulo_asignado));
845  $caption = '<p>'. t('This action cannot be undone.') .'</p>';
846  $return_path = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'proyectosopedit/' . $node->nid . '/ae';
847  return confirm_form($form, $message, $return_path, $caption, t('Eliminar'));
848}
849
850/**
851 * Implementation of proyectos_operativos_remove_ac_form_submit().
852 * Process funcion delete accion especifica.
853 */
854function proyectos_operativos_remove_ac_form_submit($form, &$form_state) {
855  global $user;
856  $titulo = $form['#$ac']->titulo_asignado;
857  $nid = $form['#ac']->nid;
858  node_delete($form['#ac']->nid);
859  $accion_esp = array();
860  $proyecto = $form['#node'];
861  foreach($proyecto->field_proyecto_accion_esp as $ac) {
862    if ($ac['nid'] != $nid) {
863      $accion_esp[] = $ac['nid'];
864    }
865  }
866  $proyecto->field_proyecto_accion_esp = $accion_esp;
867  $proyecto->revision = 1;
868  $texto = t('Se elimino la acción especifica @nombre', array('@nombre' => $ac->titulo_asignado));
869  $proyecto->log = $texto;
870  drupal_set_message($texto);
871  if (!$_REQUEST['destination']) {
872    // add redirect
873    $form_state['redirect'] = 'proyectosopedit/' . $form['#node']->nid . '/ae';
874  }
875}
876
877/*
878 * hook_form_alter()
879 */
880function proyectos_operativos_form_alter(&$form, $form_state, $form_id) {
881  if ($form_id == 'proyectos_operativos_proyecto_basico_form' && !user_access('admin planificador')) {
882    $form['field_proyecto_ente']['#pre_render'][] = 'proyectos_operativos_nodereference_field_pre_render';
883  }
884  if ($form_id == 'proyectos_operativos_proyecto_generales_form') {
885    $form['#pre_render'][] = 'proyectos_operativos_nodereference2_field_pre_render';
886    $arreglo = array(
887      'field_proyecto_emdirecto' => 'field_proyecto_emdirecto',
888      'field_proyecto_efdirecto' => 'field_proyecto_efdirecto',
889      'field_proyecto_emindirecto' => 'field_proyecto_emindirecto',
890      'field_proyecto_efindirecto' => 'field_proyecto_efindirecto',
891    );
892    foreach($arreglo as $id) {
893      if (array_key_exists($id, $form)) {
894        $form[$id]['#pre_render'][] = 'proyectos_operativos_agregaclase_field_pre_render';
895      }
896    }
897  }
898  if ($form_id == 'workflow_tab_form') {
899    if ($form['node']['#value']->type == 'proyectos_operativos') {
900      $form['#submit'][] = 'proyectos_operativos_cambia_redirect_submit';
901    }
902  }
903}
904
905/*
906 * Implementation of proyectos_operativos_agregaclase_field_pre_render()
907 * agregar clases y funciones javascript en el formulario
908 */
909function proyectos_operativos_agregaclase_field_pre_render($element) {
910  $element[0]['value']['#attributes']['class'] .= ' empleos_generados';
911  $element[0]['value']['#attributes']['onchange'] .= ";sumabeneficiario('empleos_generados');";
912  return $element;
913}
914
915/*
916 * Implementation of proyectos_operativos_nodereference_field_pre_render()
917 * Limitar al formulario a los entes que le es posible a los usuarios
918 */
919function proyectos_operativos_nodereference_field_pre_render($element) {
920  global $user;
921  $ente = usuario_tiene_ente($user->uid);
922  if ($ente) {
923    if (count($element['nid']['nid']['#options'])) {
924      foreach($element['nid']['nid']['#options'] as $id => $entes){
925        if ($ente->nid != $id) {
926          unset($element['nid']['nid']['#options'][$id]);
927        }
928      }
929    }
930  }
931  return $element;
932}
933
934/*
935 * Implementation of proyectos_operativos_nodereference2_field_pre_render()
936 * Limitar al formulario a los entes que le es posible a los usuarios
937 */
938function proyectos_operativos_nodereference2_field_pre_render($form) {
939  if (isset($form['#node']->field_proyecto_ente[0]['nid'])){
940    $nid_exclude = $form['#node']->field_proyecto_ente[0]['nid'];
941    if (isset($form['field_proyecto_relacion']['nid']['nid']['#options'][$nid_exclude])) {
942      unset($form['field_proyecto_relacion']['nid']['nid']['#options'][$nid_exclude]);
943    }
944  }
945  if (isset($form['field_proyecto_relacion']['nid']['nid']['#options'][''])) {
946    $form['field_proyecto_relacion']['nid']['nid']['#options'][''] = t('- Sin relación -');
947  }
948/*
949
950  global $user;
951  if (!((user_access('edit all planificador'))||(user_access('admin planificador')))) {
952    $entes = obtener_mis_ente_planificador($user->uid);
953    $options = array();
954    if (count($entes)) {
955      foreach($entes as $ente){
956        unset($element['nid']['nid']['#options'][$ente['nid']]);
957      }
958    }
959  }
960*/
961  return $form;
962}
963
964/**
965 * proyectos_operativos_cambia_redirect_submit.
966 * retorna a consultar proyecto cuando se actualiza el estado del proyecto.
967 */
968function proyectos_operativos_cambia_redirect_submit($form, &$form_state) {
969  // The entire node object was stashed in the form.
970  $node = $form_state['values']['node'];
971  $form_state['redirect'] = 'proyectosop/' . $node->nid;
972    drupal_set_message(t('Se modifico el estado del proyecto.'));
973}
974
975/**
976 * Implementation of _proyectos_operativos_proyecto_regresa_ver().
977 * retorna a consultar proyecto.
978 */
979function _proyectos_operativos_proyecto_regresa_ver($node) {
980  drupal_goto('proyectosop/' . $node->nid);
981}
982
983/**
984 * Implementation of _proyectos_operativos_proyecto_editar().
985 * retorna a editar proyecto.
986 */
987function _proyectos_operativos_proyecto_editar($node) {
988  drupal_goto('proyectosopedit/' . $node->nid);
989}
990
991/**
992 * Implementation of _list_proyectos_operativos_proyecto_ae().
993 * listar acciones especificas de un proyecto.
994 */
995function _list_proyectos_operativos_proyecto_ae($node) {
996  global $user;
997  drupal_set_title('Consultar Acciones Específicas');
998  $current_time = time();
999  $tipo_plan = 'proyectos_operativos_formular';
1000  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
1001  $fecha = FALSE;
1002  $ente = usuario_tiene_ente($user->uid);
1003  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1004    $fecha = TRUE;
1005  }
1006  if (!fecha) {
1007    muestra_mensaje($tipo_plan, 2);
1008  }
1009  if ($fecha && $ente->nid) {
1010    muestra_mensaje($tipo_plan, 2, 0);
1011  }
1012  foreach($node->field_proyecto_accion_esp as $accion) {
1013    if ($accion['nid'] && $nid != $accion['nid']) {
1014      $accion_load = node_load($accion['nid']);
1015      if ($accion_load && $accion_load->type == 'accion_especifica') {
1016        $acciones_especificas[$accion_load->nid] = $accion_load;
1017        $ejecucion += $accion_load->field_accion_esp_ponderacion[0]['value'];
1018      }
1019    }
1020    elseif($nid = $accion['nid']) {
1021      $acciones_especificas[$ae->nid] = $ae;
1022    }
1023  }
1024  $output = '';
1025  $header = array();
1026  $cab = 6;
1027  $header[] = array('data' => t('Nro'));
1028  $header[] = array('data' => t('Nombre'));
1029  $header[] = array('data' => t('Fecha de inicio'));
1030  $header[] = array('data' => t('Fecha de Fin')); 
1031  $header[] = array('data' => t('%'));
1032  $header[] = array('data' => t('Acción'));
1033  $rows = array();
1034  $i = 1;
1035  if (count($acciones_especificas)) {
1036    $suma = 0;
1037    foreach($acciones_especificas as $accion) {
1038      $row = array();
1039      $row[] = array('data' => $i,);
1040      $row[] = array('data' => $accion->titulo_asignado,);
1041      //Se cambia el formato de la fecha
1042      $fecha = explode(' ', $accion->field_accion_esp_fechai[0]['value']);
1043      $formato = explode('-', $fecha[0]);
1044      $row[] = array('data' => $formato[2] . '/' . $formato[1] . '/' . $formato[0],);
1045      //Se cambia el formato de la fecha
1046      $fecha = explode(' ', $accion->field_accion_esp_fechaf[0]['value']);
1047      $formato = explode('-', $fecha[0]);
1048      $row[] = array('data' => $formato[2] . '/' . $formato[1] . '/' . $formato[0],);
1049      $suma += $accion->field_accion_esp_ponderacion[0]['value'];
1050      $row[] = array('data' => $accion->field_accion_esp_ponderacion[0]['value'],);
1051      $links = array();
1052      $links[] = array(
1053        'data' => l(t('Consultar Acción específica'), 'proyectosop/' . $node->nid . '/ae/' . $accion->nid . '/ver'),
1054        'class' => 'proyectos-operativos-acciones_especificas-pdf',
1055      );
1056      if (_proyectos_operativos_edita_datos_ae_access($node)){
1057        $links[] = array(
1058          'data' => l(t('Eliminar Acción específica'), 'proyectosop/' . $node->nid . '/ae/' . $accion->nid . '/remove', array('query' => array('destination' => 'proyectosop/' . $node->nid . '/ae'))),
1059          'class' => 'proyectos-operativos-acciones_especificas-pdf',
1060        );
1061      }
1062      drupal_alter('proyecto_accion_obtiene_links', $links, $node, $accion, $fecha);
1063      $row[] = array('data' => theme('item_list', $links),);
1064      $rows[] = $row;
1065      $i++;
1066    }
1067  }
1068  if (count($rows)) {
1069    $output .= theme('table', $header, $rows);
1070  }
1071  else {
1072    $output .= t('No existen acciones especifícas para este proyecto');
1073  }
1074  return $output;
1075}
1076
1077/**
1078 * Implementation of _proyectos_operativos_proyecto_ver_workflow().
1079 * cambiar estado del flujo de trabajo.
1080 */
1081function _proyectos_operativos_proyecto_ver_workflow($node){
1082  global $user;
1083  $current_time = time();
1084  $tipo_plan = 'proyectos_operativos_formular';
1085  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
1086  $fecha = FALSE;
1087  $ente = usuario_tiene_ente($user->uid);
1088  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1089    $fecha = TRUE;
1090  }
1091  if (!$fecha) {
1092    muestra_mensaje($tipo_plan, 2);
1093  }
1094  if ($fecha && $ente->nid) {
1095    muestra_mensaje($tipo_plan, 2, 0);
1096  }
1097  module_load_include('inc', 'workflow', 'workflow.pages');
1098  $wid = workflow_get_workflow_for_type($node->type);
1099  $states_per_page = variable_get('workflow_states_per_page', 20);
1100  $result = db_query("SELECT sid, state FROM {workflow_states} WHERE status = 1 ORDER BY sid");
1101  while ($data = db_fetch_object($result)) {
1102    $states[$data->sid] = check_plain(t($data->state));
1103  }
1104  $deleted_states = array();
1105  $result = db_query("SELECT sid, state FROM {workflow_states} WHERE status = 0 ORDER BY sid");
1106  while ($data = db_fetch_object($result)) {
1107    $deleted_states[$data->sid] = check_plain(t($data->state));
1108  }
1109  $current = workflow_node_current_state($node);
1110  // theme_workflow_current_state() must run state through check_plain().
1111  $output = '<p>'. t('Current state: !state', array('!state' => theme('workflow_current_state', $states[$current]))) . "</p>\n";
1112  $output .= drupal_get_form('workflow_tab_form', $node, $wid, $states, $current);
1113  return $output;
1114}
1115
1116/**
1117 * Implementation of proyectos_operativos_proyecto_genera_campos_form().
1118 * Formulario con todos los campos disponibles en el proyecto.
1119 */
1120function proyectos_operativos_proyecto_genera_campos_form(&$form_state, $node = 0) {
1121  $form = array();
1122  $form['#node'] = $node;
1123  $node_type = content_types('proyectos_operativos');
1124  $fields = $node_type['fields'];
1125  //$campos = array();
1126  //DATOS BASICOS
1127  //Datos Básicos de Identificación del Proyecto
1128  $title_combos = array();
1129  $title_combos['db']['title'] = t('Datos Básicos');
1130  $arreglo['db']['identificacion'] = array();
1131  $arreglo['db']['identificacion'] = array(
1132    'title' => t('Nombre del Proyecto'),
1133    'field_proyecto_codigo' => 'field_proyecto_codigo',
1134    'field_proyecto_codigo_n_etap' => 'field_proyecto_codigo_n_etap',
1135    'field_proyecto_fecha_i' => 'field_proyecto_fecha_i',
1136    'field_proyecto_fecha_f' => 'field_proyecto_fecha_f',
1137    'field_proyecto_status' => 'field_proyecto_status',
1138    'field_proyecto_situacion_p' => 'field_proyecto_situacion_p',
1139    'field_proyecto_plurianual' => 'field_proyecto_plurianual',
1140    'field_proyecto_monto_anual' => 'field_proyecto_monto_anual',
1141    'field_proyecto_total' => 'field_proyecto_total',
1142    'field_proyecto_poan' => 'field_proyecto_poan',
1143  );
1144  $title_combos['db']['identificacion']['title'] = t('Datos Básicos de Identificación del Proyecto');
1145  //Gerente del Proyecto
1146  $arreglo['db']['gerentep'] = array();
1147  $arreglo['db']['gerentep'] = array(
1148    'field_proyecto_ente' => 'field_proyecto_ente',
1149    'field_proyecto_autoridad' => 'field_proyecto_autoridad',
1150    'field_proyecto_lider' => 'field_proyecto_lider',
1151    'field_proyecto_unidad_a' => 'field_proyecto_unidad_a',
1152    'field_proyecto_cargo' => 'field_proyecto_cargo',
1153    'field_proyecto_telefono' => 'field_proyecto_telefono',
1154    'field_proyecto_correo' => 'field_proyecto_correo',
1155  );
1156  $title_combos['db']['gerentep']['title'] = t('Gerente del Proyecto');
1157  //Área Estrategica
1158  $pndes = variable_get('proyectos_operativos_muestra_pndes', TRUE);
1159  $mcti = variable_get('proyectos_operativos_muestra_mcti', TRUE);
1160  $arreglo['db']['areae'] = array();
1161  if ($pndes) {
1162    $arreglo['db']['areae']['field_proyecto_pndes'] = 'field_proyecto_pndes';
1163  }
1164  if ($mcti) {
1165    $arreglo['db']['areae']['field_proyecto_mcti'] = 'field_proyecto_mcti';
1166  }
1167  $title_combos['db']['areae']['title'] = t('Área Estratégica');
1168  //DATOS GENERALES
1169  $title_combos['dg']['title'] = t('Datos Generales');
1170  //Clasificación Sectorial
1171  $arreglo['dg']['sector'] = array();
1172  $arreglo['dg']['sector'] = array(
1173    'field_proyecto_sector' => 'field_proyecto_sector',
1174  );
1175  $title_combos['dg']['sector']['title'] = t('Clasificación Sectorial');
1176  //Talento Humano
1177  $arreglo['dg']['talentoh'] = array();
1178  if (variable_get('proyectos_operativos_muestra_talento', TRUE)) {
1179    $arreglo['dg']['talentoh'] = array(
1180      'field_proyecto_institucionth' => 'field_proyecto_institucionth',
1181      'field_proyecto_nombres_a' => 'field_proyecto_nombres_a',
1182      'field_proyecto_cargo_th' => 'field_proyecto_cargo_th',
1183      'field_proyecto_rol_th' => 'field_proyecto_rol_th',
1184      'field_proyecto_esfuerzo' => 'field_proyecto_esfuerzo',
1185      'field_proyecto_formacion' => 'field_proyecto_formacion',
1186    );
1187  }
1188  $title_combos['dg']['talentoh']['title'] = t('Talento Humano');
1189  //Capacidades
1190  $arreglo['dg']['capacidades'] = array();
1191  if (variable_get('proyectos_operativos_muestra_capacidades', TRUE)) {
1192    $arreglo['dg']['capacidades'] = array(
1193      'field_proyecto_institucion_alc' => 'field_proyecto_institucion_alc',
1194      'field_proyecto_infraestructura' => 'field_proyecto_infraestructura',
1195      'field_proyecto_equipos' => 'field_proyecto_equipos',
1196      'field_proyecto_insumos' => 'field_proyecto_insumos',
1197      'field_proyectos_servicios' => 'field_proyectos_servicios',
1198    );
1199  }
1200  $title_combos['dg']['capacidades']['title'] = t('Capacidades');
1201  //Instituciones
1202  $arreglo['dg']['relacion'] = array();
1203  $arreglo['dg']['relacion'] = array(
1204    'field_proyecto_relacion' => 'field_proyecto_relacion',
1205  );
1206  $title_combos['dg']['relacion']['title'] = t('Instituciones');
1207  //Empleos Generados
1208  $arreglo['dg']['empleosg'] = array();
1209  if (variable_get('proyectos_operativos_muestra_beneficiario', TRUE)) {
1210    $arreglo['dg']['empleosg'] = array(
1211      'field_proyecto_emdirecto' => 'field_proyecto_emdirecto',
1212      'field_proyecto_efdirecto' => 'field_proyecto_efdirecto',
1213    );
1214    if (variable_get('proyectos_operativos_muestra_empleos_indirectos', TRUE)) {
1215      $arreglo['dg']['empleosg']['field_proyecto_emindirecto'] = 'field_proyecto_emindirecto';
1216      $arreglo['dg']['empleosg']['field_proyecto_efindirecto'] = 'field_proyecto_efindirecto';
1217    }
1218  }
1219  $title_combos['dg']['empleosg']['title'] = t('Empleos Generados');
1220  //Objetivos del Proyecto
1221  $arreglo['dg']['objetivosp'] = array();
1222  $arreglo['dg']['objetivosp'] = array(
1223    'field_proyecto_og' => 'field_proyecto_og',
1224    'field_proyecto_oe' => 'field_proyecto_oe',
1225  );
1226  //INDICADORES DEL PROYECTO
1227  //Enunciado del Problema
1228  $title_combos['ip']['title'] = t('Indicadores del Proyecto');
1229  $arreglo['ip']['enunciadop'] = array();
1230  if (variable_get('proyectos_operativos_muestra_enunciado_problema', TRUE)) {
1231    $arreglo['ip']['enunciadop'] = array(
1232      'field_proyecto_causas' => 'field_proyecto_causas',
1233      'field_proyecto_problemas' => 'field_proyecto_problemas',
1234      'field_proyecto_consecuencias' => 'field_proyecto_consecuencias',
1235    );
1236  }
1237  $title_combos['ip']['enunciadop']['title'] = t('Enunciado del Problema');
1238  //Justificación del Proyecto
1239  $arreglo['ip']['justificacion'] = array();
1240  if (variable_get('proyectos_operativos_muestra_justicacion', TRUE)) {
1241    $arreglo['ip']['justificacion'] = array(
1242      'field_proyecto_justificacion' => 'field_proyecto_justificacion',
1243    );
1244  }
1245  $title_combos['ip']['justificacion']['title'] = t('Justificación del Proyecto');
1246  //Alcance del Proyecto
1247  $arreglo['ip']['alcance'] = array();
1248  if (variable_get('proyectos_operativos_muestra_alcance', TRUE)) {
1249    $arreglo['ip']['alcance'] = array(
1250      'field_proyecto_alcance' => 'field_proyecto_alcance',
1251    );
1252  }
1253  $title_combos['ip']['alcance']['title'] = t('Alcance del Proyecto');
1254  //Situación Actual del Proyecto
1255  $arreglo['ip']['situaciona'] = array();
1256  if (variable_get('proyectos_operativos_muestra_sa', TRUE)) {
1257    $arreglo['ip']['situaciona'] = array(
1258      'field_proyecto_sa_descripcion' => 'field_proyecto_sa_descripcion',
1259    );
1260    if (variable_get('proyectos_operativos_muestra_sa_cuantificacion', TRUE)) {
1261      $arreglo['ip']['situaciona']['field_proyecto_sa_cuantificacion'] = 'field_proyecto_sa_cuantificacion';
1262    }
1263    $arreglo['ip']['situaciona']['field_proyecto_sa_formulai'] = 'field_proyecto_sa_formulai';
1264    $arreglo['ip']['situaciona']['field_proyecto_sa_fuentei'] = 'field_proyecto_sa_fuentei';
1265    $arreglo['ip']['situaciona']['field_proyecto_sa_fecha'] = 'field_proyecto_sa_fecha';
1266  }
1267  $title_combos['ip']['situaciona']['title'] = t('Situación Actual');
1268  //Situación Objetivo
1269  $arreglo['ip']['situaciono'] = array();
1270  if (variable_get('proyectos_operativos_muestra_so', TRUE)) {
1271    $arreglo['ip']['situaciono'] = array(
1272      'field_proyecto_so_descripcion' => 'field_proyecto_so_descripcion',
1273      'field_proyecto_so_cuantificacion' => 'field_proyecto_so_cuantificacion',
1274      'field_proyecto_tiempoi' => 'field_proyecto_tiempoi',
1275    );
1276  }
1277  $title_combos['ip']['situaciono']['title'] = t('Situación Objetivo');
1278  //Indicador del resultado del Proyecto
1279  $arreglo['ip']['resultadop'] = array();
1280  $arreglo['ip']['resultadop'] = array(
1281    'field_proyecto_descripcion_bien' => 'field_proyecto_descripcion_bien',
1282    'field_proyecto_unidadm' => 'field_proyecto_unidadm',
1283    'field_proyecto_meta_fisica' => 'field_proyecto_meta_fisica',
1284  );
1285  $title_combos['ip']['resultadop']['title'] = t('Indicador del resultado del Proyecto');
1286  if (!isset($_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid]) || !count($_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid])) {
1287    $campos['todos-los-campos'] = t('Mostrar todos los campos');
1288    //$campos['title'] = t('Nombre del Proyecto');
1289    if (count($fields)) {
1290      foreach($fields as $id => $field) {
1291        if (!$field['display_settings']['full']['exclude']) {
1292          //DATOS BASICOS DEL PROYECTO
1293          //Datos Básicos de Identificación del Proyecto
1294          if (array_key_exists($id,  $arreglo['db']['identificacion'])) {
1295            $arreglo['db']['identificacion'][$id] = $field['widget']['label'];
1296          }
1297          //Gerente del Proyecto
1298          elseif(array_key_exists($id,  $arreglo['db']['gerentep'])) {
1299            $arreglo['db']['gerentep'][$id] = $field['widget']['label'];
1300          }
1301          //Área Estrategica
1302          elseif(array_key_exists($id,  $arreglo['db']['areae'])) {
1303            $arreglo['db']['areae'][$id] = $field['widget']['label'];
1304          }
1305          //DATOS GENERALES
1306          //Clasificación Sectorial
1307          elseif(array_key_exists($id,  $arreglo['dg']['sector'])) {
1308            $arreglo['dg']['sector'][$id] = $field['widget']['label'];
1309          }
1310          //Talento Humano
1311          elseif(array_key_exists($id,  $arreglo['dg']['talentoh'])) {
1312            $arreglo['dg']['talentoh'][$id] = $field['widget']['label'];
1313          }
1314          //Capacidades
1315          elseif(array_key_exists($id,  $arreglo['dg']['capacidades'])) {
1316            $arreglo['dg']['capacidades'][$id] = $field['widget']['label'];
1317          }
1318          //Instituciones
1319          elseif(array_key_exists($id,  $arreglo['dg']['relacion'])) {
1320            $arreglo['dg']['relacion'][$id] = $field['widget']['label'];
1321          }
1322          //Empleos Generados
1323          elseif(array_key_exists($id,  $arreglo['dg']['empleosg'])) {
1324            $arreglo['dg']['empleosg'][$id] = $field['widget']['label'];
1325          }
1326          //Objetivos del Proyecto
1327          elseif(array_key_exists($id,  $arreglo['dg']['objetivosp'])) {
1328            $arreglo['dg']['objetivosp'][$id] = $field['widget']['label'];
1329          }
1330          //INDICADORES DEL PROYECTO
1331          //Enunciado del Problema
1332          elseif(array_key_exists($id,  $arreglo['ip']['enunciadop'])) {
1333            $arreglo['ip']['enunciadop'][$id] = $field['widget']['label'];
1334          }
1335          //Justificación del Proyecto
1336          elseif(array_key_exists($id,  $arreglo['ip']['justificacion'])) {
1337            $arreglo['ip']['justificacion'][$id] = $field['widget']['label'];
1338          }
1339          //Alcance del Proyecto
1340          elseif(array_key_exists($id,  $arreglo['ip']['alcance'])) {
1341            $arreglo['ip']['alcance'][$id] = $field['widget']['label'];
1342          }
1343          //Situación Actual del Proyecto
1344          elseif(array_key_exists($id,  $arreglo['ip']['situaciona'])) {
1345            $arreglo['ip']['situaciona'][$id] = $field['widget']['label'];
1346          }
1347          //Situación Objetivo
1348          elseif(array_key_exists($id,  $arreglo['ip']['situaciono'])) {
1349            $arreglo['ip']['situaciono'][$id] = $field['widget']['label'];
1350          }
1351          //Indicador del resultado del Proyecto
1352          elseif(array_key_exists($id,  $arreglo['ip']['resultadop'])) {
1353            $arreglo['ip']['resultadop'][$id] = $field['widget']['label'];
1354          }
1355          //DATOS BASICOS DEL PROYECTO
1356          //Datos Básicos de Identificación del Proyecto
1357          elseif (variable_get('proyectos_operativos_ac_d_' . $id, FALSE)) {
1358            $arreglo['db']['identificacion'][$id] = $field['widget']['label'];
1359          }
1360          //Gerente del Proyecto
1361          elseif (variable_get('proyectos_operativos_ac_di_' . $id, FALSE)) {
1362            $arreglo['db']['gerentep'][$id] = $field['widget']['label'];
1363          }   
1364          //Área Estrategica     
1365          elseif (variable_get('proyectos_operativos_ac_p_' . $id, FALSE)) {
1366            $arreglo['db']['areae'][$id] = $field['widget']['label'];
1367          }
1368          //DATOS GENERALES
1369          //Clasificación Sectorial
1370          elseif (variable_get('proyectos_operativos_dg_s_' . $id, FALSE)) {
1371            $arreglo['dg']['sector'][$id] = $field['widget']['label'];
1372          }
1373          //Instituciones
1374          elseif (variable_get('proyectos_operativos_dg_r_' . $id, FALSE)) {
1375            $arreglo['dg']['relacion'][$id] = $field['widget']['label'];
1376          }
1377          //Objetivos del Proyecto
1378          elseif (variable_get('proyectos_operativos_dg_o_' . $id, FALSE)) {
1379            $arreglo['dg']['objetivosp'][$id] = $field['widget']['label'];
1380          }
1381          //Enunciado del Problema
1382          elseif (variable_get('proyectos_operativos_ip_in_' . $id, FALSE)) {
1383            $arreglo['ip']['enunciadop'][$id] = $field['widget']['label'];
1384          }
1385          //Alcance del Proyecto
1386          elseif (variable_get('proyectos_operativos_ip_al_' . $id, FALSE)) {
1387            $arreglo['ip']['alcance'][$id] = $field['widget']['label'];
1388          }
1389          //Justificación del Proyecto
1390          elseif (variable_get('proyectos_operativos_ip_ju_' . $id, FALSE)) {
1391            $arreglo['ip']['justificacion'][$id] = $field['widget']['label'];
1392          }
1393          //Situación Actual del Proyecto
1394          elseif (variable_get('proyectos_operativos_ip_sa_' . $id, FALSE)) {
1395            $arreglo['ip']['situaciona'][$id] = $field['widget']['label'];
1396          }
1397          //Situación Objetivo
1398          elseif (variable_get('proyectos_operativos_ip_so_' . $id, FALSE)) {
1399            $arreglo['ip']['situaciono'][$id] = $field['widget']['label'];
1400          }
1401          //Indicador del resultado del Proyecto
1402          elseif (variable_get('proyectos_operativos_ip_re_' . $id, FALSE)) {
1403            $arreglo['ip']['resultadop'][$id] = $field['widget']['label'];
1404          }
1405          //$campos[$id] = $field['widget']['label'];
1406        }
1407        //DATOS BASICOS DEL PROYECTO
1408        //Datos Básicos de Identificación del Proyecto
1409        elseif (array_key_exists($id,  $arreglo['db']['identificacion'])) {
1410          unset($arreglo['db']['identificacion'][$id]);
1411        }
1412        //Gerente del Proyecto
1413        elseif (array_key_exists($id,  $arreglo['db']['gerentep'])) {
1414          unset($arreglo['db']['gerentep'][$id]);
1415        }
1416        //Área Estrategica
1417        elseif (array_key_exists($id,  $arreglo['db']['areae'])) {
1418          unset($arreglo['db']['areae'][$id]);
1419        }
1420        //DATOS GENERALES
1421        //Clasificación Sectorial
1422        elseif (array_key_exists($id,  $arreglo['dg']['sector'])) {
1423          unset($arreglo['dg']['sector'][$id]);
1424        }
1425        //Talento Humano
1426        elseif (array_key_exists($id,  $arreglo['dg']['talentoh'])) {
1427          unset($arreglo['dg']['talentoh'][$id]);
1428        }
1429        //Capacidades
1430        elseif (array_key_exists($id,  $arreglo['dg']['capacidades'])) {
1431          unset($arreglo['dg']['capacidades'][$id]);
1432        }
1433        //Instituciones
1434        elseif (array_key_exists($id,  $arreglo['dg']['relacion'])) {
1435          unset($arreglo['dg']['relacion'][$id]);
1436        }
1437        //Empleos Generados
1438        elseif (array_key_exists($id,  $arreglo['dg']['empleosg'])) {
1439          unset($arreglo['dg']['empleosg'][$id]);
1440        }
1441        //Objetivos del Proyecto
1442        elseif (array_key_exists($id,  $arreglo['dg']['objetivosp'])) {
1443          unset($arreglo['dg']['objetivosp'][$id]);
1444        }
1445        //INDICADORES DEL PROYECTO
1446        //Enunciado del Problema
1447        elseif (array_key_exists($id,  $arreglo['ip']['enunciadop'])) {
1448          unset($arreglo['ip']['enunciadop'][$id]);
1449        }
1450        //Justificación del Proyecto
1451        elseif (array_key_exists($id,  $arreglo['ip']['justificacion'])) {
1452          unset($arreglo['ip']['justificacion'][$id]);
1453        }
1454        //Alcance del Proyecto
1455        elseif (array_key_exists($id,  $arreglo['ip']['alcance'])) {
1456          unset($arreglo['ip']['alcance'][$id]);
1457        }
1458        //Situación Actual del Proyecto
1459        elseif (array_key_exists($id,  $arreglo['ip']['situaciona'])) {
1460          unset($arreglo['ip']['situaciona'][$id]);
1461        }
1462        //Situación Objetivo
1463        elseif (array_key_exists($id,  $arreglo['ip']['situaciono'])) {
1464          unset($arreglo['ip']['situaciono'][$id]);
1465        }
1466        //Indicador del resultado del Proyecto
1467        elseif (array_key_exists($id,  $arreglo['ip']['resultadop'])) {
1468          unset($arreglo['ip']['resultadop'][$id]);
1469        }
1470      }
1471    }
1472
1473    //$campos['proyectos_operativos_flujo'] = t('Flujo de Trabajo');
1474    //DATOS BASICOS DEL PROYECTO
1475
1476
1477    $identificacion = count($arreglo['db']['identificacion']);
1478    $gerentep = count($arreglo['db']['gerentep']);
1479    $areae = count($arreglo['db']['areae']);
1480    if ($identificacion || $gerentep || $areae) {
1481      $form['db'] = array(
1482        '#type' => 'fieldset',
1483        '#title' => t('Datos Básicos'),
1484      );
1485    }
1486    if ($identificacion) {
1487      $form['db']['identificacion'] = array(
1488        '#type' => 'checkboxes',
1489        '#options' => $arreglo['db']['identificacion'],
1490        '#default_value' => array(),
1491        '#title' => t('Datos Básicos de Identificación del Proyecto'),
1492        '#multiple' => TRUE,
1493      );
1494    }
1495    if ($gerentep) {
1496      $form['db']['gerentep'] = array(
1497        '#type' => 'checkboxes',
1498        '#options' => $arreglo['db']['gerentep'],
1499        '#default_value' => array(),
1500        '#title' => t('Gerente del Proyecto'),
1501        '#multiple' => TRUE,
1502      );
1503    }
1504    if ($areae) {
1505      $form['db']['areae'] = array(
1506        '#type' => 'checkboxes',
1507        '#options' => $arreglo['db']['areae'],
1508        '#default_value' => array(),
1509        '#title' => t('Área Estratégica'),
1510        '#multiple' => TRUE,
1511      );
1512    }
1513
1514    //DATOS GENERALES DEL PROYECTO
1515    $sector = count($arreglo['dg']['sector']);
1516    $talentoh = count($arreglo['dg']['talentoh']);
1517    $capacidades = count($arreglo['dg']['capacidades']);
1518    $relacion = count($arreglo['dg']['relacion']);
1519    $objetivosp = count($arreglo['dg']['objetivosp']);
1520    if ($sector || $talentoh || $capacidades || $relacion || $objetivosp) {
1521      $form['dg'] = array(
1522        '#type' => 'fieldset',
1523        '#title' => t('Datos Generales'),
1524      );
1525    }
1526    //Clasificación Sectorial
1527    if ($sector) {
1528      $form['dg']['sector'] = array(
1529        '#type' => 'checkboxes',
1530        '#options' => $arreglo['dg']['sector'],
1531        '#default_value' => array(),
1532        '#title' => t('Clasificación Sectorial'),
1533        '#multiple' => TRUE,
1534      );
1535    }
1536    //Talento Humano
1537    if ($talentoh) {
1538      $form['dg']['talentoh'] = array(
1539        '#type' => 'checkboxes',
1540        '#options' => $arreglo['dg']['talentoh'],
1541        '#default_value' => array(),
1542        '#title' => t('Talento Humano'),
1543        '#multiple' => TRUE,
1544      );
1545    }
1546    //Capacidades
1547    if ($capacidades) {
1548      $form['dg']['capacidades'] = array(
1549        '#type' => 'checkboxes',
1550        '#options' => $arreglo['dg']['capacidades'],
1551        '#default_value' => array(),
1552        '#title' => t('Capacidades'),
1553        '#multiple' => TRUE,
1554      );
1555    }
1556    //Instituciones
1557    if ($relacion) {
1558      $form['dg']['relacion'] = array(
1559        '#type' => 'checkboxes',
1560        '#options' => $arreglo['dg']['relacion'],
1561        '#default_value' => array(),
1562        '#title' => t('Instituciones'),
1563        '#multiple' => TRUE,
1564      );
1565    }
1566    //Objetivos del Proyecto
1567    if ($objetivosp) {
1568      $form['dg']['objetivosp'] = array(
1569        '#type' => 'checkboxes',
1570        '#options' => $arreglo['dg']['objetivosp'],
1571        '#default_value' => array(),
1572        '#title' => t('Objetivos del Proyecto'),
1573        '#multiple' => TRUE,
1574      );
1575    }
1576    //INDICADORES DEL PROYECTO
1577    $enunciadop = count($arreglo['ip']['enunciadop']);
1578    $justificacion = count($arreglo['ip']['justificacion']);
1579    $alcance = count($arreglo['ip']['alcance']);
1580    $situaciona = count($arreglo['ip']['situaciona']);
1581    $situaciono = count($arreglo['ip']['situaciono']);
1582    $resultadop = count($arreglo['ip']['resultadop']);
1583    if ($enunciadop || $justificacion || $alcance || $situaciona || $situaciono || $resultadop) {
1584      $form['ip'] = array(
1585        '#type' => 'fieldset',
1586        '#title' => t('Indicadores del Proyecto'),
1587      );
1588    }
1589    //Enunciado del Problema
1590    if ($enunciadop) {
1591      $form['ip']['enunciadop'] = array(
1592        '#type' => 'checkboxes',
1593        '#options' => $arreglo['ip']['enunciadop'],
1594        '#default_value' => array(),
1595        '#title' => t('Enunciado del Problema'),
1596        '#multiple' => TRUE,
1597      );
1598    }
1599    //Justificación del Proyecto
1600    if ($justificacion) {
1601      $form['ip']['justificacion'] = array(
1602        '#type' => 'checkboxes',
1603        '#options' => $arreglo['ip']['justificacion'],
1604        '#default_value' => array(),
1605        '#title' => t('Justificación del Proyecto'),
1606        '#multiple' => TRUE,
1607      );
1608    }
1609    //Alcance del Proyecto
1610    if ($alcance) {
1611      $form['ip']['alcance'] = array(
1612        '#type' => 'checkboxes',
1613        '#options' => $arreglo['ip']['alcance'],
1614        '#default_value' => array(),
1615        '#title' => t('Alcance del Proyecto'),
1616        '#multiple' => TRUE,
1617      );
1618    }
1619    //Situación Actual del Proyecto
1620    if ($situaciona) {
1621      $form['ip']['situaciona'] = array(
1622        '#type' => 'checkboxes',
1623        '#options' => $arreglo['ip']['situaciona'],
1624        '#default_value' => array(),
1625        '#title' => t('Situación Actual'),
1626        '#multiple' => TRUE,
1627      );
1628    }
1629    //Situación Objetivo
1630    if ($situaciono) {
1631      $form['ip']['situaciono'] = array(
1632        '#type' => 'checkboxes',
1633        '#options' => $arreglo['ip']['situaciono'],
1634        '#default_value' => array(),
1635        '#title' => t('Situación Objetivo'),
1636        '#multiple' => TRUE,
1637      );
1638    }
1639    //Indicador del resultado del Proyecto
1640    if ($resultadop) {
1641      $form['ip']['resultadop'] = array(
1642        '#type' => 'checkboxes',
1643        '#options' => $arreglo['ip']['resultadop'],
1644        '#default_value' => array(),
1645        '#title' => t('Indicador del resultado del Proyecto'),
1646        '#multiple' => TRUE,
1647      );
1648    }
1649    //Acciones especificas
1650    $form['ae'] = array(
1651      '#type' => 'fieldset',
1652      '#title' => t('Acciones Específicas'),
1653    );
1654    $arreglo['ae']['field_proyecto_accion_esp'] = t('Acciones Específicas');
1655    //Indicador del resultado del Proyecto
1656    $form['ae']['accionesesp'] = array(
1657      '#type' => 'checkboxes',
1658      '#options' => $arreglo['ae'],
1659      '#default_value' => array(),
1660      '#title' => t('Acciones Específicas'),
1661      '#multiple' => TRUE,
1662      '#weight' => 99,
1663    );
1664    $title_combos['accionesesp']['title'] = t('Acciones Específicas');
1665
1666
1667    //otros
1668    $form['otros'] = array(
1669      '#type' => 'fieldset',
1670      '#title' => t('Otros'),
1671    );
1672
1673    $arreglo['otros']['proyectos_operativos_flujo'] = t('Flujo de Trabajo');
1674    //Indicador del resultado del Proyecto
1675    $form['otros']['fl'] = array(
1676      '#type' => 'checkboxes',
1677      '#options' => $arreglo['otros'],
1678      '#default_value' => array(),
1679      '#title' => t('Flujo de Trabajo'),
1680      '#multiple' => TRUE,
1681      '#weight' => 99,
1682    );
1683    $title_combos['fl']['title'] = t('Flujo de Trabajo');
1684    $form['#title_combos'] = $title_combos;
1685    //$campos['proyectos_operativos_flujo'] = t('Flujo de Trabajo');
1686/*
1687    $form['proyectos_operativos_campos'] = array(
1688      '#type' => 'checkboxes',
1689      '#options' => $campos,
1690      '#default_value' => array(),
1691      '#title' => t('Campos a mostrar'),
1692      '#multiple' => TRUE,
1693    );
1694*/
1695    $form['buttons'] = array(
1696      '#prefix' => '<div class="container-inline">',
1697      '#suffix' => '</div>',
1698      '#weight' => 100,
1699    );
1700    $form['buttons']['registrar'] = array(
1701      '#type' => 'submit',
1702      '#default_value' => t('Mostrar'),
1703      '#weight' => 100,
1704    );
1705    $form['buttons']['cancelar'] = array(
1706      '#type' => 'submit',
1707      '#default_value' => t('Cancelar'),
1708      '#weight' => 101,
1709      '#attributes' => array('onClick' => 'window.location="' . base_path() .$_GET['q'] . '"; return false;'),
1710      '#skip_validation' => TRUE,
1711    );
1712  }
1713  else {
1714    $form['buttons']['cancelar'] = array(
1715      '#type' => 'submit',
1716      '#default_value' => t('Volver a las opciones de campo'),
1717      '#weight' => 101,
1718      '#skip_validation' => TRUE,
1719    );
1720  }
1721  return $form;
1722}
1723
1724/**
1725 * Implementation of proyectos_operativos_proyecto_genera_campos_form_submit().
1726 * cambia los valores del filtro de campos.
1727 */
1728function proyectos_operativos_proyecto_genera_campos_form_submit($form, &$form_state) {
1729  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1730  if ($op == t('Volver a las opciones de campo')) {
1731    unset($_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid]);
1732    $form_state['redirect'] = 'proyectosop/' . $form['#node']->nid;
1733    return;
1734  }
1735  $_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid]['#values'] = $form_state['values'];
1736  $_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid]['#title_combos'] = $form['#title_combos'];
1737}
1738
1739/**
1740 * Implementation of _proyectos_operativos_proyecto_campos().
1741 * Muestra los campos de un proyecto.
1742 */
1743function _proyectos_operativos_proyecto_campos($node) {
1744  global $user;
1745  drupal_set_title(t('Consultar Datos del Proyecto'));
1746  $current_time = time();
1747  $tipo_plan = 'proyectos_operativos_formular';
1748  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
1749  $fecha = FALSE;
1750  $ente = usuario_tiene_ente($user->uid);
1751  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1752    $fecha = TRUE;
1753  }
1754  if (!$fecha) {
1755    muestra_mensaje($tipo_plan, 2);
1756  }
1757  if ($fecha && $ente->nid) {
1758    muestra_mensaje($tipo_plan, 2, 0);
1759  }
1760  $output = drupal_get_form('proyectos_operativos_proyecto_genera_campos_form', $node);
1761  $views = array();
1762  if (isset($_SESSION['proyectos_operativos_mostrar_campos'][$node->nid]) && count($_SESSION['proyectos_operativos_mostrar_campos'][$node->nid])) {
1763    $content = node_build_content($node);
1764    $datos = $_SESSION['proyectos_operativos_mostrar_campos'][$node->nid]['#values'];
1765    $title_combos = $_SESSION['proyectos_operativos_mostrar_campos'][$node->nid]['#title_combos'];
1766    $valores = array();
1767    foreach($_SESSION['proyectos_operativos_mostrar_campos'][$node->nid]['#values'] as $id => $campos){
1768      if (is_array($campos) && count($campos)) {
1769        foreach($campos as $campo) {
1770          if ($campo) {
1771            $valores[$id][] = $campo;
1772          }
1773        }
1774      }
1775      else {
1776
1777      }
1778     
1779    }
1780    foreach($_SESSION['proyectos_operativos_mostrar_campos'][$node->nid]['#title_combos'] as $id => $campos){
1781      if (isset($valores[$id])) {
1782        $views[$id] = !isset($views[$id]) ? '<fieldset><legend>' . $campos['title'] . '</legend' : $views[$id];
1783        foreach($valores[$id] as $campo) {
1784          if ($campo && isset($content->content[$campo])) {
1785            $views[$id] .= drupal_render($content->content[$campo]);
1786          }
1787          elseif($campo == 'title') {
1788            $views[$id] .= '<h2>' . $node->titulo_asignado . '</h2>';
1789          }
1790        }
1791        $views[$id] .= '</fieldset>';
1792      }
1793      else {
1794        foreach($campos as $id_campo => $campo) {
1795          if (isset($valores[$id_campo])) {
1796            $muestra = TRUE;
1797            $views[$id] = !isset($views[$id]) ? '<fieldset><legend>' . $campos['title'] . '</legend' : $views[$id];
1798            $views[$id] .= '<fieldset><legend>' . $campo['title'] . '</legend';
1799            foreach($valores[$id_campo] as $id_field) {
1800              if ($id_field && isset($content->content[$id_field])) {
1801                $views[$id] .= drupal_render($content->content[$id_field]);
1802              }
1803              elseif($id_field == 'title') {
1804                $views[$id] .= '<h2>' . $node->titulo_asignado . '</h2>';
1805              }
1806            }
1807            $views[$id] .= '</fieldset>';
1808
1809          }
1810        }
1811        if (isset($views[$id])) {
1812          $views[$id] .= '</fieldset>';
1813        }
1814      }
1815   }
1816
1817  }
1818  if (count($views)) {
1819    $output .= implode('', $views);
1820  }
1821  elseif (isset($_SESSION['proyectos_operativos_mostrar_campos'][$node->nid])) {
1822    $output .= '<p>' . t('No ha seleccionado ningún campo que mostrar') . '</p>';
1823  }
1824  return $output;
1825}
1826
1827/**
1828 * Implementation of _proyectos_operativos_reformula_obtiene_estados().
1829 * Obtiene los estados del tipo de contenido proyecto.
1830 */
1831function _proyectos_operativos_reformula_obtiene_estados() {
1832  $estados = array();
1833  $wid = 0;
1834  if (module_exists('workflow')) {
1835    $wid = workflow_get_workflow_for_type('proyectos_operativos');
1836    if ($wid){
1837      $estados = workflow_get_states($wid);
1838    }
1839  }
1840  return array(
1841    'wid' => $wid,
1842    'states' => $estados,
1843  );
1844}
1845
1846/**
1847 * Implementation of proyectos_operativos_search_ac_display().
1848 * Muestra la lista de proyectos disponibles.
1849 */
1850function proyectos_operativos_search_ac_display() {
1851  global $user;
1852  $step = 10;
1853  $current_time = time();
1854  $tipo_plan = 'proyectos_operativos_formular';
1855  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
1856  $fecha = FALSE;
1857  $ente = usuario_tiene_ente($user->uid);
1858  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1859    $fecha = TRUE;
1860  }
1861  if (!$fecha) {
1862    muestra_mensaje($tipo_plan, 2);
1863  }
1864  if ($fecha && $ente->nid) {
1865    muestra_mensaje($tipo_plan, 2, 0);
1866  }
1867  $states = array();
1868  $first_state = 0;
1869  if (module_exists('workflow')) {
1870    $states = _proyectos_operativos_reformula_obtiene_estados();
1871    if ($states['wid']) {
1872      $first_state = _workflow_creation_state($states['wid']);
1873    }
1874  }
1875  $output = drupal_get_form('proyectos_operativos_search_ac_form');
1876  $inputs = array();
1877  $sql = '';
1878  $sql_count = '';
1879  if (!user_access('admin planificador') && $user->entes) {
1880    $inputs[] = $user->entes;
1881    $inputs[] = variable_get('proyectos_operativos_state_naprobado', NULL);
1882    $sql .= "SELECT ac.nid, ac.year, w.sid, n.created, n.title as nombre, u.name, n.uid, e.title AS ente, ctpo.field_proyecto_titulo_value FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid  WHERE ac.ente = %d AND w.sid <> %d";
1883    $sql_count .= "SELECT COUNT(ac.nid) FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid  WHERE ac.ente = %d AND w.sid <> %d";
1884//    $sql .= "SELECT ac.nid, ac.year, w.sid, n.created, n.title as nombre, u.name, n.uid, e.title AS ente FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND w.sid <> %d";
1885  }
1886  elseif (user_access('admin planificador')) {
1887    $inputs[] = variable_get('proyectos_operativos_state_naprobado', NULL);
1888    $sql .= "SELECT ac.nid, ac.year, ac.ente, w.sid, n.created, n.title as nombre,  u.name, n.uid, e.title AS enten, ctpo.field_proyecto_titulo_value FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid  LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid WHERE w.sid <> %d";
1889    $sql_count .= "SELECT COUNT(ac.nid) FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid  LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid WHERE w.sid <> %d";
1890//    $sql .= "SELECT ac.nid, ac.year, ac.ente, w.sid, n.created, n.title as nombre,  u.name, n.uid, e.title AS enten FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE w.sid <> %d";
1891    $proyectos_operativos_search_ac_ente = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ente']) ? $_SESSION['proyectos_operativos']['ente'] : 0;
1892    if ($proyectos_operativos_search_ac_ente) {
1893      $inputs[] = $proyectos_operativos_search_ac_ente;
1894      $sql .= ' AND ac.ente = %d';
1895      $sql_count .= ' AND ac.ente = %d';
1896    }
1897  }
1898  if (isset($user->user_entes_asignados) && count($user->user_entes_asignados)) {
1899    $extra_input = array();
1900    foreach($user->user_entes_asignados as $nid => $title) {
1901      $inputs[] = $nid;
1902      $extra_input[] = '%d';
1903    }
1904    $sql .= ' AND ac.ente IN (' . implode(', ', $extra_input) . ')';
1905    $sql_count .= ' AND ac.ente IN (' . implode(', ', $extra_input) . ')';
1906  }
1907
1908
1909  $proyectos_operativos_search_ac_anho_creacion = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['anho']) ? $_SESSION['proyectos_operativos']['anho'] : 0;
1910  if ($proyectos_operativos_search_ac_anho_creacion) {
1911    $sql .= ' AND ac.year = %d';
1912    $sql_count .= ' AND ac.year = %d';
1913    $inputs[] = $proyectos_operativos_search_ac_anho_creacion;
1914  }
1915  $sql .= ' ORDER BY ac.year DESC, ac.ente';
1916  $header = array();
1917  $cab = 6;
1918  if (user_access('admin planificador')) {
1919    $header[] = array('data' => t('Ente.'));
1920    $cab++;
1921  }
1922  $header[] = array('data' => t('Proyecto'));
1923  $header[] = array('data' => t('Año'));
1924  $header[] = array('data' => t('Estado'));
1925  $header[] = array('data' => t('Fecha de creación'));
1926  $header[] = array('data' => t('Autor'));
1927  $header[] = array('data' => t('Acción'));
1928  $result = pager_query($sql, $step, 0, $sql_count, $inputs);
1929  $rows = array();
1930  while($ac = db_fetch_object($result)) {
1931    $row = array();
1932    $color = variable_get('proyectos_operativos_state_color_' . $ac->sid, array());
1933    if (user_access('admin planificador')) {
1934      $row[] = array('data' => l($ac->enten, 'node/' . $ac->ente), 'style' => 'background:' . $color, );
1935    }
1936    $nombre_proyecto = $ac->field_proyecto_titulo_value ? $ac->field_proyecto_titulo_value : $ac->nombre;
1937    $row[] = array('data' => $nombre_proyecto, 'style' => 'background:' . $color, );
1938//    $row[] = array('data' => $ac->nombre,);
1939    $row[] = array('data' => $ac->year, 'style' => 'background:' . $color, );
1940    $estad0 = $ac->sid == $first_state ? t('Ingresado') : $states['states'][$ac->sid];
1941    $row[] = array('data' => $estad0, 'style' => 'background:' . $color, );
1942    $row[] = array('data' => format_date($ac->created), 'style' => 'background:' . $color, );
1943    $row[] = array('data' => l($ac->name, 'user/' . $ac->uid), 'style' => 'background:' . $color, );
1944    $links = array();
1945    drupal_alter('proyecto_obtiene_links', $links, $ac, $fecha);
1946    $row[] = array('data' => theme('item_list', $links), 'style' => 'background:' . $color, );
1947    $rows[] = $row;
1948  }
1949  if (!count($rows)) {
1950    $row[] = array('data' => t('No existen Proyectos Operativos'), 'colspan' => $cab);
1951    $rows[] = $row;
1952  }
1953  $output .= theme('table', $header, $rows);
1954  $output .= theme('pager', NULL);
1955  if ($fecha) {
1956    $output .= '<p>' . l(t('Agregar proyectos operativos'), 'agregarproyectosop') . '</p>';
1957  }
1958  return $output;
1959}
1960
1961/**
1962 * Implementation of proyectos_operativos_search_ac_display_not_approved().
1963 * Muestra la lista de proyectos disponibles que no han sido aprobados.
1964 */
1965function proyectos_operativos_search_ac_display_not_approved() {
1966  drupal_set_title(t("Consultar Proyectos Operativos sin Aprobar"));
1967  global $user;
1968  $step = 10;
1969  $current_time = time();
1970  $tipo_plan = 'proyectos_operativos_formular';
1971  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
1972  $fecha = FALSE;
1973  $ente = usuario_tiene_ente($user->uid);
1974  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
1975    $fecha = TRUE;
1976  }
1977  if (!$fecha) {
1978    muestra_mensaje($tipo_plan, 2);
1979  }
1980  if ($fecha && $ente->nid) {
1981    muestra_mensaje($tipo_plan, 2, 0);
1982  }
1983  $states = array();
1984  $first_state = 0;
1985  if (module_exists('workflow')) {
1986    $states = _proyectos_operativos_reformula_obtiene_estados();
1987    if ($states['wid']) {
1988      $first_state = _workflow_creation_state($states['wid']);
1989    }
1990  }
1991  $output = drupal_get_form('proyectos_operativos_search_ac_form');
1992  $inputs = array();
1993  $sql = '';
1994  $sql_count = '';
1995  if (!user_access('admin planificador') && $user->entes) {
1996    $inputs[] = $user->entes;
1997    $inputs[] = variable_get('proyectos_operativos_state_naprobado', NULL);
1998    $inputs[] = variable_get('proyectos_operativos_state_aprobado', NULL);
1999    $sql .= "SELECT ac.nid, ac.year, w.sid, n.created, n.title as nombre, u.name, n.uid, e.title AS ente, ctpo.field_proyecto_titulo_value FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid  WHERE ac.ente = %d AND w.sid <> %d AND w.sid <> %d";
2000    $sql_count .= "SELECT COUNT(ac.nid) FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid  WHERE ac.ente = %d AND w.sid <> %d AND w.sid <> %d";
2001//    $sql .= "SELECT ac.nid, ac.year, w.sid, n.created, n.title as nombre, u.name, n.uid, e.title AS ente FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND w.sid <> %d";
2002  }
2003  elseif (user_access('admin planificador')) {
2004    $inputs[] = variable_get('proyectos_operativos_state_naprobado', NULL);
2005    $inputs[] = variable_get('proyectos_operativos_state_aprobado', NULL);
2006    $sql .= "SELECT ac.nid, ac.year, ac.ente, w.sid, n.created, n.title as nombre,  u.name, n.uid, e.title AS enten, ctpo.field_proyecto_titulo_value FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid  LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid WHERE w.sid <> %d AND w.sid <> %d";
2007    $sql_count .= "SELECT COUNT(ac.nid) FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid  LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid WHERE w.sid <> %d AND w.sid <> %d";
2008//    $sql .= "SELECT ac.nid, ac.year, ac.ente, w.sid, n.created, n.title as nombre,  u.name, n.uid, e.title AS enten FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE w.sid <> %d";
2009    $proyectos_operativos_search_ac_ente = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ente']) ? $_SESSION['proyectos_operativos']['ente'] : 0;
2010    if ($proyectos_operativos_search_ac_ente) {
2011      $inputs[] = $proyectos_operativos_search_ac_ente;
2012      $sql .= ' AND ac.ente = %d';
2013      $sql_count .= ' AND ac.ente = %d';
2014    }
2015  }
2016  if (isset($user->user_entes_asignados) && count($user->user_entes_asignados)) {
2017    $extra_input = array();
2018    foreach($user->user_entes_asignados as $nid => $title) {
2019      $inputs[] = $nid;
2020      $extra_input[] = '%d';
2021    }
2022    $sql .= ' AND ac.ente IN (' . implode(', ', $extra_input) . ')';
2023    $sql_count .= ' AND ac.ente IN (' . implode(', ', $extra_input) . ')';
2024  }
2025
2026
2027  $proyectos_operativos_search_ac_anho_creacion = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['anho']) ? $_SESSION['proyectos_operativos']['anho'] : 0;
2028  if ($proyectos_operativos_search_ac_anho_creacion) {
2029    $sql .= ' AND ac.year = %d';
2030    $sql_count .= ' AND ac.year = %d';
2031    $inputs[] = $proyectos_operativos_search_ac_anho_creacion;
2032  }
2033  $sql .= ' ORDER BY ac.year DESC, ac.ente';
2034  $header = array();
2035  $cab = 6;
2036  if (user_access('admin planificador')) {
2037    $header[] = array('data' => t('Ente.'));
2038    $cab++;
2039  }
2040  $header[] = array('data' => t('Proyecto'));
2041  $header[] = array('data' => t('Año'));
2042  $header[] = array('data' => t('Estado'));
2043  $header[] = array('data' => t('Fecha de creación'));
2044  $header[] = array('data' => t('Autor'));
2045  $header[] = array('data' => t('Acción'));
2046  $result = pager_query($sql, $step, 0, $sql_count, $inputs);
2047  $rows = array();
2048  while($ac = db_fetch_object($result)) {
2049    $row = array();
2050    $color = variable_get('proyectos_operativos_state_color_' . $ac->sid, array());
2051    if (user_access('admin planificador')) {
2052      $row[] = array('data' => l($ac->enten, 'node/' . $ac->ente), 'style' => 'background:' . $color, );
2053    }
2054    $nombre_proyecto = $ac->field_proyecto_titulo_value ? $ac->field_proyecto_titulo_value : $ac->nombre;
2055    $row[] = array('data' => $nombre_proyecto, 'style' => 'background:' . $color, );
2056//    $row[] = array('data' => $ac->nombre,);
2057    $row[] = array('data' => $ac->year, 'style' => 'background:' . $color, );
2058    $estad0 = $ac->sid == $first_state ? t('Ingresado') : $states['states'][$ac->sid];
2059    $row[] = array('data' => $estad0, 'style' => 'background:' . $color, );
2060    $row[] = array('data' => format_date($ac->created), 'style' => 'background:' . $color, );
2061    $row[] = array('data' => l($ac->name, 'user/' . $ac->uid), 'style' => 'background:' . $color, );
2062    $links = array();
2063    drupal_alter('proyecto_obtiene_links', $links, $ac, $fecha);
2064    $row[] = array('data' => theme('item_list', $links), 'style' => 'background:' . $color, );
2065    $rows[] = $row;
2066  }
2067  if (!count($rows)) {
2068    $row[] = array('data' => t('No existen Proyectos Operativos'), 'colspan' => $cab);
2069    $rows[] = $row;
2070  }
2071  $output .= theme('table', $header, $rows);
2072  $output .= theme('pager', NULL);
2073  if ($fecha) {
2074    $output .= '<p>' . l(t('Agregar proyectos operativos'), 'agregarproyectosop') . '</p>';
2075  }
2076  return $output;
2077}
2078
2079/**
2080 * Implementation of proyectos_operativos_remove_ac_form()
2081 * Eliminar accion especifica
2082 */
2083function proyectos_operativos_remove_proyectosop_form($form_state, $node = 0) {
2084  $form = array();
2085  $form['#node'] = $node;
2086  $message = t('Esta seguro de eliminar el proyecto operativo @nombre?', array('@nombre' => $form['#node']->titulo_asignado));
2087  $caption = '<p>'. t('This action cannot be undone.') .'</p>';
2088  $return_path = $_REQUEST['destination'] ? $_REQUEST['destination'] : 'proyectos_operativos';
2089  return confirm_form($form, $message, $return_path, $caption, t('Eliminar'));
2090}
2091
2092/**
2093 * Implementation of proyectos_operativos_remove_ac_form_submit().
2094 * Process funcion delete accion especifica.
2095 */
2096function proyectos_operativos_remove_proyectosop_form_submit($form, &$form_state) {
2097  global $user;
2098  $titulo = $form['#node']->titulo_asignado;
2099  $nid = $form['#node']->nid;
2100  node_delete($form['#node']->nid);
2101  $texto = t('Se elimino el proyecto @nombre', array('@nombre' => $form['#node']->titulo_asignado));
2102  drupal_set_message($texto);
2103  if (!$_REQUEST['destination']) {
2104    // add redirect
2105    $form_state['redirect'] = 'proyectos_operativos';
2106  }
2107}
2108
2109/*
2110 * Implementation of hook_acciones_obtiene_links_alter()
2111 */
2112function proyectos_operativos_proyecto_obtiene_links_alter(&$links, $proyecto, $acceso = FALSE) {
2113  $node_accion = node_load($proyecto->nid);
2114  if (node_access('view', $node_accion)){
2115    $links[] = array(
2116      'data' => l(t('Consultar'), 'proyectosop/' . $proyecto->nid),
2117      'class' => 'proyectos-operativos-ver',
2118    );
2119  }
2120  if (_proyectos_operativos_access_editar($node_accion)){
2121    $links[] = array(
2122      'data' => l(t('Modificar'), 'proyectosop/' . $proyecto->nid . '/edit'),
2123      'class' => 'proyectos-operativos-modificar',
2124    );
2125    if (_proyectos_operativos_edita_datos_ae_access($node_accion)) {
2126      $links[] = array(
2127        'data' => l(t('Agregar Acción Específica'), 'proyectosopedit/' . $proyecto->nid . '/ae'),
2128        'class' => 'proyectos-operativos-ae-modificar',
2129      );
2130    }
2131    $links[] = array(
2132      'data' => l(t('Eliminar'), 'proyectosop/' . $proyecto->nid . '/remove'),
2133      'class' => 'proyectos-operativos-eliminar',
2134    );
2135  }
2136  if (_proyectos_operativos_edita_datos_wk_access($node_accion)) {
2137    $links[] = array(
2138      'data' => l(t('Cambiar el estado'), 'proyectosop/' . $proyecto->nid . '/workflow', array('html' => true, 'query' => 'destination=proyectos_operativos')),
2139      'class' => 'proyectos-operativos-estado',
2140    );
2141  }
2142  if (_proyectos_operativos_ver_datos_wk_access($node_accion)) {
2143    $links[] = array(
2144      'data' => l(t('Consultar las Acciones Especificas'), 'proyectosop/' . $proyecto->nid . '/ae'),
2145      'class' => 'proyectos-operativos-ae',
2146    );
2147    $links[] = array(
2148      'data' => l(t('Consultar Datos Financieros'), 'proyectosop/' . $proyecto->nid . '/finacieros'),
2149      'class' => 'proyectos-operativos-finacieros',
2150    );
2151  }
2152}
2153
2154/**
2155 * Implementation of proyectos_operativos_search_ac_form().
2156 * Formulario de busqueda de proyecto.
2157 */
2158function proyectos_operativos_search_ac_form($form_state) {
2159  global $user;
2160  $form = array();
2161  if (user_access('admin planificador')) {
2162    $entes = array();
2163    $sql = 'SELECT e.nid, n.title FROM {ente_planificador} AS e INNER JOIN {node} AS n ON n.nid = e.nid WHERE n.status = %d';
2164    $entes[0] = t('Todos');
2165    $inputs = array();
2166    $inputs[] = 1;
2167    if (isset($user->user_entes_asignados) && count($user->user_entes_asignados)) {
2168      $extra_input = array();
2169      foreach ($user->user_entes_asignados as $nid => $title) {
2170        $inputs[] = $nid;
2171        $extra_input[] = '%d';
2172      }
2173      $sql .= ' AND e.nid IN(' . implode(', ', $extra_input) . ')';
2174    }
2175    $result = db_query($sql, $inputs);
2176    while ($ente = db_fetch_object($result)) {
2177      $entes[$ente->nid] = $ente->title;
2178    }
2179    $proyectos_operativos_search_ac_ente = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ente']) ? $_SESSION['proyectos_operativos']['ente'] : 0;
2180    $form['proyectos_operativos_search_ac_ente'] = array(
2181      '#title' => t('Ente Planificador'),
2182      '#type' => 'select',
2183      '#default_value' => $proyectos_operativos_search_ac_ente,
2184      '#options' => $entes,
2185    );
2186  }
2187  $years = array();
2188  $years[0] = t('Todos');
2189  $current_year = date("Y");
2190  for ($i = $current_year - 10; $i <= $current_year; $i++) {
2191    $years[$i] = $i;
2192  }
2193  $proyectos_operativos_search_ac_anho_creacion = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['anho']) ? $_SESSION['proyectos_operativos']['anho'] : 0;
2194  $form['proyectos_operativos_search_ac_anho_creacion'] = array(
2195    '#title' => t('Proyectos Operativos para el año'),
2196    '#type' => 'select',
2197    '#default_value' => $proyectos_operativos_search_ac_anho_creacion,
2198    '#options' => $years,
2199  );
2200  $form['buttons'] = array(
2201    '#prefix' => '<div class="container-inline">',
2202    '#suffix' => '</div>',
2203  );
2204  $form['buttons']['submit'] = array(
2205    '#type' => 'submit',
2206    '#value' => t('Buscar'),
2207  );
2208  return $form;
2209}
2210
2211/**
2212 * Implementation of proyectos_operativos_search_ac_form_submit().
2213 * cambia el filtro de busqueda de proyectos.
2214 */
2215function proyectos_operativos_search_ac_form_submit($form, &$form_state) {
2216  $_SESSION['proyectos_operativos'] = array();
2217  if (user_access('admin planificador')) {
2218    $_SESSION['proyectos_operativos']['ente'] = $form_state['values']['proyectos_operativos_search_ac_ente'];
2219  }
2220  $_SESSION['proyectos_operativos']['anho'] = $form_state['values']['proyectos_operativos_search_ac_anho_creacion'];
2221}
2222
2223/*
2224 * Implementation of hook_perm
2225 */
2226function proyectos_operativos_perm() {
2227  return array(
2228    'editar datos institucionales de mi ente',
2229  );
2230}
2231
2232/**
2233 * Implementation of proyectosop_load().
2234 * Leer un proyecto operativo.
2235 */
2236function proyectosop_load($nid = 0) {
2237  if ($nid && is_numeric($nid)) {
2238    $node_load = node_load($nid);
2239    if ($node_load && $node_load->type == 'proyectos_operativos') {
2240      return $node_load;
2241    }
2242  }
2243  return FALSE;
2244}
2245
2246/**
2247 * Implementation of accion_especifical_load().
2248 * Leer una accion especifica.
2249 */
2250function accion_especifical_load($nid = 0) {
2251  if ($nid && is_numeric($nid)) {
2252    $node_load = node_load($nid);
2253    if ($node_load && $node_load->type == 'accion_especifica') {
2254      return $node_load;
2255    }
2256  }
2257  return FALSE;
2258}
2259
2260/**
2261 * Implementation of _proyectos_operativos_proyecto_agregar_proyecto().
2262 * Agregar un nuevo proyecto.
2263 */
2264function _proyectos_operativos_proyecto_agregar_proyecto() {
2265  $output = '';
2266  $output .= drupal_get_form('proyectos_operativos_proyecto_basico_form');
2267  return $output;
2268}
2269
2270/**
2271 * Implementation of proyectos_operativos_proyecto_basico_form().
2272 * Formulario de datos basicos (proyectos operativos).
2273 */
2274function proyectos_operativos_proyecto_basico_form(&$form_state, $proyecto = 0) {
2275  global $user;
2276  $current_time = time();
2277  $tipo_plan = 'proyectos_operativos_formular';
2278  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
2279  $fecha = FALSE;
2280  $ente = usuario_tiene_ente($user->uid);
2281  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2282    $fecha = TRUE;
2283  }
2284  if (!$fecha) {
2285    muestra_mensaje($tipo_plan, 2);
2286  }
2287  if ($fecha && $ente->nid) {
2288    muestra_mensaje($tipo_plan, 2, 0);
2289  }
2290  $fechas_validacion = array(
2291    'inicio' => '',
2292    'fin' => '',
2293  );
2294  $montos_asignados = 0;
2295  $acciones_especificas = array();
2296  $porcentajes = array();
2297  $ejecucion = 0;
2298  if (!$proyecto) {
2299    $proyecto_leido = new stdClass();
2300    $proyecto_leido->type = 'proyectos_operativos';
2301    $proyecto_leido->title = '';
2302  }
2303  else {
2304    $proyecto_leido = $proyecto;
2305    $proyecto_leido->field_proyecto_titulo[0]['value'] = trim($proyecto_leido->field_proyecto_titulo[0]['value']) == '' ? $proyecto_leido->title : $proyecto_leido->field_proyecto_titulo[0]['value'];
2306
2307    if (isset($proyecto->field_proyecto_accion_esp)){
2308      foreach ($proyecto->field_proyecto_accion_esp as $accion) {
2309        if ($accion['nid']) {
2310          $accion_load = node_load($accion['nid']);
2311          if ($accion_load && ($fechas_validacion['inicio'] == '' || $accion_load->field_accion_esp_fechai[0]['value'] < $fechas_validacion['inicio'])) {
2312            $fechas_validacion['inicio'] = $accion_load->field_accion_esp_fechai[0]['value'];
2313          }
2314          if ($accion_load && ($fechas_validacion['fin'] == '' || $accion_load->field_accion_esp_fechaf[0]['value'] > $fechas_validacion['fin'])) {
2315            $fechas_validacion['fin'] = $accion_load->field_accion_esp_fechaf[0]['value'];
2316          }
2317          if ($accion_load && $accion_load->type == 'accion_especifica') {
2318            if ($accion_load->field_accion_esp_programacion[0]['tid']) {
2319              foreach ($accion_load->field_accion_esp_programacion as $programacion) {
2320                foreach ($programacion as $id_value => $mesp){
2321                  if ($id_value != 'tid') {
2322                    $montos_asignados +=$mesp;
2323                  }
2324                }
2325              }
2326            }
2327            $acciones_especificas[$accion_load->nid] = $accion_load;
2328            $porcentajes[$accion_load->field_accion_esp_ponderacion[0]['value']] = 1;
2329            $ejecucion += $accion_load->field_accion_esp_ponderacion[0]['value'];
2330          }
2331        }
2332      }
2333    }
2334  }
2335  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
2336  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
2337  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos2.js');
2338  $form = array();
2339  $fechas_validacion['fin_texto'] = '';
2340  $fechas_validacion['inicio_texto'] = '';
2341  if ($fechas_validacion['inicio']) {
2342    $f_aux = explode(' ', $fechas_validacion['inicio']);
2343    $f_aux = explode('-', $f_aux[0]);
2344    $fechas_validacion['inicio_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2345    $fechas_validacion['inicio_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2346    $f_aux = explode(' ', $proyecto_leido->field_proyecto_fecha_i[0]['value']);
2347    $f_aux = explode('-', $f_aux[0]);
2348    $fechas_validacion['inicio_current_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2349    $fechas_validacion['inicio_current_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2350  }
2351  if ($fechas_validacion['fin']) {
2352    $f_aux = explode(' ', $fechas_validacion['fin']);
2353    $f_aux = explode('-', $f_aux[0]);
2354    $fechas_validacion['fin_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2355    $fechas_validacion['fin_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2356    $f_aux = explode(' ', $proyecto_leido->field_proyecto_fecha_f[0]['value']);
2357    $f_aux = explode('-', $f_aux[0]);
2358    $fechas_validacion['fin_current_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2359    $fechas_validacion['fin_current_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2360  }
2361  $format_number = array(
2362    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2363    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2364    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2365  );
2366  $form['#format_number'] = array('format_number' => $format_number);
2367  drupal_add_js($form['#format_number'], 'setting');
2368
2369  $form['#fechas_validacion'] = $fechas_validacion;
2370  $form['#montos_asignados'] = $montos_asignados;
2371  $form['#count_ae'] = count($acciones_especificas);
2372  $node_type = content_types('proyectos_operativos');
2373  $fields = $node_type['fields'];
2374  $form['#proyecto_fields'] = $fields;
2375  $form['#proyecto_anho'] = variable_get('proyectos_operativos_anho_creacion', 0) ? variable_get('proyectos_operativos_anho_creacion', 0) : date("Y");
2376  $field_form = array();
2377  $fields_form = array();
2378  $fields_form_ac_d = array();
2379  $arreglo = array(
2380    'field_proyecto_titulo' => 'field_proyecto_titulo',
2381    'field_proyecto_codigo' => 'field_proyecto_codigo',
2382    'field_proyecto_codigo_n_etap' => 'field_proyecto_codigo_n_etap',
2383    'field_proyecto_fecha_i' => 'field_proyecto_fecha_i',
2384    'field_proyecto_fecha_f' => 'field_proyecto_fecha_f',
2385    'field_proyecto_status' => 'field_proyecto_status',
2386    'field_proyecto_situacion_p' => 'field_proyecto_situacion_p',
2387    'field_proyecto_plurianual' => 'field_proyecto_plurianual',
2388    'field_proyecto_monto_anual' => 'field_proyecto_monto_anual',
2389    'field_proyecto_total' => 'field_proyecto_total',
2390    'field_proyecto_poan' => 'field_proyecto_poan',
2391  );
2392  if (is_array($fields) && count($fields)) {
2393    foreach ($fields as $field_id => $field) {
2394      if (array_key_exists($field_id, $arreglo)) {
2395        $field_form[] = $field_id;
2396        $fields_form[] = $field_id;
2397      }
2398      elseif (variable_get('proyectos_operativos_ac_d_' . $field_id, FALSE)) {
2399        $fields_form_ac_d[$field_id] = $field_id;
2400        $field_form[] = $field_id;
2401        $fields_form[] = $field_id;
2402      }
2403    }
2404  }
2405/*
2406  $form['title'] = array(
2407    '#type' => 'textfield',
2408    '#title' => t('Nombre del Proyecto'),
2409    '#required' => TRUE,
2410    '#default_value' => $proyecto_leido->title,
2411    '#maxlength' => 511,
2412    '#weight' => -5,
2413  );
2414*/
2415  $form['#node'] = $proyecto_leido;
2416  if (is_array($field_form) && count($field_form)) {
2417    module_load_include('inc', 'content', 'includes/content.node_form');
2418    foreach ($field_form as $field_id) {
2419      $field = content_fields($field_id, 'proyectos_operativos');
2420      $form['#field_info'][$field_id] = $field;
2421      $form += (array) content_field_form($form, $form_state, $field);
2422    }
2423  }
2424  $field_form = array();
2425  $arreglo = array(
2426    'field_proyecto_ente' => 'field_proyecto_ente',
2427    'field_proyecto_autoridad' => 'field_proyecto_autoridad',
2428    'field_proyecto_lider' => 'field_proyecto_lider',
2429    'field_proyecto_unidad_a' => 'field_proyecto_unidad_a',
2430    'field_proyecto_cargo' => 'field_proyecto_cargo',
2431    'field_proyecto_telefono' => 'field_proyecto_telefono',
2432    'field_proyecto_correo' => 'field_proyecto_correo',
2433  );
2434  $fields_form_ac_di = array();
2435  if (is_array($fields) && count($fields)) {
2436    foreach ($fields as $field_id => $field) {
2437      if (array_key_exists($field_id, $arreglo)) {
2438        $field_form[] = $field_id;
2439        $fields_form[] = $field_id;
2440      }
2441      elseif (variable_get('proyectos_operativos_ac_di_' . $field_id, FALSE)) {
2442        $fields_form_ac_di[$field_id] = $field_id;
2443        $field_form[] = $field_id;
2444        $fields_form[] = $field_id;
2445      }
2446    }
2447  }
2448  if (is_array($field_form) && count($field_form)) {
2449    module_load_include('inc', 'content', 'includes/content.node_form');
2450    foreach ($field_form as $field_id) {
2451      $field = content_fields($field_id, 'proyectos_operativos');
2452      $form['#field_info'][$field_id] = $field;
2453      $form += (array) content_field_form($form, $form_state, $field);
2454    }
2455  }
2456  $field_form = array();
2457  if (variable_get('proyectos_operativos_muestra_pndes', TRUE)) {
2458    $arreglo['field_proyecto_pndes'] = 'field_proyecto_pndes';
2459  }
2460  if (variable_get('proyectos_operativos_muestra_mcti', TRUE)) {
2461    $arreglo['field_proyecto_mcti'] = 'field_proyecto_mcti';
2462  }
2463  $fields_form_ac_p = array();
2464  if (is_array($fields) && count($fields)) {
2465    foreach ($fields as $field_id => $field) {
2466      if (array_key_exists($field_id, $arreglo)) {
2467        $field_form[] = $field_id;
2468        $fields_form[] = $field_id;
2469      }
2470      elseif (variable_get('proyectos_operativos_ac_p_' . $field_id, FALSE)) {
2471        $fields_form_ac_p[$field_id] = $field_id;
2472        $field_form[] = $field_id;
2473        $fields_form[] = $field_id;
2474      }
2475    }
2476  }
2477  if (is_array($field_form) && count($field_form)) {
2478    module_load_include('inc', 'content', 'includes/content.node_form');
2479    foreach ($field_form as $field_id) {
2480      $field = content_fields($field_id, 'proyectos_operativos');
2481      $form['#field_info'][$field_id] = $field;
2482      $form += (array) content_field_form($form, $form_state, $field);
2483    }
2484  }
2485  $form['#fields_form_ac_d'] = $fields_form_ac_d;
2486  $form['#fields_form_ac_di'] = $fields_form_ac_di;
2487  $form['#fields_form_ac_p'] = $fields_form_ac_p;
2488
2489
2490
2491  $form['#proyectos_operativos_fields'] = $fields_form;
2492  $form['buttons'] = array(
2493    '#prefix' => '<div class="container-inline">',
2494    '#suffix' => '</div>',
2495  );
2496  $form['buttons']['registrar'] = array(
2497    '#type' => 'submit',
2498    '#default_value' => t('Aceptar'),
2499    '#weight' => 100,
2500  );
2501  $form['buttons']['cancelar'] = array(
2502    '#type' => 'submit',
2503    '#default_value' => t('Cancelar'),
2504    '#attributes' => array('onClick' => 'window.location="' . base_path() .$_GET['q'] . '"; return false;'),
2505    '#weight' => 101,
2506  );
2507  $form['#submit'] = array('proyectos_operativos_proyecto_basico_form_submit');
2508  return $form;
2509}
2510
2511/*
2512 * Implementation of proyectos_operativos_proyecto_basico_form_validate()
2513 * Validar formulario de datos basicos (proyectos operativos).
2514 */
2515function proyectos_operativos_proyecto_basico_form_validate($form, &$form_state) {
2516  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
2517  if ($op == t('Cancelar')) {
2518    return;
2519  }
2520  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
2521  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
2522  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos2.js');
2523  //drupal_add_js($form['#format_number'], 'setting');
2524  $form_state['values']['field_proyecto_monto_anual'][0]['value'] = str_replace("", $form['#format_number']['format_number']['thousands_sep'], $form_state['values']['field_proyecto_monto_anual'][0]['value']);
2525  $form_state['values']['field_proyecto_monto_anual'][0]['value'] = str_replace(".", $form['#format_number']['format_number']['dec_point'], $form_state['values']['field_proyecto_monto_anual'][0]['value']);
2526  $form_state['values']['field_proyecto_total'][0]['value'] = str_replace("", $form['#format_number']['format_number']['thousands_sep'], $form_state['values']['field_proyecto_total'][0]['value']);
2527  $form_state['values']['field_proyecto_total'][0]['value'] = str_replace(".", $form['#format_number']['format_number']['dec_point'], $form_state['values']['field_proyecto_total'][0]['value']);
2528
2529  // garantizar el formato numerico y no exponencial con numeros grandes
2530  $form_state['values']['field_proyecto_monto_anual'][0]['value'] = number_format($form_state['values']['field_proyecto_monto_anual'][0]['value'], $form['#format_number']['format_number']['decimals'], '.', '');
2531  $form_state['values']['field_proyecto_total'][0]['value'] = number_format($form_state['values']['field_proyecto_total'][0]['value'], $form['#format_number']['format_number']['decimals'], '.', '');
2532  if (trim($form_state['values']['field_proyecto_correo'][0]['email']) && !valid_email_address(trim($form_state['values']['field_proyecto_correo'][0]['email']))) {
2533    form_set_error('field_proyecto_correo', t('"%mail" is not a valid email address',array('%mail' => $form_state['values']['field_proyecto_correo'][0]['email'])));
2534  }
2535  if ($form_state['values']['field_proyecto_monto_anual'][0]['value'] <= 0) {
2536    form_set_error('field_proyecto_monto_anual', t('El monto anual del proyecto no puede ser negativo o cero'));
2537  }
2538  $start = $form_state['values']['field_proyecto_total'][0]['value'];
2539  $value = preg_replace('@[^-0-9]@', '', $start);
2540  if ($start != $value) {
2541    form_set_error('field_proyecto_total', t('Solo números enteros son permitidos en el monto anual del proyecto.'));
2542  }
2543  $start = $form_state['values']['field_proyecto_monto_anual'][0]['value'];
2544  $value = preg_replace('@[^-0-9]@', '', $start);
2545  if ($start != $value) {
2546    form_set_error('field_proyecto_monto_anual', t('Solo números enteros son permitidos en el monto total del proyecto'));
2547  }
2548  if ($form['#count_ae'] && $form['#montos_asignados'] > $value) {
2549    form_set_error('field_proyecto_monto_anual', t('El monto anual del proyecto (@monto_proyecto Bs.) es inferior al asignado a las Acciones Específicas (@monto_asignado Bs.)', array('@monto_proyecto' => number_format($value, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']), '@monto_asignado' => number_format($form['#montos_asignados'], $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']))));
2550  }
2551  if ($form_state['values']['field_proyecto_total'][0]['value'] <= 0) {
2552    form_set_error('field_proyecto_total', t('El monto anual del proyecto no puede ser negativo o cero'));
2553  }
2554  if ($form_state['values']['field_proyecto_monto_anual'][0]['value'] > $form_state['values']['field_proyecto_total'][0]['value']) {
2555    form_set_error('field_proyecto_monto_anual', t('El monto anual debe ser menor o igual al monto total del proyecto'));
2556  }
2557  //lamentablemente date no valida que from sea menor que to
2558  if ($form_state['values']['field_proyecto_fecha_i'][0]['value'] > $form_state['values']['field_proyecto_fecha_f'][0]['value']) {
2559    form_set_error('field_proyecto_fecha_i', t('La fecha de inicio debe ser menor a la fecha de culminación'));
2560  }
2561  if ($form_state['values']['field_proyecto_plurianual'][0]['value'] == 'NO' && $form_state['values']['field_proyecto_total'][0]['value'] != $form_state['values']['field_proyecto_monto_anual'][0]['value']) {
2562    form_set_error('field_proyecto_monto_anual', t('Cuando un proyecto no es plurianual, el monto total debe ser igual al monto anual del proyecto'));
2563  }
2564  //validamos el añofield_proyecto_plurianual
2565  $fecha = explode('-', $form_state['values']['field_proyecto_fecha_i'][0]['value']);
2566  if (is_array($fecha) && count($fecha)) {
2567    if ($form['#proyecto_anho'] != $fecha[0]) {
2568      form_set_error('field_proyecto_fecha_i',t('El año de inicio del proyecto debe ser igual a @year', array('@year' => $form['#proyecto_anho'])));
2569    }
2570  }
2571  if ($form['#count_ae'] && $form['#fechas_validacion']['inicio'] < $form_state['values']['field_proyecto_fecha_i'][0]['value']) {
2572    $fecha_dia = explode(' ', $fecha[2]);
2573    form_set_error('field_proyecto_fecha_i',t('La fecha de inicio del proyecto (@fecha_inicio) es mayor a la menor fecha de inicio de las Acciones Específicas (@fecha_aei)', array('@fecha_inicio' => $fecha_dia[0] . '-' . $fecha[1] . '-' . $fecha[0], '@fecha_aei' => $form['#fechas_validacion']['inicio_texto'])));
2574  }
2575  $fecha = explode('-', $form_state['values']['field_proyecto_fecha_f'][0]['value']);
2576  if (is_array($fecha) && count($fecha)) {
2577    if ($form['#proyecto_anho'] != $fecha[0]) {
2578      form_set_error('field_proyecto_fecha_f',t('El año de finalización del debe ser igual a @year', array('@year' => $form['#proyecto_anho'])));
2579    }
2580  }
2581  if ($form['#count_ae'] && $form['#fechas_validacion']['fin'] > $form_state['values']['field_proyecto_fecha_f'][0]['value']) {
2582    $fecha_dia = explode(' ', $fecha[2]);
2583    form_set_error('field_proyecto_fecha_f',t('La fecha de culminación del proyecto (@fecha_inicio) es menor a la menor fecha de inicio de las Acciones Específicas (@fecha_aei)', array('@fecha_inicio' => $fecha_dia[0] . '-' . $fecha[1] . '-' . $fecha[0], '@fecha_aei' => $form['#fechas_validacion']['fin_texto'])));
2584  }
2585}
2586
2587/*
2588 * Implementation of proyectos_operativos_proyecto_basico_form_submit().
2589 * Guardar formulario de datos basicos (proyectos operativos).
2590 */
2591function proyectos_operativos_proyecto_basico_form_submit($form, &$form_state) {
2592  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
2593  if ($op == t('Cancelar')) {
2594    drupal_set_message(t('Se cancelo el ingreso de los datos básicos del proyecto.'));
2595    if ($form['#node']->nid) {
2596      $form_state['redirect'] = 'proyectosopedit/' . $form['#node']->nid;
2597    }
2598    else {
2599      $form_state['redirect'] = 'proyectos_operativos';
2600    }
2601    return;
2602  }
2603  global $user;
2604  if (module_exists('hs_content_taxonomy')) {
2605    foreach ($form['#field_info'] as $field_name => $field_info) {
2606      if ($field_info['widget']['type'] == 'content_taxonomy_hs') {
2607        // Change format of values to the one Content Taxonomy expects
2608        if (is_array($form_state['values'][$field_name]['tids'])) {
2609          $values = array();
2610          foreach($form_state['values'][$field_name]['tids'] as $tid) {
2611            $values[] = array('value' => $tid);
2612            array_unshift($form_state['values'][$field_name], array('value' => $tid));
2613          }
2614          $form_state['values'][$field_name]['tids'] = $values;
2615        }
2616        else {
2617          $values[] = array('value' => $form_state['values'][$field_name]['tids']);
2618          array_unshift($form_state['values'][$field_name],array('value' => $form_state['values'][$field_name]['tids']));
2619          $form_state['values'][$field_name]['tids'] = $values;
2620        }
2621      }
2622    }
2623  }
2624  if (module_exists('hs_content_taxonomy_description')) {
2625    foreach ($form['#field_info'] as $field_name => $field_info) {
2626      if ($field_info['widget']['type'] == 'content_taxonomy_hsd') {
2627        // Change format of values to the one Content Taxonomy expects
2628        if (is_array($form_state['values'][$field_name]['tids'])) {
2629          $values = array();
2630          foreach($form_state['values'][$field_name]['tids'] as $tid) {
2631            $values[] = array('value' => $tid);
2632            array_unshift($form_state['values'][$field_name], array('value' => $tid));
2633          }
2634          $form_state['values'][$field_name]['tids'] = $values;
2635        }
2636        else {
2637          $values[] = array('value' => $form_state['values'][$field_name]['tids']);
2638          array_unshift($form_state['values'][$field_name],array('value' => $form_state['values'][$field_name]['tids']));
2639          $form_state['values'][$field_name]['tids'] = $values;
2640        }
2641      }
2642    }
2643  }
2644  $field_form = $form['#proyectos_operativos_fields'];
2645  module_load_include('inc', 'node', 'node.pages');
2646  $node_load = $form['#node'];
2647  $form_values = $form_state['values'];
2648  //$node_load->title = check_plain($form_values['title']);
2649  if (is_array($field_form) && count($field_form)) {
2650    foreach ($field_form as $field_id) {
2651      if (isset($form_values[$field_id]) && is_array($form_values[$field_id])) {
2652        foreach($form_values[$field_id] as $id => $value) {
2653          if (is_numeric($id) && isset($form_values[$field_id][$id]['_error_element'])) {
2654            unset($form_values[$field_id][$id]['_error_element']);
2655          }
2656        }
2657        $node_load->{$field_id} = $form_values[$field_id];
2658      }
2659    }
2660  }
2661  $node_load->title = $node_load->field_proyecto_codigo[0]['value'] && trim($node_load->field_proyecto_codigo[0]['value']) != '' ? check_plain($node_load->field_proyecto_codigo[0]['value']) : 'proyecto';
2662  if ($node_load->nid) {
2663    $texto = t('Modificados los datos básicos del proyecto');
2664    $node_load->log = $texto;
2665    drupal_set_message($texto);
2666  }
2667  else {
2668    $node_load->uid = $user->uid;
2669    $texto = t('Agregados los datos básicos del proyecto');
2670    $node_load->log = t('Agregados los datos básicos del proyecto');
2671    drupal_set_message($texto);
2672  }
2673  $node_load->revision = 1;
2674  node_save($node_load);
2675  if ($_REQUEST['destination']) {
2676    $form_state['redirect'] = url('proyectosopedit/' . $node_load->nid . '/generales',
2677      array(
2678        'query' => array(
2679          'destination' => $_REQUEST['destination'],
2680         ),
2681         'absolute' => TRUE,               
2682      )
2683    );
2684    unset($_REQUEST['destination']);
2685  }
2686  else {
2687    // add redirect
2688    $form_state['redirect'] = 'proyectosopedit/' . $node_load->nid . '/generales';
2689  }
2690}
2691
2692/**
2693 * Implementation of proyectos_operativos_proyecto_generales_form().
2694 * Formulario de datos generales (proyectos operativos).
2695 */
2696function proyectos_operativos_proyecto_generales_form(&$form_state, $proyecto = 0) {
2697  global $user;
2698  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
2699  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
2700  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_generales.js');
2701  $format_number = array(
2702    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
2703    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
2704    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
2705  );
2706  $current_time = time();
2707  $tipo_plan = 'proyectos_operativos_formular';
2708  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
2709  $fecha = FALSE;
2710  $ente = usuario_tiene_ente($user->uid);
2711  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2712    $fecha = TRUE;
2713  }
2714  if (!$fecha) {
2715    muestra_mensaje($tipo_plan, 2);
2716  }
2717  if ($fecha && $ente->nid) {
2718    muestra_mensaje($tipo_plan, 2, 0);
2719  }
2720  if (!$proyecto) {
2721    $proyecto_leido = new stdClass();
2722    $proyecto_leido->type = 'proyectos_operativos';
2723  }
2724  else {
2725    $proyecto_leido = $proyecto;
2726    if (isset($proyecto->field_proyecto_accion_esp)){
2727      foreach($proyecto->field_proyecto_accion_esp as $accion) {
2728        if ($accion['nid']) {
2729          $accion_load = node_load($accion['nid']);
2730          if ($accion_load && ($fechas_validacion['inicio'] == '' || $accion_load->field_accion_esp_fechai[0]['value'] < $fechas_validacion['inicio'])) {
2731            $fechas_validacion['inicio'] = $accion_load->field_accion_esp_fechai[0]['value'];
2732          }
2733          if ($accion_load && ($fechas_validacion['fin'] == '' || $accion_load->field_accion_esp_fechaf[0]['value'] > $fechas_validacion['fin'])) {
2734            $fechas_validacion['fin'] = $accion_load->field_accion_esp_fechaf[0]['value'];
2735          }
2736          if ($accion_load && $accion_load->type == 'accion_especifica') {
2737            if ($accion_load->field_accion_esp_programacion[0]['tid']) {
2738              foreach($accion_load->field_accion_esp_programacion as $programacion) {
2739                foreach($programacion as $id_value => $mesp){
2740                  if ($id_value != 'tid') {
2741                    $montos_asignados +=$mesp;
2742                  }
2743                }
2744              }
2745            }
2746            $acciones_especificas[$accion_load->nid] = $accion_load;
2747            $porcentajes[$accion_load->field_accion_esp_ponderacion[0]['value']] = 1;
2748            $ejecucion += $accion_load->field_accion_esp_ponderacion[0]['value'];
2749          }
2750        }
2751      }
2752    }
2753  }
2754  $fechas_validacion['fin_texto'] = '';
2755  $fechas_validacion['inicio_texto'] = '';
2756  if ($fechas_validacion['inicio']) {
2757    $f_aux = explode(' ', $fechas_validacion['inicio']);
2758    $f_aux = explode('-', $f_aux[0]);
2759    $fechas_validacion['inicio_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2760    $fechas_validacion['inicio_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2761    $f_aux = explode(' ', $proyecto_leido->field_proyecto_fecha_i[0]['value']);
2762    $f_aux = explode('-', $f_aux[0]);
2763    $fechas_validacion['inicio_current_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2764    $fechas_validacion['inicio_current_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2765  }
2766  if ($fechas_validacion['fin']) {
2767    $f_aux = explode(' ', $fechas_validacion['fin']);
2768    $f_aux = explode('-', $f_aux[0]);
2769    $fechas_validacion['fin_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2770    $fechas_validacion['fin_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2771    $f_aux = explode(' ', $proyecto_leido->field_proyecto_fecha_f[0]['value']);
2772    $f_aux = explode('-', $f_aux[0]);
2773    $fechas_validacion['fin_current_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
2774    $fechas_validacion['fin_current_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
2775  }
2776  $form = array();
2777  $form['#fechas_validacion'] = $fechas_validacion;
2778  $form['#montos_asignados'] = $montos_asignados;
2779  $form['#count_ae'] = count($acciones_especificas);
2780  $form['#node'] = $proyecto_leido;
2781  $node_type = content_types('proyectos_operativos');
2782  $fields = $node_type['fields'];
2783  $form['#proyecto_fields'] = $fields;
2784  $form['#proyecto_anho'] = variable_get('proyectos_operativos_anho_creacion', 0) ? variable_get('proyectos_operativos_anho_creacion', 0) : date("Y");
2785  $field_form = array();
2786  $fields_form = array();
2787  $fields_extra_form = array();
2788  $arreglo = array(
2789    'field_proyecto_sector' => 'field_proyecto_sector',
2790  );
2791  $fields_form_dg_se = array();
2792  if (is_array($fields) && count($fields)) {
2793    foreach($fields as $field_id => $field) {
2794      if (array_key_exists($field_id, $arreglo)) {
2795        $field_form[] = $field_id;
2796        $fields_form[] = $field_id;
2797      }
2798      elseif (variable_get('proyectos_operativos_dg_se_' . $field_id, FALSE)) {
2799        $fields_form_dg_se[$field_id] = $field_id;
2800        $field_form[] = $field_id;
2801        $fields_form[] = $field_id;
2802      }
2803    }
2804  }
2805  if (is_array($field_form) && count($field_form)) {
2806    module_load_include('inc', 'content', 'includes/content.node_form');
2807    foreach ($field_form as $field_id) {
2808      $field = content_fields($field_id, 'proyectos_operativos');
2809      $form['#field_info'][$field_id] = $field;
2810      $form += (array) content_field_form($form, $form_state, $field);
2811    }
2812  }
2813  $arreglo = array(
2814    'field_proyecto_emdirecto' => 'field_proyecto_emdirecto',
2815    'field_proyecto_efdirecto' => 'field_proyecto_efdirecto',
2816  );
2817  if (variable_get('proyectos_operativos_muestra_empleos_indirectos', TRUE)) {
2818    $arreglo['field_proyecto_emindirecto'] = 'field_proyecto_emindirecto';
2819    $arreglo['field_proyecto_efindirecto'] = 'field_proyecto_efindirecto';
2820
2821  }
2822  if (is_array($fields) && count($fields)) {
2823    foreach($fields as $field_id => $field) {
2824      if (array_key_exists($field_id, $arreglo)) {
2825        $field_form[] = $field_id;
2826        $fields_form[] = $field_id;
2827      }
2828    }
2829  }
2830  if (is_array($field_form) && count($field_form)) {
2831    module_load_include('inc', 'content', 'includes/content.node_form');
2832    foreach ($field_form as $field_id) {
2833      $field = content_fields($field_id, 'proyectos_operativos');
2834      $form['#field_info'][$field_id] = $field;
2835      $form += (array) content_field_form($form, $form_state, $field);
2836    }
2837  }
2838  if (variable_get('proyectos_operativos_muestra_talento', TRUE)) {
2839    $arreglo = array(
2840      'field_proyecto_institucionth' => 'field_proyecto_institucionth',
2841      'field_proyecto_nombres_a' => 'field_proyecto_nombres_a',
2842      'field_proyecto_cargo_th' => 'field_proyecto_cargo_th',
2843      'field_proyecto_rol_th' => 'field_proyecto_rol_th',
2844      'field_proyecto_esfuerzo' => 'field_proyecto_esfuerzo',
2845      'field_proyecto_formacion' => 'field_proyecto_formacion',
2846    );
2847    $form['talento'] = array(
2848      '#type' => 'fieldset',
2849      '#title' => t('Talento Humano'),
2850    );
2851    $prefixC = '';
2852    $fields_extra_form1 = array();
2853    foreach($arreglo as $field_id => $field) {
2854      $fields_extra_form1[] = $field_id;
2855      $prefixC .= '<th>' . $fields[$field_id]['widget']['label'] . '</th>';
2856    }
2857    $fields_extra_form['talento'] = $fields_extra_form1;
2858    $tamano_array = array();
2859    foreach($arreglo as $field_id => $field) {
2860      $tamano_array[] = count($proyecto_leido->{$field_id});
2861    }
2862    $cantidad_talento = max($tamano_array);
2863    for ($i = 0; $i < $cantidad_talento; $i++) {
2864      $prefix = '';
2865      if ($i == 0) {
2866        $prefix = '<div id="talento-humano-modificar"><table><tr>' . $prefixC . '</tr><tr><td>';
2867      }
2868      else {
2869        $prefix .= '<tr><td>';
2870      }
2871      $aux = '';
2872      $aui = '';
2873      foreach($arreglo as $field_id => $field) {
2874        $valor_d = ($field_id == 'field_proyecto_esfuerzo') ? 0 : '';
2875        $form['talento'][$field_id . '_' . $i] = array(
2876          '#type' => 'textfield',
2877          '#default_value' => isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : $valor_d,
2878          '#size' => 25,
2879          '#maxlength' => $fields[$field_id]['max_length'],
2880          '#prefix' => $prefix,
2881          '#suffix' => '</td>',
2882        );
2883        if ($field_id == 'field_proyecto_esfuerzo') {
2884          $form['talento'][$field_id . '_' . $i]['#element_validate'] = array('proyectos_operativos_number_integer_validate2',);
2885        }
2886        $aux = $field_id;
2887        $aui = $i;
2888        $prefix = '<td>';
2889      }
2890      $form['talento'][$aux . '_' . $aui]['#suffix'] .= '</tr>';
2891    }
2892    $form['talento'][$aux . '_' . $aui]['#suffix'] .= '</table>';
2893    $form['talento']['cantidad_talento'] = array('#type' => 'hidden', '#value' => $cantidad_talento, '#suffix' => '</div>');
2894    $form['talento']['agrega_' . 'talento'] = array(
2895      '#type' => 'submit',
2896      '#default_value' => t('Agregar otro campo'),
2897      '#weight' => 100,
2898      '#ahah' => array(
2899        'path' => 'proyectos_operativos_proyecto_generales_agrega_talento_js_util/talento',
2900        'wrapper' => 'talento-humano-modificar',
2901        'method' => 'replace',
2902        'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
2903      ),
2904    );
2905  }
2906  if (variable_get('proyectos_operativos_muestra_capacidades', TRUE)) {
2907    $arreglo = array(
2908      'field_proyecto_institucion_alc' => 'field_proyecto_institucion_alc',
2909      'field_proyecto_infraestructura' => 'field_proyecto_infraestructura',
2910      'field_proyecto_equipos' => 'field_proyecto_equipos',
2911      'field_proyecto_insumos' => 'field_proyecto_insumos',
2912      'field_proyectos_servicios' => 'field_proyectos_servicios',
2913    );
2914    $form['capacidades'] = array(
2915      '#type' => 'fieldset',
2916      '#title' => t('Capacidades'),
2917    );
2918    $prefixC = '';
2919    $fields_extra_form1 = array();
2920    $tamano_array = array();
2921    foreach($arreglo as $field_id => $field) {
2922      $tamano_array[] = count($proyecto_leido->{$field_id});
2923    }
2924    $cantidad_capacidades = max($tamano_array);
2925    foreach($arreglo as $field_id => $field) {
2926      $fields_extra_form1[] = $field_id;
2927      $prefixC .= '<th>' . $fields[$field_id]['widget']['label'] . '</th>';
2928    }
2929    $fields_extra_form['capacidades'] = $fields_extra_form1;
2930    for ($i = 0; $i < $cantidad_capacidades; $i++) {
2931      $prefix = '';
2932      if ($i == 0) {
2933        $prefix = '<div id="capacidades-modificar"><table><tr>' . $prefixC . '</tr><tr><td>';
2934      }
2935      else {
2936        $prefix .= '<tr><td>';
2937      }
2938      $aux = '';
2939      $aui = '';
2940      foreach($arreglo as $field_id => $field) {
2941        $form['capacidades'][$field_id . '_' . $i] = array(
2942          '#type' => 'textfield',
2943          '#default_value' => isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : '',
2944          '#size' => 25,
2945          '#maxlength' => $fields[$field_id]['max_length'],
2946          '#prefix' => $prefix,
2947          '#suffix' => '</td>',
2948        );
2949        $aux = $field_id;
2950        $aui = $i;
2951        $prefix = '<td>';
2952      }
2953      $form['capacidades'][$aux . '_' . $aui]['#suffix'] .= '</tr>';
2954    }
2955    $form['capacidades'][$aux . '_' . $aui]['#suffix'] .= '</table>';
2956    $form['capacidades']['cantidad_capacidades'] = array('#type' => 'hidden', '#value' => $cantidad_capacidades, '#suffix' => '</div>');
2957    $form['capacidades']['agrega_' . 'capacidades'] = array(
2958      '#type' => 'submit',
2959      '#default_value' => t('Agregar otro campo'),
2960      '#weight' => 100,
2961      '#ahah' => array(
2962        'path' => 'proyectos_operativos_proyecto_generales_agrega_talento_js_util/capacidades',
2963        'wrapper' => 'capacidades-modificar',
2964        'method' => 'replace',
2965        'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
2966      ),
2967    );
2968  }
2969  $field_form = array();
2970  $arreglo = array(
2971    'field_proyecto_relacion' => 'field_proyecto_relacion',
2972  );
2973  $fields_form_dg_r = array();
2974  if (is_array($fields) && count($fields)) {
2975    foreach($fields as $field_id => $field) {
2976      if (array_key_exists($field_id, $arreglo)) {
2977        $field_form[] = $field_id;
2978        $fields_form[] = $field_id;
2979      }
2980      elseif (variable_get('proyectos_operativos_dg_r_' . $field_id, FALSE)) {
2981        $fields_form_dg_r[$field_id] = $field_id;
2982        $field_form[] = $field_id;
2983        $fields_form[] = $field_id;
2984      }
2985    }
2986  }
2987  if (is_array($field_form) && count($field_form)) {
2988    module_load_include('inc', 'content', 'includes/content.node_form');
2989    foreach ($field_form as $field_id) {
2990      $field = content_fields($field_id, 'proyectos_operativos');
2991      $form['#field_info'][$field_id] = $field;
2992      $form += (array) content_field_form($form, $form_state, $field);
2993    }
2994  }
2995  if (variable_get('proyectos_operativos_muestra_beneficiario', TRUE)) {
2996    $arreglo = array(
2997      'field_proyecto_beneficiario' => 'field_proyecto_beneficiario',
2998      'field_proyectos_masculino_d' => 'field_proyectos_masculino_d',
2999      'field_proyectos_femenino_d' => 'field_proyectos_femenino_d',
3000    );
3001    if (variable_get('proyectos_operativos_muestra_beneficiarios_indirectos', TRUE)) {
3002      $arreglo['field_proyectos_masculino_i'] = 'field_proyectos_masculino_i';
3003      $arreglo['field_proyectos_femenino_i'] = 'field_proyectos_femenino_i';
3004    }
3005
3006
3007    $form['beneficiario'] = array(
3008      '#type' => 'fieldset',
3009      '#title' => t('Beneficiario'),
3010    );
3011    $prefixC = '';
3012    $fields_extra_form1 = array();
3013    foreach($arreglo as $field_id => $field) {
3014      $fields_extra_form1[] = $field_id;
3015      $prefixC .= '<th>' . $fields[$field_id]['widget']['label'] . '</th>';
3016    }
3017    $prefixC .= '<th>' . t('Total') . '</th>';
3018    $fields_extra_form['beneficiario'] = $fields_extra_form1;
3019    $totales = 0;
3020    $total_arreglo = array();
3021    $sumas['beneficiarios'] = array();
3022    $vid = variable_get('proyectos_operativos_extra_bene', 0);
3023    //$terms = taxonomy_get_tree($vid);
3024    $tree = taxonomy_get_tree($vid);
3025    $options = array();
3026    $options[''] = t('Seleccionar');
3027    if ($tree) {
3028      foreach ($tree as $term) {
3029        $options[$term->name] = $term->name;
3030      }
3031    }
3032    $tamano_array = array();
3033    foreach($arreglo as $field_id => $field) {
3034      $tamano_array[] = count($proyecto_leido->{$field_id});
3035    }
3036    $cantidad_beneficiario = max($tamano_array);
3037    for ($i = 0; $i < $cantidad_beneficiario; $i++) {
3038      $subtotal = 0;
3039      $prefix = '';
3040      if ($i == 0) {
3041        $prefix = '<div id="beneficiario-modificar"><table align="center"><tr>' . $prefixC . '</tr><tr><td>';
3042      }
3043      else {
3044        $prefix .= '<tr><td>';
3045      }
3046      $aux = '';
3047      $aui = '';
3048      foreach($arreglo as $field_id => $field) {
3049        $valor = isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : '';
3050        if ($field_id == 'field_proyecto_beneficiario') {
3051          $form['beneficiario'][$field_id . '_' . $i] = array(
3052            '#type' => 'select',
3053            '#default_value' => $valor,
3054            '#options' => $options,
3055            '#prefix' => $prefix,
3056            '#suffix' => '</td>',
3057          );
3058        }
3059        else {
3060          $form['beneficiario'][$field_id . '_' . $i] = array(
3061            '#type' => 'textfield',
3062            '#default_value' => $valor,
3063            '#size' => 10,
3064            '#maxlength' => $fields[$field_id]['max_length'],
3065            '#prefix' => $prefix,
3066            '#suffix' => '</td>',
3067          );
3068        }
3069        if ($field_id != 'field_proyecto_beneficiario') {
3070          if (!isset($total_arreglo[$field_id])) {
3071            $total_arreglo[$field_id] = 0;
3072          }
3073          $subtotal += (int) $valor;
3074          $totales += (int) $valor;
3075          $total_arreglo[$field_id] += (int) $valor;
3076          $sumas['beneficiarios']['beneficiario_' . $i] = 'beneficiario_' . $i;
3077          $form['beneficiario'][$field_id . '_' . $i]['#element_validate'] = array('proyectos_operativos_number_integer_validate2',);
3078          $form['beneficiario'][$field_id . '_' . $i]['#attributes'] = array('class' => 'number beneficiario_' . $i . ' todosbeneficiarios beneficiarios_' . $field_id, 'onchange' => "sumabeneficiario('beneficiario_$i');sumabeneficiario('todosbeneficiarios');sumabeneficiario('beneficiarios_$field_id');");
3079        }
3080        $aux = $field_id;
3081        $aui = $i;
3082        $prefix = '<td align="center">';
3083      }
3084      $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiario_' . $i . '_total">' . $subtotal . '</div></td>';
3085      $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '</tr>';
3086    }
3087    $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<tr align="right"><td><b>' . t('TOTAL') . '</b></td>';
3088    foreach($arreglo as $field_id => $field) {
3089      if ($field_id != 'field_proyecto_beneficiario') {
3090        $sumas['beneficiarios']['beneficiarios_' . $field_id] = 'beneficiarios_' . $field_id;
3091        $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiarios_' . $field_id . '_total">' . $total_arreglo[$field_id] . '</div></td>';
3092      }
3093    }
3094    $sumas['beneficiarios']['todosbeneficiarios'] = 'todosbeneficiarios';
3095    $sumas['beneficiarios']['empleos_generados'] = 'empleos_generados';
3096    drupal_add_js($sumas, 'setting');
3097    $form['#sumas'] = $sumas;
3098    $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="todosbeneficiarios_total">' . $totales . '</div></td></tr>';
3099    $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '</table>';
3100    $form['beneficiario']['cantidad_beneficiario'] = array('#type' => 'hidden', '#value' => $cantidad_beneficiario, '#suffix' => '</div>');
3101    $form['beneficiario']['agrega_' . 'beneficiario'] = array(
3102      '#type' => 'submit',
3103      '#default_value' => t('Agregar otro campo'),
3104      '#weight' => 100,
3105      '#ahah' => array(
3106        'path' => 'proyectos_operativos_proyecto_generales_agrega_talento_js_util/beneficiario',
3107        'wrapper' => 'beneficiario-modificar',
3108        'method' => 'replace',
3109        'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
3110      ),
3111    );
3112  }
3113  $field_form = array();
3114  $arreglo = array(
3115    'field_proyecto_og' => 'field_proyecto_og',
3116    'field_proyecto_oe' => 'field_proyecto_oe',
3117  );
3118  $fields_form_dg_o = array();
3119  if (is_array($fields) && count($fields)) {
3120    foreach($fields as $field_id => $field) {
3121      if (array_key_exists($field_id, $arreglo)) {
3122        $field_form[] = $field_id;
3123        $fields_form[] = $field_id;
3124      }
3125      elseif (variable_get('proyectos_operativos_dg_o_' . $field_id, FALSE)) {
3126        $fields_form_dg_o[$field_id] = $field_id;
3127        $field_form[] = $field_id;
3128        $fields_form[] = $field_id;
3129      }
3130    }
3131  }
3132  $form['#format_number'] = array('format_number' => $format_number);
3133  drupal_add_js($form['#format_number'], 'setting');
3134  $form['#proyectos_operativos_fields_extra'] = $fields_extra_form;
3135  $form['#fields_form_dg_o'] = $fields_form_dg_o;
3136  $form['#fields_form_dg_se'] = $fields_form_dg_se;
3137  $form['#fields_form_dg_r'] = $fields_form_dg_r;
3138  $form['#proyectos_operativos_fields_extra'] = $fields_extra_form;
3139  $form['#proyectos_operativos_fields'] = $fields_form;
3140  if (is_array($field_form) && count($field_form)) {
3141    module_load_include('inc', 'content', 'includes/content.node_form');
3142    foreach ($field_form as $field_id) {
3143      $field = content_fields($field_id, 'proyectos_operativos');
3144      $form['#field_info'][$field_id] = $field;
3145      $form += (array) content_field_form($form, $form_state, $field);
3146    }
3147  }
3148  $form['buttons'] = array(
3149    '#prefix' => '<div class="container-inline">',
3150    '#suffix' => '</div>',
3151  );
3152  $form['buttons']['registrar'] = array(
3153    '#type' => 'submit',
3154    '#default_value' => t('Aceptar'),
3155    '#weight' => 100,
3156  );
3157  $form['buttons']['cancelar'] = array(
3158    '#type' => 'submit',
3159    '#default_value' => t('Cancelar'),
3160    '#attributes' => array('onClick' => 'window.location="' . base_path() .$_GET['q'] . '"; return false;'),
3161    '#weight' => 101,
3162  );
3163  $form['#submit'] = array('proyectos_operativos_proyecto_generales_form_submit');
3164  return $form;
3165}
3166
3167/**
3168 * Implementation of proyectos_operativos_number_integer_validate2().
3169 * Validar si el dato suministrado es un entero.
3170 */
3171function proyectos_operativos_number_integer_validate2($element, &$form_state) {
3172  $start = $element['#value'];
3173  $value = preg_replace('@[^-0-9]@', '', $start);
3174  if ($start != $value) {
3175    $fielda = explode('_', $element['#name']);
3176    $i = array_pop($fielda);
3177    $field = implode('_', $fielda);
3178    form_set_error($field . '_' . $i, t('Solo números enteros son permitidos'));
3179  }
3180}
3181
3182
3183/**
3184 * Implementation of proyectos_operativos_proyecto_generales_form_validate().
3185 * Validar formulario de datos generales (proyectos operativos).
3186 */
3187function proyectos_operativos_proyecto_generales_form_validate($form, &$form_state) {
3188  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
3189  if ($op == t('Cancelar')) {
3190    return;
3191  }
3192  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
3193  drupal_add_js($form['#format_number'], 'setting');
3194  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
3195  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_generales.js');
3196  drupal_add_js($form['#sumas'], 'setting');
3197  if (count($form['#proyectos_operativos_fields_extra'])) {
3198    foreach($form['#proyectos_operativos_fields_extra'] as $id => $arreglo) {
3199      $all_null = TRUE;
3200      $cantidad = $form_state['values']['cantidad_' . $id];
3201      for($i = 0; $i < $cantidad; $i++) {
3202        $null = TRUE;
3203        $first_campo = FALSE;
3204        foreach($arreglo as $campo) {
3205          if (!$first_campo) {
3206            $first_campo = $campo;
3207          }
3208          if ($form_state['values'][$campo . '_' . $i] && trim($form_state['values'][$campo . '_' . $i]) != '') {
3209            $all_null = FALSE;
3210            $null = FALSE;
3211          }
3212          if ($campo == 'field_proyecto_esfuerzo' || $campo == 'field_proyectos_masculino_d' || $campo == 'field_proyectos_masculino_i' || $campo == 'field_proyectos_femenino_d' || $campo == 'field_proyectos_femenino_i') {
3213            $start = $form_state['values'][$campo . '_' . $i];
3214            $value = (int) $start;
3215            if ($start != $value) {
3216              form_set_error($campo . '_' . $i, t('Solo números enteros son permitidos en el campo %field.' . $start, array('%field' => t($form['#proyecto_fields'][$campo]['widget']['label']))));
3217            }
3218            elseif ($value < 0) {
3219              form_set_error($campo . '_' . $i, t('Solo números enteros positivos son permitidos en el campo %field.' . $start, array('%field' => t($form['#proyecto_fields'][$campo]['widget']['label']))));
3220            }
3221          }
3222        }
3223        if (!$null) {
3224          foreach($arreglo as $campo) {
3225            if (trim($form_state['values'][$campo . '_' . $i]) == '') {
3226              form_set_error($campo . '_' . $i, t('El campo @campo_name no puede estar vacio', array('@campo_name' => $form['#proyecto_fields'][$campo]['widget']['label'])));
3227            }
3228          }
3229        }
3230      }
3231      if ($all_null) {
3232        form_set_error($first_campo . '_0', t('Debe llenar al menos un campo'));
3233      }
3234    }
3235  }
3236}
3237
3238/**
3239 * Implementation of proyectos_operativos_proyecto_generales_form_submit().
3240 * Guardar formulario de datos generales (proyectos operativos).
3241 */
3242function proyectos_operativos_proyecto_generales_form_submit($form, &$form_state) {
3243  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
3244  if ($op == t('Cancelar')) {
3245    drupal_set_message(t('Se cancelo el ingreso de los datos generales del proyecto.'));
3246    $form_state['redirect'] = 'proyectosopedit/' . $form['#node']->nid;
3247    return;
3248  }
3249  if (module_exists('hs_content_taxonomy')) {
3250    foreach ($form['#field_info'] as $field_name => $field_info) {
3251      if ($field_info['widget']['type'] == 'content_taxonomy_hs') {
3252        // Change format of values to the one Content Taxonomy expects
3253        if (is_array($form_state['values'][$field_name]['tids'])) {
3254          $values = array();
3255          foreach($form_state['values'][$field_name]['tids'] as $tid) {
3256            $values[] = array('value' => $tid);
3257            array_unshift($form_state['values'][$field_name], array('value' => $tid));
3258          }
3259          $form_state['values'][$field_name]['tids'] = $values;
3260        }
3261        else {
3262          $values[] = array('value' => $form_state['values'][$field_name]['tids']);
3263          array_unshift($form_state['values'][$field_name],array('value' => $form_state['values'][$field_name]['tids']));
3264          $form_state['values'][$field_name]['tids'] = $values;
3265        }
3266      }
3267    }
3268  }
3269  $field_form = $form['#proyectos_operativos_fields'];
3270  module_load_include('inc', 'node', 'node.pages');
3271  $node_load = $form['#node'];
3272  if (count($form['#proyectos_operativos_fields_extra'])) {
3273    foreach($form['#proyectos_operativos_fields_extra'] as $id => $arreglo) {
3274      foreach($arreglo as $campo) {
3275        $node_load->{$campo} = array();
3276      }
3277      $all_null = TRUE;
3278      $cantidad = $form_state['values']['cantidad_' . $id];
3279      for($i = 0; $i < $cantidad; $i++) {
3280        $null = TRUE;
3281        $first_campo = FALSE;
3282        foreach($arreglo as $campo) {
3283          if (!$first_campo) {
3284            $first_campo = $campo;
3285          }
3286          if (trim($form_state['values'][$campo . '_' . $i]) != '') {
3287            $all_null = FALSE;
3288            $null = FALSE;
3289          }
3290        }
3291        if (!$null) {
3292          foreach($arreglo as $campo) {
3293            $node_load->{$campo}[] = array('value' => trim($form_state['values'][$campo . '_' . $i]));
3294          }
3295        }
3296      }
3297    }
3298  }
3299  $form_values = $form_state['values'];
3300  if (is_array($field_form) && count($field_form)) {
3301    foreach ($field_form as $field_id) {
3302      if (isset($form_values[$field_id]) && is_array($form_values[$field_id])) {
3303        foreach($form_values[$field_id] as $id => $value) {
3304          if (is_numeric($id) && isset($form_values[$field_id][$id]['_error_element'])) {
3305            unset($form_values[$field_id][$id]['_error_element']);
3306          }
3307        }
3308        $node_load->{$field_id} = $form_values[$field_id];
3309      }
3310    }
3311  }
3312  if ($node_load->nid) {
3313    $texto = t('Modificados los datos generales del proyecto');
3314    $node_load->log = $texto;
3315    drupal_set_message($texto);
3316  }
3317  else {
3318    $texto = t('Agregados los datos generales del proyecto');
3319    $node_load->log = $texto;
3320    drupal_set_message($texto);
3321  }
3322  $node_load->revision = 1;
3323  node_save($node_load);
3324  if ($_REQUEST['destination']) {
3325    $form_state['redirect'] = url('proyectosopedit/' . $node_load->nid . '/indicadores',
3326      array(
3327        'query' => array(
3328          'destination' => $_REQUEST['destination'],
3329         ),
3330         'absolute' => TRUE,               
3331      )
3332    );
3333    unset($_REQUEST['destination']);
3334  }
3335  else {
3336    // add redirect
3337    $form_state['redirect'] = 'proyectosopedit/' . $node_load->nid . '/indicadores';
3338  }
3339}
3340
3341/**
3342 * Implementation of proyectos_operativos_proyecto_indicadores_form().
3343 * Formulario de indicadores (proyectos operativos).
3344 */
3345function proyectos_operativos_proyecto_indicadores_form(&$form_state, $proyecto = 0) {
3346  global $user;
3347  $current_time = time();
3348  $tipo_plan = 'proyectos_operativos_formular';
3349  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
3350  $fecha = FALSE;
3351  $ente = usuario_tiene_ente($user->uid);
3352  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
3353    $fecha = TRUE;
3354  }
3355  if (!$fecha) {
3356    muestra_mensaje($tipo_plan, 2);
3357  }
3358  if ($fecha && $ente->nid) {
3359    muestra_mensaje($tipo_plan, 2, 0);
3360  }
3361  if (!$proyecto) {
3362    $proyecto_leido = new stdClass();
3363    $proyecto_leido->type = 'proyectos_operativos';
3364  }
3365  else {
3366    $proyecto_leido = $proyecto;
3367    if (isset($proyecto->field_proyecto_accion_esp)){
3368      foreach($proyecto->field_proyecto_accion_esp as $accion) {
3369        if ($accion['nid']) {
3370          $accion_load = node_load($accion['nid']);
3371          if ($accion_load && ($fechas_validacion['inicio'] == '' || $accion_load->field_accion_esp_fechai[0]['value'] < $fechas_validacion['inicio'])) {
3372            $fechas_validacion['inicio'] = $accion_load->field_accion_esp_fechai[0]['value'];
3373          }
3374          if ($accion_load && ($fechas_validacion['fin'] == '' || $accion_load->field_accion_esp_fechaf[0]['value'] > $fechas_validacion['fin'])) {
3375            $fechas_validacion['fin'] = $accion_load->field_accion_esp_fechaf[0]['value'];
3376          }
3377          if ($accion_load && $accion_load->type == 'accion_especifica') {
3378            if ($accion_load->field_accion_esp_programacion[0]['tid']) {
3379              foreach($accion_load->field_accion_esp_programacion as $programacion) {
3380                foreach($programacion as $id_value => $mesp){
3381                  if ($id_value != 'tid') {
3382                    $montos_asignados +=$mesp;
3383                  }
3384                }
3385              }
3386            }
3387            $acciones_especificas[$accion_load->nid] = $accion_load;
3388            $porcentajes[$accion_load->field_accion_esp_ponderacion[0]['value']] = 1;
3389            $ejecucion += $accion_load->field_accion_esp_ponderacion[0]['value'];
3390          }
3391        }
3392      }
3393    }
3394  }
3395  $fechas_validacion['fin_texto'] = '';
3396  $fechas_validacion['inicio_texto'] = '';
3397  if ($fechas_validacion['inicio']) {
3398    $f_aux = explode(' ', $fechas_validacion['inicio']);
3399    $f_aux = explode('-', $f_aux[0]);
3400    $fechas_validacion['inicio_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
3401    $fechas_validacion['inicio_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
3402    $f_aux = explode(' ', $proyecto_leido->field_proyecto_fecha_i[0]['value']);
3403    $f_aux = explode('-', $f_aux[0]);
3404    $fechas_validacion['inicio_current_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
3405    $fechas_validacion['inicio_current_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
3406  }
3407  if ($fechas_validacion['fin']) {
3408    $f_aux = explode(' ', $fechas_validacion['fin']);
3409    $f_aux = explode('-', $f_aux[0]);
3410    $fechas_validacion['fin_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
3411    $fechas_validacion['fin_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
3412    $f_aux = explode(' ', $proyecto_leido->field_proyecto_fecha_f[0]['value']);
3413    $f_aux = explode('-', $f_aux[0]);
3414    $fechas_validacion['fin_current_texto'] = $f_aux[2] . '-' . $f_aux[1] . '-' . $f_aux[0];
3415    $fechas_validacion['fin_current_time'] = mktime(0, 0, 0, $f_aux[1], $f_aux[2], $f_aux[0]);
3416  }
3417  $form = array();
3418  $form['#fechas_validacion'] = $fechas_validacion;
3419  $form['#montos_asignados'] = $montos_asignados;
3420  $form['#count_ae'] = count($acciones_especificas);
3421  $form['#node'] = $proyecto_leido;
3422  $node_type = content_types('proyectos_operativos');
3423  $fields = $node_type['fields'];
3424  $field_form = array();
3425  $fields_form = array();
3426  if (variable_get('proyectos_operativos_muestra_enunciado_problema', TRUE)) {
3427    $arreglo = array(
3428      'field_proyecto_causas' => 'field_proyecto_causas',
3429      'field_proyecto_problemas' => 'field_proyecto_problemas',
3430      'field_proyecto_consecuencias' => 'field_proyecto_consecuencias',
3431    );
3432    $fields_form_ip_in = array();
3433    if (is_array($fields) && count($fields)) {
3434      foreach($fields as $field_id => $field) {
3435        if (array_key_exists($field_id, $arreglo)) {
3436          $field_form[] = $field_id;
3437          $fields_form[] = $field_id;
3438        }
3439        elseif (variable_get('proyectos_operativos_ip_in_' . $field_id, FALSE)) {
3440          $fields_form_ip_in[$field_id] = $field_id;
3441          $field_form[] = $field_id;
3442          $fields_form[] = $field_id;
3443        }
3444      }
3445    }
3446    $form['#datos_institucionales_fields_datos1'] = $field_form;
3447    if (is_array($field_form) && count($field_form)) {
3448      module_load_include('inc', 'content', 'includes/content.node_form');
3449      foreach ($field_form as $field_id) {
3450        $field = content_fields($field_id, 'proyectos_operativos');
3451        $form['#field_info'][$field_id] = $field;
3452        $form += (array) content_field_form($form, $form_state, $field);
3453      }
3454    }
3455  }
3456  if (variable_get('proyectos_operativos_muestra_justicacion', TRUE)) {
3457    $field_form = array();
3458    $arreglo = array(
3459      'field_proyecto_justificacion' => 'field_proyecto_justificacion',
3460    );
3461    $fields_form_ip_ju = array();
3462    if (is_array($fields) && count($fields)) {
3463      foreach($fields as $field_id => $field) {
3464        if (array_key_exists($field_id, $arreglo)) {
3465          $field_form[] = $field_id;
3466          $fields_form[] = $field_id;
3467        }
3468        elseif (variable_get('proyectos_operativos_ip_ju_' . $field_id, FALSE)) {
3469          $fields_form_ip_ju[$field_id] = $field_id;
3470          $field_form[] = $field_id;
3471          $fields_form[] = $field_id;
3472        }
3473      }
3474    }
3475    $form['#datos_institucionales_fields_datosds'] = $field_form;
3476    if (is_array($field_form) && count($field_form)) {
3477      module_load_include('inc', 'content', 'includes/content.node_form');
3478      foreach ($field_form as $field_id) {
3479        $field = content_fields($field_id, 'proyectos_operativos');
3480        $form['#field_info'][$field_id] = $field;
3481        $form += (array) content_field_form($form, $form_state, $field);
3482      }
3483    }
3484  }
3485  if (variable_get('proyectos_operativos_muestra_alcance', TRUE)) {
3486    $field_form = array();
3487    $arreglo = array(
3488      'field_proyecto_alcance' => 'field_proyecto_alcance',
3489    );
3490    $fields_form_ip_al = array();
3491    if (is_array($fields) && count($fields)) {
3492      foreach($fields as $field_id => $field) {
3493        if (array_key_exists($field_id, $arreglo)) {
3494          $field_form[] = $field_id;
3495          $fields_form[] = $field_id;
3496        }
3497        elseif (variable_get('proyectos_operativos_ip_al_' . $field_id, FALSE)) {
3498          $fields_form_ip_al[$field_id] = $field_id;
3499          $field_form[] = $field_id;
3500          $fields_form[] = $field_id;
3501        }
3502      }
3503    }
3504    $form['#datos_institucionales_fields_datosds1'] = $field_form;
3505    if (is_array($field_form) && count($field_form)) {
3506      module_load_include('inc', 'content', 'includes/content.node_form');
3507      foreach ($field_form as $field_id) {
3508        $field = content_fields($field_id, 'proyectos_operativos');
3509        $form['#field_info'][$field_id] = $field;
3510        $form += (array) content_field_form($form, $form_state, $field);
3511      }
3512    }
3513  }
3514  $sa = variable_get('proyectos_operativos_muestra_sa', TRUE);
3515  $so = variable_get('proyectos_operativos_muestra_so', TRUE);
3516  if ($sa || $so) {
3517    $form['indicador'] = array(
3518      '#type' => 'fieldset',
3519      '#title' => t('Indicador de la Situación'),
3520    );
3521  }
3522  if ($sa) {
3523    $field_form = array();
3524    $arreglo = array(
3525      'field_proyecto_sa_descripcion' => 'field_proyecto_sa_descripcion',
3526    );
3527    if (variable_get('proyectos_operativos_muestra_sa_cuantificacion', TRUE)) {
3528      $arreglo['field_proyecto_sa_cuantificacion'] = 'field_proyecto_sa_cuantificacion';
3529    }
3530    $arreglo['field_proyecto_sa_formulai'] = 'field_proyecto_sa_formulai';
3531    $arreglo['field_proyecto_sa_fuentei'] = 'field_proyecto_sa_fuentei';
3532    $arreglo['field_proyecto_sa_fecha'] = 'field_proyecto_sa_fecha';
3533    $fields_form_ip_sa = array();
3534    if (is_array($fields) && count($fields)) {
3535      foreach($fields as $field_id => $field) {
3536        if (array_key_exists($field_id, $arreglo)) {
3537          $field_form[] = $field_id;
3538          $fields_form[] = $field_id;
3539        }
3540        elseif (variable_get('proyectos_operativos_ip_sa_' . $field_id, FALSE)) {
3541          $fields_form_ip_sa[$field_id] = $field_id;
3542          $field_form[] = $field_id;
3543          $fields_form[] = $field_id;
3544        }
3545      }
3546    }
3547    $form['indicador']['sa'] = array(
3548      '#type' => 'fieldset',
3549      '#title' => t('Situación Actual'),
3550    );
3551    $form['#datos_institucionales_fields_datosds1'] = $field_form;
3552    if (is_array($field_form) && count($field_form)) {
3553      module_load_include('inc', 'content', 'includes/content.node_form');
3554      foreach ($field_form as $field_id) {
3555        $field = content_fields($field_id, 'proyectos_operativos');
3556        $form['#field_info'][$field_id] = $field;
3557        $form['indicador']['sa'] += (array) content_field_form($form, $form_state, $field);
3558      }
3559    }
3560  }
3561  if ($so) {
3562    $field_form = array();
3563    $arreglo = array(
3564      'field_proyecto_so_descripcion' => 'field_proyecto_so_descripcion',
3565      'field_proyecto_so_cuantificacion' => 'field_proyecto_so_cuantificacion',
3566      'field_proyecto_tiempoi' => 'field_proyecto_tiempoi',
3567    );
3568    $fields_form_ip_so = array();
3569    if (is_array($fields) && count($fields)) {
3570      foreach($fields as $field_id => $field) {
3571        if (array_key_exists($field_id, $arreglo)) {
3572          $field_form[] = $field_id;
3573          $fields_form[] = $field_id;
3574        }
3575        elseif (variable_get('proyectos_operativos_ip_so_' . $field_id, FALSE)) {
3576          $fields_form_ip_so[$field_id] = $field_id;
3577          $field_form[] = $field_id;
3578          $fields_form[] = $field_id;
3579        }
3580      }
3581    }
3582    $form['indicador']['so'] = array(
3583      '#type' => 'fieldset',
3584      '#title' => t('Situación Objetivo'),
3585    );
3586    $form['#datos_institucionales_fields_datosds1'] = $field_form;
3587    if (is_array($field_form) && count($field_form)) {
3588      module_load_include('inc', 'content', 'includes/content.node_form');
3589      foreach ($field_form as $field_id) {
3590        $field = content_fields($field_id, 'proyectos_operativos');
3591        $form['#field_info'][$field_id] = $field;
3592        $form['indicador']['so'] += (array) content_field_form($form, $form_state, $field);
3593      }
3594    }
3595  }
3596  $field_form = array();
3597  $arreglo = array(
3598    'field_proyecto_descripcion_bien' => 'field_proyecto_descripcion_bien',
3599    'field_proyecto_unidadm' => 'field_proyecto_unidadm',
3600    'field_proyecto_meta_fisica' => 'field_proyecto_meta_fisica',
3601  );
3602  $fields_form_ip_re = array();
3603  if (is_array($fields) && count($fields)) {
3604    foreach($fields as $field_id => $field) {
3605      if (array_key_exists($field_id, $arreglo)) {
3606        $field_form[] = $field_id;
3607        $fields_form[] = $field_id;
3608      }
3609      elseif (variable_get('proyectos_operativos_ip_re_' . $field_id, FALSE)) {
3610        $fields_form_ip_re[$field_id] = $field_id;
3611        $field_form[] = $field_id;
3612        $fields_form[] = $field_id;
3613      }
3614    }
3615  }
3616  if (is_array($field_form) && count($field_form)) {
3617    module_load_include('inc', 'content', 'includes/content.node_form');
3618    foreach ($field_form as $field_id) {
3619      $field = content_fields($field_id, 'proyectos_operativos');
3620      $form['#field_info'][$field_id] = $field;
3621      $form += (array) content_field_form($form, $form_state, $field);
3622    }
3623  }
3624  //obtener la fecha de inicio y fin
3625  $mes = explode('-', $form['#node']->field_proyecto_fecha_i[0]['value']);
3626  $mes_inicio = 0;
3627  if (count($mes)) {
3628    $mes_inicio = $mes[1] - 1;
3629  }
3630  //obtener la fecha de inicio y fin
3631  $mes = explode('-', $form['#node']->field_proyecto_fecha_f[0]['value']);
3632  $mes_final = 0;
3633  if (count($mes)) {
3634    $mes_final = $mes[1] - 1;
3635  }
3636
3637  $form['#fields_form_ip_al'] = $fields_form_ip_al;
3638  $form['#fields_form_ip_in'] = $fields_form_ip_in;
3639  $form['#fields_form_ip_ju'] = $fields_form_ip_ju;
3640  $form['#fields_form_ip_sa'] = $fields_form_ip_sa;
3641  $form['#fields_form_ip_so'] = $fields_form_ip_so;
3642  $form['#fields_form_ip_re'] = $fields_form_ip_re;
3643
3644
3645
3646  $form['#proyectos_operativos_fecha'] = array();
3647  $form['#proyectos_operativos_fecha'][0] = $mes_inicio;
3648  $form['#proyectos_operativos_fecha'][1] = $mes_final;
3649  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
3650  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
3651  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos1.js');
3652  drupal_add_js(array('proyectos_operativos' => array('fecha' => $form['#proyectos_operativos_fecha'])), 'setting');
3653  $format_number = array(
3654    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
3655    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
3656    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
3657  );
3658  $form['#format_number'] = array('format_number' => $format_number);
3659  drupal_add_js($form['#format_number'], 'setting');
3660  $form['#proyectos_operativos_fields'] = $fields_form;
3661  $form['buttons'] = array(
3662    '#prefix' => '<div class="container-inline">',
3663    '#suffix' => '</div>',
3664  );
3665  $form['buttons']['registrar'] = array(
3666    '#type' => 'submit',
3667    '#default_value' => t('Aceptar'),
3668    '#weight' => 100,
3669  );
3670  $form['buttons']['cancelar'] = array(
3671    '#type' => 'submit',
3672    '#default_value' => t('Cancelar'),
3673    '#attributes' => array('onClick' => 'window.location="' . base_path() .$_GET['q'] . '"; return false;'),
3674    '#weight' => 101,
3675  );
3676  $form['#submit'] = array('proyectos_operativos_proyecto_indicadores_form_submit');
3677  return $form;
3678}
3679
3680/**
3681 * Implementation of proyectos_operativos_proyecto_indicadores_form_validate().
3682 * Validar formulario de indicadores (proyectos operativos).
3683 */
3684function proyectos_operativos_proyecto_indicadores_form_validate($form, &$form_state) {
3685  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
3686  if ($op == t('Cancelar')) {
3687    return;
3688  }
3689  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
3690  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
3691  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos1.js');
3692  drupal_add_js(array('proyectos_operativos' => array('fecha' => $form['#proyectos_operativos_fecha'])), 'setting');
3693  drupal_add_js($form['#format_number'], 'setting');
3694  if (isset($form_state['values']['field_proyecto_meta_fisica'])) {
3695    $suma = 0;
3696    for ($i = 0; $i < 12; $i++) {
3697      if ($form['#proyectos_operativos_fecha'][0] <= $i && $form['#proyectos_operativos_fecha'][1] >= $i) {
3698        $valor = $i ? 'value_' . $i : 'value';
3699        $suma += $form_state['values']['field_proyecto_meta_fisica'][0][$valor];
3700      }
3701    }
3702    if (!$suma) {
3703      form_set_error('field_proyecto_meta_fisica', t('La Distribución de la Meta Fisíca del Proyecto debe tener al menos un resultado'));
3704    }
3705  }
3706}
3707
3708/**
3709 * Implementation of proyectos_operativos_proyecto_indicadores_form_submit().
3710 * Guardar formulario de indicadores (proyectos operativos).
3711 */
3712function proyectos_operativos_proyecto_indicadores_form_submit($form, &$form_state) {
3713  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
3714  if ($op == t('Cancelar')) {
3715    drupal_set_message(t('Se cancelo el ingreso de los indicadores del proyecto.'));
3716    $form_state['redirect'] = 'proyectosopedit/' . $form['#node']->nid;
3717    return;
3718  }
3719  if (module_exists('hs_content_taxonomy')) {
3720    foreach ($form['#field_info'] as $field_name => $field_info) {
3721      if ($field_info['widget']['type'] == 'content_taxonomy_hs') {
3722        // Change format of values to the one Content Taxonomy expects
3723        if (is_array($form_state['values'][$field_name]['tids'])) {
3724          $values = array();
3725          foreach($form_state['values'][$field_name]['tids'] as $tid) {
3726            $values[] = array('value' => $tid);
3727            array_unshift($form_state['values'][$field_name], array('value' => $tid));
3728          }
3729          $form_state['values'][$field_name]['tids'] = $values;
3730        }
3731        else {
3732          $values[] = array('value' => $form_state['values'][$field_name]['tids']);
3733          array_unshift($form_state['values'][$field_name],array('value' => $form_state['values'][$field_name]['tids']));
3734          $form_state['values'][$field_name]['tids'] = $values;
3735        }
3736      }
3737    }
3738  }
3739  $field_form = $form['#proyectos_operativos_fields'];
3740  module_load_include('inc', 'node', 'node.pages');
3741  $node_load = $form['#node'];
3742  if (isset($form_state['values']['field_proyecto_meta_fisica'])) {
3743    $suma = 0;
3744    for ($i = 0; $i < 12; $i++) {
3745      $valor = $i ? 'value_' . $i : 'value';
3746      if ($form['#proyectos_operativos_fecha'][0] <= $i && $form['#proyectos_operativos_fecha'][1] >= $i) {
3747        $suma += $form_state['values']['field_proyecto_meta_fisica'][0][$valor];
3748      }
3749      else {
3750        $form_state['values']['field_proyecto_meta_fisica'][0][$valor] = 0;
3751      }
3752    }
3753  }
3754  $form_values = $form_state['values'];
3755  if (is_array($field_form) && count($field_form)) {
3756    foreach ($field_form as $field_id) {
3757      if (isset($form_values[$field_id]) && is_array($form_values[$field_id])) {
3758        foreach($form_values[$field_id] as $id => $value) {
3759          if (is_numeric($id) && isset($form_values[$field_id][$id]['_error_element'])) {
3760            unset($form_values[$field_id][$id]['_error_element']);
3761          }
3762        }
3763        $node_load->{$field_id} = $form_values[$field_id];
3764      }
3765    }
3766  }
3767  if ($node_load->nid) {
3768    $texto = t('Modificados los indicadores del proyecto');
3769    $node_load->log = $texto;
3770    drupal_set_message($texto);
3771  }
3772  else {
3773    $texto = t('Agregados los indicadores del proyecto');
3774    $node_load->log = $texto;
3775    drupal_set_message($texto);
3776  }
3777  $node_load->revision = 1;
3778  node_save($node_load);
3779  if ($_REQUEST['destination']) {
3780    $form_state['redirect'] = url('proyectosopedit/' . $node_load->nid . '/ae',
3781      array(
3782        'query' => array(
3783          'destination' => $_REQUEST['destination'],
3784         ),
3785         'absolute' => TRUE,               
3786      )
3787    );
3788    unset($_REQUEST['destination']);
3789  }
3790  else {
3791    // add redirect
3792    $form_state['redirect'] = 'proyectosopedit/' . $node_load->nid . '/ae';
3793  }
3794}
3795
3796/**
3797 * Implementation of _proyectos_operativos_proyecto_ae().
3798 * Formulario de acciones especificas (proyectos operativos).
3799 */
3800function _proyectos_operativos_proyecto_ae($proyecto = 0, $ae = 0) {
3801  global $user;
3802  $current_time = time();
3803  $tipo_plan = 'proyectos_operativos_formular';
3804  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
3805  $fecha = FALSE;
3806  $ente = usuario_tiene_ente($user->uid);
3807  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
3808    $fecha = TRUE;
3809  }
3810  if (!$fecha) {
3811    muestra_mensaje($tipo_plan, 2);
3812  }
3813  if ($fecha && $ente->nid) {
3814    muestra_mensaje($tipo_plan, 2, 0);
3815  }
3816  $output = '';
3817  $output .= drupal_get_form('proyectos_operativos_accion_especifica_crear_form', $proyecto, $ae);
3818  return $output;
3819}
3820
3821/**
3822 * Implementation of _proyectos_operativos_proyecto_financieros().
3823 * Ver datos financieros (proyectos operativos).
3824 */
3825function _proyectos_operativos_proyecto_financieros($proyecto = 0) {
3826/*
3827
3828
3829  drupal_set_title(t('Consultar Datos Financieros'));
3830  global $user;
3831  $format_number = array(
3832    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
3833    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
3834    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
3835  );
3836  $current_time = time();
3837  $tipo_plan = 'proyectos_operativos_formular';
3838  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
3839  $fecha = FALSE;
3840  $ente = usuario_tiene_ente($user->uid);
3841  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
3842    $fecha = TRUE;
3843  }
3844  if (!$fecha) {
3845    muestra_mensaje($tipo_plan, 2);
3846  }
3847  if ($fecha && $ente->nid) {
3848    muestra_mensaje($tipo_plan, 2, 0);
3849  }
3850  $output = '';
3851  $ejecucion = 0;
3852  $acciones_especificas = array();
3853  $arreglo_anual = array();
3854  $arreglo_partida = array();
3855  $titles = array();
3856  $partidas = array();
3857  $node_type = content_types('accion_especifica');
3858  $fields = $node_type['fields'];
3859
3860  $titulos_campos = array();
3861  $valores = array();
3862  $campos = array();
3863
3864  //financiamiento
3865  $arreglo_financiamiento = array();
3866  $accion_especifica_number_fields = variable_get('accion_especifica_number_fields', 4);
3867  if ($accion_especifica_number_fields > 0) {
3868    for($i = 0; $i < $accion_especifica_number_fields; $i++) {
3869      $arreglo_financiamiento['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_label_' . $i, '') ? variable_get('accion_especifica_financiamiento_label_' . $i, '') : '';
3870      $arreglo_financiamiento_fields['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_options_' . $i, array());
3871    }
3872  }
3873  if (is_array($fields) && count($fields)) {
3874    foreach($fields as $field_id => $field) {
3875      $titulos_campos[$field_id] = $field['widget']['label'];
3876    }
3877  }
3878
3879
3880  $valores_financiamiento = array();
3881  $totalvalores_financiamiento_partida = array();
3882  $rows_f = array();
3883  $arreglo_financiamiento_fields2 = $arreglo_financiamiento_fields;
3884  foreach($proyecto->field_proyecto_accion_esp as $accion) {
3885    if ($accion['nid']) {
3886      $accion_load = node_load($accion['nid']);
3887      if ($accion_load && $accion_load->type == 'accion_especifica') {
3888        foreach($campos as $field) {
3889          $valores[$field] += $accion_load->{$field}[0]['value'];
3890        }
3891        $row = array();
3892        $titles[$accion_load->nid] = $accion_load->titulo_asignado;
3893        $row[] = array('data' => $titles[$accion_load->nid], 'align' => 'center');
3894        $acciones_especificas[$accion_load->nid] = $accion_load;
3895        $ejecucion += $accion_load->field_accion_esp_ponderacion[0]['value'];
3896        foreach($accion_load->field_accion_esp_programacion as $accion) {
3897          if ($accion['tid']) {
3898            $partidas[$accion['tid']] = $accion['tid'];
3899            for ($i = 0; $i < 12; $i++) {
3900              $valor = $i ? 'value_' . $i : 'value';
3901              if (!isset($arreglo_partida[$accion_load->nid][$accion['tid']])) {
3902                $arreglo_partida[$accion_load->nid][$accion['tid']] = 0;
3903              }
3904              if (!isset($arreglo_anual[$accion_load->nid][$valor])) {
3905                $arreglo_anual[$accion_load->nid][$valor] = 0;
3906              }
3907              $arreglo_partida[$accion_load->nid][$accion['tid']] += $accion[$valor];
3908              $arreglo_anual[$accion_load->nid][$valor] += $accion[$valor];
3909            }
3910          }
3911        }
3912        $totalvalores_financiamiento_partida[$accion_load->nid] = 0;
3913        $valores_financiamiento_partida[$accion_load->nid] = array();
3914          foreach($arreglo_financiamiento as $id => $titulo) {
3915            foreach($arreglo_financiamiento_fields[$id] as $field) {
3916              if (!$field) {
3917                unset($arreglo_financiamiento_fields2[$id][$id_field]);
3918              }
3919              if (!isset($valores_financiamiento[$field])) {
3920                $valores_financiamiento[$field] = 0;
3921              }
3922              if (!isset($valores_financiamiento_partida[$accion_load->nid][$field])) {
3923                $valores_financiamiento_partida[$accion_load->nid][$field] = 0;
3924              }
3925              $totalvalores_financiamiento_partida[$accion_load->nid] += $accion_load->{$field}[0]['value'];
3926              $valores_financiamiento[$field] += $accion_load->{$field}[0]['value'];
3927              $valores_financiamiento_partida[$accion_load->nid][$field] += $accion_load->{$field}[0]['value'];
3928            }
3929          }
3930      }
3931    }
3932  }
3933
3934
3935
3936  $rowsf = array();
3937  //Se agregan los encabezados
3938  $row = array();
3939  $row[] = array('data' => '<b>' . t('Acciones Especificas') . '</b>', 'align' => 'center', 'rowspan' => 2);
3940  $cuenta_financia = array();
3941  $colspans = array();
3942  foreach($arreglo_financiamiento as $id => $titulo) {
3943    $cuenta_financia[$id] = count($arreglo_financiamiento_fields2[$id]);
3944
3945    $colspan = 0;
3946    foreach($arreglo_financiamiento_fields2[$id] as $field) {
3947      if ($field) {
3948        $colspan++;
3949      }
3950    }
3951    $colspans[$id] = $colspan;
3952
3953
3954
3955    $row[] = array('data' => '<b>' . $titulo . '</b>', 'align' => 'center', 'colspan' => $colspan);
3956  }
3957  $row[] = array('data' => '<b>' . t('Total') . '</b>', 'align' => 'center', 'rowspan' => 2);
3958  $rowsf[] = $row;
3959  $row = array();
3960  foreach($arreglo_financiamiento as $id => $titulo) {
3961    foreach($arreglo_financiamiento_fields2[$id] as $field) {
3962      if ($field) {
3963        $row[] = array('data' => '<b>' . $titulos_campos[$field] . '</b>', 'align' => 'center');
3964      }
3965    }
3966  }
3967  $rowsf[] = $row;
3968  $tttfinan = 0;
3969  foreach($valores_financiamiento_partida as $nid => $titulo) {
3970    $row = array();
3971    $totlaesfin = 0;
3972          $row[] = array('data' => $titles[$nid], 'align' => 'center');
3973    foreach($arreglo_financiamiento as $id => $titulo) {
3974      foreach($arreglo_financiamiento_fields2[$id] as $field) {
3975        if ($field && isset($valores_financiamiento_partida[$nid][$field])) {
3976          $row[] = array('data' =>  number_format($valores_financiamiento_partida[$nid][$field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
3977$tttfinan += $valores_financiamiento_partida[$nid][$field];
3978          $totlaesfin += $valores_financiamiento_partida[$nid][$field];
3979        }
3980        else {
3981          $row[] = array('data' => 0, 'align' => 'center');
3982        }
3983      }
3984    }
3985    $row[] = array('data' =>  number_format($totlaesfin, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
3986    $rowsf[] = $row;
3987  }
3988
3989
3990
3991print "<pre>";
3992
3993print_r($arreglo_financiamiento_fields2);
3994print_r($valores_financiamiento_partida);
3995print "</pre>";
3996
3997  $rowsf = array();
3998  //Se agregan los encabezados
3999  $row = array();
4000  $row[] = array('data' => '<b>' . t('Acciones Especificas') . '</b>', 'align' => 'center', 'rowspan' => 2);
4001  $cuenta_financia = array();
4002  $colspans = array();
4003
4004  foreach($arreglo_financiamiento as $id => $titulo) {
4005    $cuenta_financia[$id] = count($arreglo_financiamiento_fields2[$id]);
4006    $colspan = 0;
4007    foreach($arreglo_financiamiento_fields2[$id] as $field) {
4008      if ($field) {
4009        $colspan++;
4010      }
4011    }
4012    $colspans[$id] = $colspan;
4013    $row[] = array('data' => '<b>' . $titulo . '</b>', 'align' => 'center', 'colspan' => $colspan);
4014  }
4015  $row[] = array('data' => '<b>' . t('Total') . '</b>', 'align' => 'center', 'rowspan' => 2);
4016  $rowsf[] = $row;
4017  $row = array();
4018  foreach($arreglo_financiamiento as $id => $titulo) {
4019    foreach($arreglo_financiamiento_fields2[$id] as $field) {
4020      if ($field) {
4021        $row[] = array('data' => '<b>' . $titulos_campos[$field] . '</b>', 'align' => 'center');
4022      }
4023    }
4024  }
4025  $rowsf[] = $row;
4026  $tttfinan = 0;
4027  foreach($valores_financiamiento_partida as $nid => $titulo) {
4028    $row = array();
4029    $totlaesfin = 0;
4030          $row[] = array('data' => $titles[$nid], 'align' => 'center');
4031    foreach($arreglo_financiamiento as $id => $titulo) {
4032      foreach($arreglo_financiamiento_fields2[$id] as $field) {
4033        if ($field && isset($valores_financiamiento_partida[$nid][$field])) {
4034          $row[] = array('data' =>  number_format($valores_financiamiento_partida[$nid][$field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4035$tttfinan += $valores_financiamiento_partida[$nid][$field];
4036          $totlaesfin += $valores_financiamiento_partida[$nid][$field];
4037        }
4038        else {
4039          $row[] = array('data' => 0, 'align' => 'center');
4040        }
4041      }
4042    }
4043    $row[] = array('data' =>  number_format($totlaesfin, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4044    $rowsf[] = $row;
4045  }
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062  $ftypes = array(
4063    'value' => t('ENE'),
4064    'value_1' => t('FEB'),
4065    'value_2' => t('MAR'),
4066    'value_3' => t('ABR'),
4067    'value_4' => t('MAY'),
4068    'value_5' => t('JUN'),
4069    'value_6' => t('JUL'),
4070    'value_7' => t('AGO'),
4071    'value_8' => t('SEP'),
4072    'value_9' => t('OCT'),
4073    'value_10' => t('NOV'),
4074    'value_11' => t('DEC'),
4075  );
4076  $rows = array();
4077  $row = array();
4078  $row[] = array('data' => '<b>' . t('Acciones Especificas') . '</b>', 'rowspan' => 2, 'align' => 'center');
4079  $row[] = array('data' => '<b>' . t('Mes') . '</b>', 'colspan' => 12, 'align' => 'center');
4080  $row[] = array('data' => '<b>' . t('Total') . '</b>', 'rowspan' => 2, 'align' => 'center');
4081  $rows[] = $row;
4082  $row = array();
4083  foreach($ftypes as $valor) {
4084    $row[] = array('data' =>  '<b>' . $valor . '</b>', 'align' => 'center');
4085  }
4086  $rows[] = $row;
4087  $i = 1;
4088  $suma_mes = array();
4089  if (count($arreglo_anual)) {
4090    foreach($arreglo_anual as $nid => $valore) {
4091      $suma = 0;
4092      $row = array();
4093      $row[] = array('data' => $titles[$nid], 'align' => 'center');
4094      foreach($ftypes as $id => $valor) {
4095        $suma += $valore[$id];
4096        if (!isset($suma_mes[$id])) {
4097          $suma_mes[$id] = 0;
4098        }
4099        $suma_mes[$valor] += $valore[$id];
4100        $row[] = array('data' => number_format($valore[$id], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4101      }
4102      $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4103      $rows[] = $row;
4104    }
4105    $row = array();
4106    $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right');
4107    $suma = 0;
4108    foreach($ftypes as $valor) {
4109      $row[] = array('data' => number_format($suma_mes[$valor], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4110      $suma += $suma_mes[$valor];
4111    }
4112    $style = '';
4113    if ($suma != $proyecto->field_proyecto_monto_anual[0]['value']) {
4114      $style = 'color: red';
4115    }
4116    $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center', 'style' => $style);
4117    $rows[] = $row;
4118  }
4119  else {
4120    $row = array();
4121    $row[] = array('data' => t('No existen acciones especificas'), 'colspan' => 12, 'align' => 'center');
4122  }
4123  $output .= '<fieldset><legend>' . t('Resumen financiero de las acciones') . '</legend>' .   '<div class="field-label"><b>' . t('Monto total para el año en curso:') . '</b> ' . number_format($proyecto->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . theme('table', array(), $rows) . '</fieldset>';
4124  $rows = array();
4125  $row = array();
4126  $row[] = array('data' => '<b>' . t('Acciones Especificas') . '</b>', 'rowspan' => 2, 'align' => 'center');
4127  $row[] = array('data' =>  '<b>' . t('Partidas') . '</b>', 'colspan' => count($partidas), 'align' => 'center');
4128  $row[] = array('data' =>  '<b>' . t('Total') . '</b>', 'rowspan' => 2, 'align' => 'center');
4129  $rows[] = $row;
4130  $row = array();
4131  foreach($partidas as $valor) {
4132    $term = taxonomy_get_term($valor);
4133    // If this term's vocabulary supports localization.
4134    if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
4135      $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
4136    }
4137    $row[] = array('data' => '<b>' . $term->name . '</b>', 'align' => 'center');
4138  }
4139  $rows[] = $row;
4140  $suma_mes = array();
4141  if (count($arreglo_partida)) {
4142    foreach($arreglo_partida as $nid => $valore) {
4143      $suma = 0;
4144      $row = array();
4145      $row[] = array('data' => $titles[$nid], 'align' => 'center');
4146      foreach($partidas as $valor) {
4147        if (!$valore[$valor]) {
4148          $valore[$valor] = 0;
4149        }
4150        $suma += $valore[$valor];
4151        if (!isset($suma_mes[$valor])) {
4152          $suma_mes[$valor] = 0;
4153        }
4154        $suma_mes[$valor] += $valore[$valor];
4155        $row[] = array('data' => number_format($valore[$valor], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4156      }
4157      $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4158      $rows[] = $row;
4159    }
4160    $row = array();
4161    $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right');
4162    $suma = 0;
4163    foreach($partidas as $valor) {
4164      $row[] = array('data' => number_format($suma_mes[$valor], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4165      $suma += $suma_mes[$valor];
4166    }
4167    $style = '';
4168    if ($suma != $proyecto->field_proyecto_monto_anual[0]['value']) {
4169      $style = 'color: red';
4170    }
4171    $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center', 'style' => $style);
4172    $rows[] = $row;
4173  }
4174  else {
4175    $row = array();
4176    $row[] = array('data' => t('No existen acciones especificas'), 'colspan' => 12, 'align' => 'center');
4177  }
4178  $output .= '<fieldset><legend>' . t('Distribución por partida presupuestaria') . '</legend>' .   '<div class="field-label"><b>' . t('Monto total para el año en curso:') . '</b> ' . number_format($proyecto->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . theme('table', array(), $rows) . '</fieldset>';
4179  $rows = array();
4180  $row = array();
4181  $totales_fin = array();
4182
4183
4184  $totales_ae_fin = array();
4185  $rowf = array();
4186  $rowf[] = array('data' => '<b>' . t('Sub-totales') . '</b>', 'align' => 'right');
4187
4188
4189
4190  foreach($arreglo_financiamiento as $id => $titulo) {
4191    $output1 = '<fieldset><legend>' . $titulo . '</legend>';
4192    foreach($arreglo_financiamiento_fields[$id] as $field) {
4193      if ($field) {
4194        if (!isset($totales_fin[$id])) {
4195          $totales_fin[$id] = 0;
4196        }
4197        //$valores[$field] = $valores_financiamiento[$field];
4198        $totales_fin[$id] += $valores_financiamiento[$field];
4199        $output1 .= '<div class="field-label"><b>' . $titulos_campos[$field] . ':</b> ' . number_format($valores_financiamiento[$field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>';
4200
4201  $rowf[] = array('data' => number_format($valores_financiamiento[$field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4202
4203
4204
4205      }
4206    }
4207    $output1 .= '</fieldset>';
4208    $row[] = array('data' => $output1, 'align' => 'center');
4209  }
4210
4211
4212    $rowf[] = array('data' => number_format($tttfinan, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'right');
4213$rowsf[] = $rowf;
4214  $rowf = array();
4215  $rowf[] = array('data' => '<b>' . t('Total Fuentes') . '</b>', 'align' => 'right');
4216
4217
4218
4219  $rows[] = $row;
4220  $row = array();
4221  $total_total = 0;
4222  foreach($arreglo_financiamiento as $id => $arreglo) {
4223    $total_total += $totales_fin[$id];
4224    $row[] = array('data' => number_format($totales_fin[$id], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4225
4226    $rowf[] = array('data' => number_format($totales_fin[$id], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center', 'colspan' => $colspans[$id]);
4227
4228
4229  }
4230
4231    $rowf[] = array('data' => number_format($tttfinan, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'right');
4232$rowsf[] = $rowf;
4233
4234
4235
4236
4237  $rows[] = $row;
4238  $row = array();
4239  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right', 'colspan' => count($arreglo_financiamiento) - 1);
4240  $row[] = array('data' => number_format($total_total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4241  $rows[] = $row;
4242  $output .= '<fieldset><legend>' . t('Fuentes de financiamiento') . '</legend>' .   '<div class="field-label"><b>' . t('Monto total para el año en curso:') . '</b> ' . number_format($proyecto->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . theme('table', array(), $rows) . '</fieldset>';
4243
4244
4245$output .= '<fieldset><legend>' . t('Fuentes de financiamiento por AE') . '</legend>';
4246$output .= theme('table', array(), $rowsf) . '</fieldset>';
4247
4248
4249  if (_proyectos_operativos_access_editar($proyecto)) {
4250    $output .= _proyectos_operativos_proyecto_ver_workflow($proyecto);
4251  }
4252  return $output;
4253
4254*/
4255
4256
4257
4258  drupal_set_title(t('Consultar Datos Financieros'));
4259  //add breadcrumb
4260  $breadcrumb = array();
4261  $breadcrumb[] = l(t('Home'), '<front>');
4262  $breadcrumb[] = l(t('Proyectos Operativos'), 'proyectos_operativos');
4263  if ($proyecto->nid) {
4264    $breadcrumb[] = l(check_plain($proyecto->title), 'proyectosop/' . $proyecto->nid);
4265  }
4266  $breadcrumb[] = t('Datos Financieros');
4267  drupal_set_breadcrumb($breadcrumb);
4268  global $user;
4269  $format_number = array(
4270    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
4271    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
4272    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
4273  );
4274  $current_time = time();
4275  $tipo_plan = 'proyectos_operativos_formular';
4276  $fecha = FALSE;
4277  $ente = usuario_tiene_ente($user->uid);
4278  $ente_planificador = 0;
4279  if ($ente && $ente->nid) {
4280    $ente_planificador = ente_planificador_leer_ente_planificadores($ente->nid);
4281  }
4282  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, $ente_planificador);
4283  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
4284    $fecha = TRUE;
4285  }
4286  if (!$fecha) {
4287    muestra_mensaje($tipo_plan, $ente_planificador);
4288  }
4289  if ($fecha && $ente->nid) {
4290    muestra_mensaje($tipo_plan, $ente_planificador, 0);
4291  }
4292  $output = '';
4293  $ejecucion = 0;
4294  $acciones_especificas = array();
4295  $arreglo_anual = array();
4296  $arreglo_partida = array();
4297  $titles = array();
4298  $partidas = array();
4299  $node_type = content_types('accion_especifica');
4300  $fields = $node_type['fields'];
4301
4302  $titulos_campos = array();
4303  $valores = array();
4304  $campos = array();
4305
4306  //financiamiento
4307  $arreglo_financiamiento = array();
4308  $accion_especifica_number_fields = variable_get('accion_especifica_number_fields', 4);
4309  if ($accion_especifica_number_fields > 0) {
4310    for($i = 0; $i < $accion_especifica_number_fields; $i++) {
4311      $arreglo_financiamiento['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_label_' . $i, '') ? variable_get('accion_especifica_financiamiento_label_' . $i, '') : '';
4312      $arreglo_financiamiento_fields['financiamiento_' . $i] = variable_get('accion_especifica_financiamiento_options_' . $i, array());
4313    }
4314  }
4315  if (is_array($fields) && count($fields)) {
4316    foreach($fields as $field_id => $field) {
4317      $titulos_campos[$field_id] = $field['widget']['label'];
4318    }
4319  }
4320
4321
4322  $valores_financiamiento = array();
4323
4324  $valores_financiamiento_partida = array();
4325  $totalvalores_financiamiento_partida = array();
4326  $rows_f = array();
4327  $arreglo_financiamiento_fields2 = $arreglo_financiamiento_fields;
4328  foreach($proyecto->field_proyecto_accion_esp as $accion) {
4329    if ($accion['nid']) {
4330      $accion_load = node_load($accion['nid']);
4331      if ($accion_load && $accion_load->type == 'accion_especifica') {
4332        foreach($campos as $field) {
4333          $valores[$field] += $accion_load->{$field}[0]['value'];
4334        }
4335        $row = array();
4336        $titles[$accion_load->nid] = $accion_load->titulo_asignado;
4337        $row[] = array('data' => $titles[$accion_load->nid], 'align' => 'center');
4338        $acciones_especificas[$accion_load->nid] = $accion_load;
4339        $ejecucion += $accion_load->field_accion_esp_ponderacion[0]['value'];
4340        foreach($accion_load->field_accion_esp_programacion as $accion) {
4341          if ($accion['tid']) {
4342            $partidas[$accion['tid']] = $accion['tid'];
4343            for ($i = 0; $i < 12; $i++) {
4344              $valor = $i ? 'value_' . $i : 'value';
4345              if (!isset($arreglo_partida[$accion_load->nid][$accion['tid']])) {
4346                $arreglo_partida[$accion_load->nid][$accion['tid']] = 0;
4347              }
4348              if (!isset($arreglo_anual[$accion_load->nid][$valor])) {
4349                $arreglo_anual[$accion_load->nid][$valor] = 0;
4350              }
4351              $arreglo_partida[$accion_load->nid][$accion['tid']] += $accion[$valor];
4352              $arreglo_anual[$accion_load->nid][$valor] += $accion[$valor];
4353            }
4354          }
4355        }
4356        $totalvalores_financiamiento_partida[$accion_load->nid] = 0;
4357        $valores_financiamiento_partida[$accion_load->nid] = array();
4358
4359
4360          foreach($arreglo_financiamiento as $id => $titulo) {
4361            foreach($arreglo_financiamiento_fields[$id] as $id_field => $field) {
4362              if (!$field) {
4363                unset($arreglo_financiamiento_fields2[$id][$id_field]);
4364              }
4365              if (!isset($valores_financiamiento[$id_field])) {
4366                $valores_financiamiento[$id_field] = 0;
4367              }
4368
4369              if (!isset($valores_financiamiento_partida[$accion_load->nid][$field])) {
4370                $valores_financiamiento_partida[$accion_load->nid][$field] = 0;
4371              }
4372
4373
4374              $totalvalores_financiamiento_partida[$accion_load->nid] += $accion_load->{$field}[0]['value'];
4375              $valores_financiamiento[$field] += $accion_load->{$field}[0]['value'];
4376              $valores_financiamiento_partida[$accion_load->nid][$field] += $accion_load->{$field}[0]['value'];
4377            }
4378          }
4379      }
4380    }
4381  }
4382
4383  $rowsf = array();
4384  //Se agregan los encabezados
4385  $row = array();
4386  $row[] = array('data' => '<b>' . t('Acciones Especificas') . '</b>', 'align' => 'center', 'rowspan' => 2);
4387  $cuenta_financia = array();
4388  $colspans = array();
4389
4390/*
4391print "<pre>";
4392
4393print_r($arreglo_financiamiento_fields2);
4394print_r($valores_financiamiento_partida);
4395
4396print "</pre>";
4397*/
4398  foreach($arreglo_financiamiento as $id => $titulo) {
4399    $cuenta_financia[$id] = count($arreglo_financiamiento_fields2[$id]);
4400    $colspan = 0;
4401    foreach($arreglo_financiamiento_fields2[$id] as $field) {
4402      if ($field) {
4403        $colspan++;
4404      }
4405    }
4406    $colspans[$id] = $colspan;
4407    $row[] = array('data' => '<b>' . $titulo . '</b>', 'align' => 'center', 'colspan' => $colspan);
4408  }
4409  $row[] = array('data' => '<b>' . t('Total') . '</b>', 'align' => 'center', 'rowspan' => 2);
4410  $rowsf[] = $row;
4411  $row = array();
4412  foreach($arreglo_financiamiento as $id => $titulo) {
4413    foreach($arreglo_financiamiento_fields2[$id] as $field) {
4414      if ($field) {
4415        $row[] = array('data' => '<b>' . $titulos_campos[$field] . '</b>', 'align' => 'center');
4416      }
4417    }
4418  }
4419  $rowsf[] = $row;
4420  $tttfinan = 0;
4421  foreach($valores_financiamiento_partida as $nid => $titulo) {
4422    $row = array();
4423    $totlaesfin = 0;
4424          $row[] = array('data' => $titles[$nid], 'align' => 'center');
4425    foreach($arreglo_financiamiento as $id => $titulo) {
4426      foreach($arreglo_financiamiento_fields2[$id] as $field) {
4427        if ($field && isset($valores_financiamiento_partida[$nid][$field])) {
4428          $row[] = array('data' =>  number_format($valores_financiamiento_partida[$nid][$field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4429$tttfinan += $valores_financiamiento_partida[$nid][$field];
4430          $totlaesfin += $valores_financiamiento_partida[$nid][$field];
4431        }
4432        else {
4433          $row[] = array('data' => 0, 'align' => 'center');
4434        }
4435      }
4436    }
4437    $row[] = array('data' =>  number_format($totlaesfin, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4438    $rowsf[] = $row;
4439  }
4440
4441
4442
4443
4444
4445  $ftypes = array(
4446    'value' => t('ENE'),
4447    'value_1' => t('FEB'),
4448    'value_2' => t('MAR'),
4449    'value_3' => t('ABR'),
4450    'value_4' => t('MAY'),
4451    'value_5' => t('JUN'),
4452    'value_6' => t('JUL'),
4453    'value_7' => t('AGO'),
4454    'value_8' => t('SEP'),
4455    'value_9' => t('OCT'),
4456    'value_10' => t('NOV'),
4457    'value_11' => t('DEC'),
4458  );
4459  $rows = array();
4460  $row = array();
4461  $row[] = array('data' => '<b>' . t('Acciones Especificas') . '</b>', 'rowspan' => 2, 'align' => 'center');
4462  $row[] = array('data' => '<b>' . t('Mes') . '</b>', 'colspan' => 12, 'align' => 'center');
4463  $row[] = array('data' => '<b>' . t('Total') . '</b>', 'rowspan' => 2, 'align' => 'center');
4464  $rows[] = $row;
4465  $row = array();
4466  foreach($ftypes as $valor) {
4467    $row[] = array('data' =>  '<b>' . $valor . '</b>', 'align' => 'center');
4468  }
4469  $rows[] = $row;
4470  $i = 1;
4471  $suma_mes = array();
4472  if (count($arreglo_anual)) {
4473    foreach($arreglo_anual as $nid => $valore) {
4474      $suma = 0;
4475      $row = array();
4476      $row[] = array('data' => $titles[$nid], 'align' => 'center');
4477      foreach($ftypes as $id => $valor) {
4478        $suma += $valore[$id];
4479        if (!isset($suma_mes[$id])) {
4480          $suma_mes[$id] = 0;
4481        }
4482        $suma_mes[$valor] += $valore[$id];
4483        $row[] = array('data' => number_format($valore[$id], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4484      }
4485      $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4486      $rows[] = $row;
4487    }
4488    $row = array();
4489    $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right');
4490    $suma = 0;
4491    foreach($ftypes as $valor) {
4492      $row[] = array('data' => number_format($suma_mes[$valor], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4493      $suma += $suma_mes[$valor];
4494    }
4495    $style = '';
4496    if ($suma != $proyecto->field_proyecto_monto_anual[0]['value']) {
4497      $style = 'color: red';
4498    }
4499    $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center', 'style' => $style);
4500    $rows[] = $row;
4501  }
4502  else {
4503    $row = array();
4504    $row[] = array('data' => t('No existen acciones especificas'), 'colspan' => 12, 'align' => 'center');
4505  }
4506  $output .= '<fieldset><legend>' . t('Resumen financiero de las acciones') . '</legend>' .   '<div class="field-label"><b>' . t('Monto total para el año en curso:') . '</b> ' . number_format($proyecto->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . theme('table', array(), $rows) . '</fieldset>';
4507  $rows = array();
4508  $row = array();
4509  $row[] = array('data' => '<b>' . t('Acciones Especificas') . '</b>', 'rowspan' => 2, 'align' => 'center');
4510  $row[] = array('data' =>  '<b>' . t('Partidas') . '</b>', 'colspan' => count($partidas), 'align' => 'center');
4511  $row[] = array('data' =>  '<b>' . t('Total') . '</b>', 'rowspan' => 2, 'align' => 'center');
4512  $rows[] = $row;
4513  $row = array();
4514  foreach($partidas as $valor) {
4515    $term = taxonomy_get_term($valor);
4516    // If this term's vocabulary supports localization.
4517    if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
4518      $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
4519    }
4520    $row[] = array('data' => '<b>' . $term->name . '</b>', 'align' => 'center');
4521  }
4522  $rows[] = $row;
4523  $suma_mes = array();
4524  if (count($arreglo_partida)) {
4525    foreach($arreglo_partida as $nid => $valore) {
4526      $suma = 0;
4527      $row = array();
4528      $row[] = array('data' => $titles[$nid], 'align' => 'center');
4529      foreach($partidas as $valor) {
4530        if (!$valore[$valor]) {
4531          $valore[$valor] = 0;
4532        }
4533        $suma += $valore[$valor];
4534        if (!isset($suma_mes[$valor])) {
4535          $suma_mes[$valor] = 0;
4536        }
4537        $suma_mes[$valor] += $valore[$valor];
4538        $row[] = array('data' => number_format($valore[$valor], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4539      }
4540      $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4541      $rows[] = $row;
4542    }
4543    $row = array();
4544    $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right');
4545    $suma = 0;
4546    foreach($partidas as $valor) {
4547      $row[] = array('data' => number_format($suma_mes[$valor], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4548      $suma += $suma_mes[$valor];
4549    }
4550    $style = '';
4551    if ($suma != $proyecto->field_proyecto_monto_anual[0]['value']) {
4552      $style = 'color: red';
4553    }
4554    $row[] = array('data' => number_format($suma, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center', 'style' => $style);
4555    $rows[] = $row;
4556  }
4557  else {
4558    $row = array();
4559    $row[] = array('data' => t('No existen acciones especificas'), 'colspan' => 12, 'align' => 'center');
4560  }
4561  $output .= '<fieldset><legend>' . t('Distribución por partida presupuestaria') . '</legend>' .   '<div class="field-label"><b>' . t('Monto total para el año en curso:') . '</b> ' . number_format($proyecto->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . theme('table', array(), $rows) . '</fieldset>';
4562  $rows = array();
4563  $row = array();
4564  $totales_fin = array();
4565  $totales_ae_fin = array();
4566  $rowf = array();
4567  $rowf[] = array('data' => '<b>' . t('Sub-totales') . '</b>', 'align' => 'right');
4568  foreach($arreglo_financiamiento as $id => $titulo) {
4569    $output1 = '<fieldset><legend>' . $titulo . '</legend>';
4570    foreach($arreglo_financiamiento_fields[$id] as $field) {
4571      if ($field) {
4572        if (!isset($totales_fin[$id])) {
4573          $totales_fin[$id] = 0;
4574        }
4575        //$valores[$field] = $valores_financiamiento[$field];
4576        $totales_fin[$id] += $valores_financiamiento[$field];
4577        $output1 .= '<div class="field-label"><b>' . $titulos_campos[$field] . ':</b> ' . number_format($valores_financiamiento[$field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>';
4578  $rowf[] = array('data' => number_format($valores_financiamiento[$field], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4579      }
4580    }
4581    $output1 .= '</fieldset>';
4582    $row[] = array('data' => $output1, 'align' => 'center');
4583  }
4584    $rowf[] = array('data' => number_format($tttfinan, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'right');
4585$rowsf[] = $rowf;
4586  $rowf = array();
4587  $rowf[] = array('data' => '<b>' . t('Total Fuentes') . '</b>', 'align' => 'right');
4588  $rows[] = $row;
4589  $row = array();
4590  $total_total = 0;
4591  foreach($arreglo_financiamiento as $id => $arreglo) {
4592    $total_total += $totales_fin[$id];
4593    $row[] = array('data' => number_format($totales_fin[$id], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4594    $rowf[] = array('data' => number_format($totales_fin[$id], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center', 'colspan' => $colspans[$id]);
4595
4596
4597  }
4598    $rowf[] = array('data' => number_format($tttfinan, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'right');
4599$rowsf[] = $rowf;
4600  $rows[] = $row;
4601  $row = array();
4602  $row[] = array('data' => '<b>' . t('TOTAL') . '</b>', 'align' => 'right', 'colspan' => count($arreglo_financiamiento) - 1);
4603  $row[] = array('data' => number_format($total_total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), 'align' => 'center');
4604  $rows[] = $row;
4605  $output .= '<fieldset><legend>' . t('Fuentes de financiamiento') . '</legend>' .   '<div class="field-label"><b>' . t('Monto total para el año en curso:') . '</b> ' . number_format($proyecto->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div>' . theme('table', array(), $rows) . '</fieldset>';
4606
4607
4608$output .= '<fieldset><legend>' . t('Fuentes de financiamiento por AE') . '</legend>';
4609$output .= theme('table', array(), $rowsf) . '</fieldset>';;
4610  if (_proyectos_operativos_access_editar($proyecto)) {
4611    $output .= _proyectos_operativos_proyecto_ver_workflow($proyecto);
4612  }
4613  return $output;
4614
4615
4616
4617
4618
4619
4620}
4621
4622/**
4623 * Implementation of hook_planner_items_toolbar().
4624*/
4625function proyectos_operativos_planner_items_toolbar($ente_planificador, $handler_icon) {
4626  $link = array();
4627  $icon_path = entes_planificadores_toolbar_get_icon_path('planner', 'proyectosop', $handler_icon);
4628  $link[] = array(
4629    'path' => 'proyectos_operativos',
4630    'icon_path' => $icon_path,
4631    'icon' => theme('image', $icon_path, t('Consultar Información de los proyectos operativos del actor planificador'), t('Consultar Información de los proyectos operativos del actor planificador'), array('class' => 'handler-icon-' . $handler_icon)),
4632    'title' => t('Proyectos operativos'),
4633    'description' => t('Consultar Información de los proyectos operativos del actor planificador'),
4634    'category' => 'planner',
4635  );
4636  return $link;
4637}
4638
4639/**
4640 * Implementation of hook_admin_items_toolbar().
4641*/
4642function proyectos_operativos_admin_items_toolbar($handler_icon) {
4643  $link = array();
4644  $icon_path = entes_planificadores_toolbar_get_icon_path('admin', 'proyectosop', $handler_icon);
4645  $link[] = array(
4646    'path' => 'proyectos_operativos',
4647    'icon_path' => $icon_path,
4648    'icon' => theme('image', $icon_path, t('Consultar Información de los proyectos operativos del actor planificador'), t('Consultar Información de los proyectos operativos del actor planificador'), array('class' => 'handler-icon-' . $handler_icon)),
4649    'title' => t('Proyectos operativos'),
4650    'description' => t('Consultar Información de los proyectos operativos del actor planificador'),
4651    'category' => 'planner',
4652  );
4653  return $link;
4654}
4655
4656/**
4657 * Implementation of hook_theme().
4658 */
4659function proyectos_operativos_theme() {
4660  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos') . '/templates';
4661  return array(
4662    'proyectos_operativos_proyecto_basico_form' => array(
4663      'arguments' => array('form' => NULL),
4664    ),
4665    'proyectos_operativos_proyecto_generales_form' => array(
4666      'arguments' => array('form' => NULL),
4667    ),
4668    'proyectos_operativos_proyecto_indicadores_form' => array(
4669      'arguments' => array('form' => NULL),
4670    ),
4671    'proyectos_operativos_ficha_proyecto' => array(
4672      'arguments' => array(
4673        'proyecto' => array(),
4674      ),
4675      'template' => 'proyectos-operativos-ficha-proyecto',
4676      'path' => $proyectos_operativos_path,
4677    ),
4678    'proyecto_operativos_flujo_avance' => array(
4679      'arguments' => array(
4680        'proyecto' => array(),
4681        'states' => array(),
4682      ),
4683      'template' => 'proyectos-operativos-flujo-avance',
4684      'path' => $proyectos_operativos_path,
4685    ),
4686  );
4687}
4688
4689/**
4690 * @ingroup themeable
4691 * @see proyectos_operativos_proyecto_basico_form
4692 */
4693function theme_proyectos_operativos_proyecto_basico_form($form) {
4694  $output = '';
4695  $fecha_inicio = $form['#fechas_validacion']['inicio'];
4696  if ($form['#count_ae']) {
4697    $format_number = array(
4698      'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
4699      'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
4700      'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
4701    );
4702    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas, con un monto total de @montos_asignados Bs asignados. y fechas de Inicio  @inicio y fin  @fin. Tome en consideración estos valores al momento de modificar los valores de los campos @title_fecha_i, @final title_fecha_f y @title_monto_total_proyecto_year', array('@count_ae' => $form['#count_ae'], '@montos_asignados' => number_format($form['#montos_asignados'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '@inicio' => $form['#fechas_validacion']['inicio_texto'], '@fin' => $form['#fechas_validacion']['fin_texto'], '@title_fecha_i' => $form['field_proyecto_fecha_i']['#title'], '@final title_fecha_f' => $form['field_proyecto_fecha_f']['#title'], '@title_monto_total_proyecto_year' => $form['field_proyecto_monto_anual']['#title'] ));
4703    $output .= '<div id="mensaje-mostrar" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
4704  }
4705  $output .= '<fieldset><legend>' . t('Datos Básicos de Identificación del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_titulo']) . drupal_render($form['field_proyecto_codigo']) . drupal_render($form['field_proyecto_codigo_n_etap']) . drupal_render($form['field_proyecto_fecha_i']) . drupal_render($form['field_proyecto_fecha_f']) . drupal_render($form['field_proyecto_status']) . drupal_render($form['field_proyecto_situacion_p']) . drupal_render($form['field_proyecto_plurianual']) . drupal_render($form['field_proyecto_monto_anual']) . drupal_render($form['field_proyecto_total']) . drupal_render($form['field_proyecto_poan']);
4706  if (is_array($form['#fields_form_ac_d']) && count($form['#fields_form_ac_d'])) {
4707    foreach($form['#fields_form_ac_d'] as $id_a) {
4708      $output .= drupal_render($form[$id_a]);
4709    }
4710  }
4711  $output .= '</fieldset>';
4712  $output .= '<fieldset><legend>' . t('Gerente del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_ente']) . drupal_render($form['field_proyecto_autoridad']) . drupal_render($form['field_proyecto_lider']) . drupal_render($form['field_proyecto_unidad_a']) . drupal_render($form['field_proyecto_cargo']) . drupal_render($form['field_proyecto_telefono']) . drupal_render($form['field_proyecto_correo']);
4713  if (is_array($form['#fields_form_ac_di']) && count($form['#fields_form_ac_di'])) {
4714    foreach($form['#fields_form_ac_d'] as $id_a) {
4715      $output .= drupal_render($form[$id_a]);
4716    }
4717  }
4718  $output .= '</fieldset>';
4719  $pndes = variable_get('proyectos_operativos_muestra_pndes', TRUE);
4720  $mcti = variable_get('proyectos_operativos_muestra_mcti', TRUE);
4721  $count_ac_p = count($form['#fields_form_ac_p']);
4722
4723  if ($pndes || $mcti || $count_ac_p) {
4724    $output .= '<fieldset><legend>' . t('Área Estrategica') . '</legend>';
4725    if ($pndes) {
4726      $output .= drupal_render($form['field_proyecto_pndes']);
4727    }
4728    if ($mcti) {
4729      $output .= drupal_render($form['field_proyecto_mcti']);
4730    }
4731    if ($count_ac_p) {
4732      foreach($form['#fields_form_ac_p'] as $id_a) {
4733        $output .= drupal_render($form[$id_a]);
4734      }
4735    }
4736    $output .= '</fieldset>';
4737  }
4738  $output .= drupal_render($form);
4739  return $output;
4740}
4741
4742/**
4743 * @ingroup themeable
4744 * @see proyectos_operativos_proyecto_generales_form
4745 */
4746function theme_proyectos_operativos_proyecto_generales_form($form) {
4747  $arreglo = array(
4748    'field_proyecto_emdirecto' => 'field_proyecto_emdirecto',
4749    'field_proyecto_efdirecto' => 'field_proyecto_efdirecto',
4750    'field_proyecto_emindirecto' => 'field_proyecto_emindirecto',
4751    'field_proyecto_efindirecto' => 'field_proyecto_efindirecto',
4752  );
4753  $output = '';
4754  if ($form['#count_ae'] && $form['#montos_asignados']!= $form['#node']->field_proyecto_monto_anual[0]['value']) {
4755    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
4756    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
4757    $format_number = array(
4758      'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
4759      'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
4760      'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
4761    );
4762    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas con un monto total de @montos_asignados Bs, el cual difiere con el monto asignado en el proyecto para el @title_monto_total_proyecto_year (@monto_proyecto). Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@montos_asignados' => number_format($form['#montos_asignados'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '@title_monto_total_proyecto_year' => $form['#proyecto_fields']['field_proyecto_monto_anual']['widget']['label'], '@monto_proyecto' => number_format($form['#node']->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
4763    $output .= '<div id="mensaje-mostrar-monto" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
4764  }
4765  if ($form['#count_ae'] && $fechas_validacion['inicio'] && $fechas_validacion['fin'] && ($fechas_validacion['inicio_time'] < $fechas_validacion['inicio_current_time'] || $fechas_validacion['fin_current_time'] < $fechas_validacion['fin_time'])) {
4766    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
4767    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
4768    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas que difieren con la @title_fecha_de_inicio o @title_fecha_de_final del Proyecto. Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@title_fecha_de_inicio' => $form['#proyecto_fields']['field_proyecto_fecha_i']['widget']['label'], '@title_fecha_de_final' => $form['#proyecto_fields']['field_proyecto_fecha_f']['widget']['label'], '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
4769    $output .= '<div id="mensaje-mostrar-time" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
4770  }
4771  $output .= '<fieldset><legend>' . t('Clasificación Sectorial') . '</legend>' . drupal_render($form['field_proyecto_sector']);
4772  if (count($form['#fields_form_dg_se'])) {
4773    foreach($form['#fields_form_dg_se'] as $id_c) {
4774      $output .= drupal_render($form[$id_c]);
4775    }
4776  }
4777  $output .= '</fieldset>';
4778
4779
4780  if (variable_get('proyectos_operativos_muestra_talento', TRUE)) {
4781    $output .= drupal_render($form['talento']);
4782  }
4783  if (variable_get('proyectos_operativos_muestra_capacidades', TRUE)) {
4784    $output .= drupal_render($form['capacidades']);
4785  }
4786  $output .= '<fieldset><legend>' . t('Instituciones') . '</legend>' . drupal_render($form['field_proyecto_relacion']);
4787  if (count($form['#fields_form_dg_r'])) {
4788    foreach($form['#fields_form_dg_r'] as $id_c) {
4789      $output .= drupal_render($form[$id_c]);
4790    }
4791  }
4792  $output .= '</fieldset>';
4793  $output .= '<fieldset><legend>' . t('Empleos Generados') . '</legend>' . t('Nro Estimados de Empleos:');
4794  $output .= '<table><tr>';
4795  $output1 = '<tr>';
4796  foreach($arreglo as $empleo) {
4797    if (array_key_exists($empleo, $form)) {
4798      $output .= '<th>' . $form[$empleo]['#title'] . '</th>';
4799      $form[$empleo][0]['value']['#title'] = '';
4800      $output1 .= '<td>' . drupal_render($form[$empleo]) . '</td>';
4801    }
4802  }
4803  $output1 .= '<td><div class="empleos_generados_total"></div></td>';
4804  $output .= '<th>' . t('TOTAL') . '</th>';
4805  $output1 .= '</tr>';
4806  $output .= '</tr>' . $output1 .'</table></fieldset>';
4807  if (variable_get('proyectos_operativos_muestra_beneficiario', TRUE)) {
4808    $output .= drupal_render($form['beneficiario']);
4809  }
4810  $output .= '<fieldset><legend>' . t('Objetivos del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_og']) . drupal_render($form['field_proyecto_oe']);
4811  if (count($form['#fields_form_dg_o'])) {
4812    foreach($form['#fields_form_dg_o'] as $id_c) {
4813      $output .= drupal_render($form[$id_c]);
4814    }
4815  }
4816  $output .= '</fieldset>';
4817
4818
4819  $output .= drupal_render($form);
4820  return $output;
4821}
4822
4823/**
4824 * @ingroup themeable
4825 * @see proyectos_operativos_proyecto_indicadores_form
4826 */
4827function theme_proyectos_operativos_proyecto_indicadores_form($form) {
4828  $output = '';
4829  if ($form['#count_ae'] && $form['#montos_asignados']!= $form['#node']->field_proyecto_monto_anual[0]['value']) {
4830    $format_number = array(
4831      'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
4832      'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
4833      'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
4834    );
4835    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
4836    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
4837    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas con un monto total de @montos_asignados Bs, el cual difiere con el monto asignado en el proyecto para el @title_monto_total_proyecto_year (@monto_proyecto). Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@montos_asignados' => number_format($form['#montos_asignados'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '@title_monto_total_proyecto_year' => $form['#proyecto_fields']['field_proyecto_monto_anual']['widget']['label'], '@monto_proyecto' => number_format($form['#node']->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
4838    $output .= '<div id="mensaje-mostrar-monto" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
4839  }
4840  if ($form['#count_ae'] && $fechas_validacion['inicio'] && $fechas_validacion['fin'] && ($fechas_validacion['inicio_time'] < $fechas_validacion['inicio_current_time'] || $fechas_validacion['fin_current_time'] < $fechas_validacion['fin_time'])) {
4841    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
4842    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
4843    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas que difieren con la @title_fecha_de_inicio o @title_fecha_de_final del Proyecto. Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@title_fecha_de_inicio' => $form['#proyecto_fields']['field_proyecto_fecha_i']['widget']['label'], '@title_fecha_de_final' => $form['#proyecto_fields']['field_proyecto_fecha_f']['widget']['label'], '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
4844    $output .= '<div id="mensaje-mostrar-time" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
4845  }
4846  if (variable_get('proyectos_operativos_muestra_enunciado_problema', TRUE)) {
4847    $output .= '<fieldset><legend>' . t('Enunciado del Problema') . '</legend>' . drupal_render($form['field_proyecto_causas']) . drupal_render($form['field_proyecto_problemas']) . drupal_render($form['field_proyecto_consecuencias']);
4848    if (count($form['#fields_form_ip_in'])) {
4849      foreach($form['#fields_form_ip_in'] as $id_c) {
4850        $output .= drupal_render($form[$id_c]);
4851      }
4852    }
4853    $output .= '</fieldset>';
4854  }
4855  if (variable_get('proyectos_operativos_muestra_justicacion', TRUE)) {
4856    $output .= '<fieldset><legend>' . t('Justificación del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_justificacion']);
4857    if (count($form['#fields_form_ip_ju'])) {
4858      foreach($form['#fields_form_ip_ju'] as $id_c) {
4859        $output .= drupal_render($form[$id_c]);
4860      }
4861    }
4862    $output .= '</fieldset>';
4863  }
4864  if (variable_get('proyectos_operativos_muestra_alcance', TRUE)) {
4865    $output .= '<fieldset><legend>' . t('Alcance del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_alcance']);
4866    if (count($form['#fields_form_ip_al'])) {
4867      foreach($form['#fields_form_ip_al'] as $id_c) {
4868        $output .= drupal_render($form[$id_c]);
4869      }
4870    }
4871    $output .= '</fieldset>';
4872  }
4873  $sa = variable_get('proyectos_operativos_muestra_sa', TRUE);
4874  $so = variable_get('proyectos_operativos_muestra_so', TRUE);
4875  if ($sa || $so) {
4876    $output .= drupal_render($form['indicador']);
4877  }
4878  $output .= '<fieldset><legend>' . t('Indicador del resultado del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_descripcion_bien']) . drupal_render($form['field_proyecto_unidadm']) . drupal_render($form['field_proyecto_meta_fisica']);
4879  if (count($form['#fields_form_ip_re'])) {
4880    foreach($form['#fields_form_ip_re'] as $id_c) {
4881      $output .= drupal_render($form[$id_c]);
4882    }
4883  }
4884  $output .= '</fieldset>';
4885  $output .= drupal_render($form);
4886  return $output;
4887}
4888
4889function proyectos_operativos_theme_registry_alter(&$theme_registry) {
4890  $theme_registry['hierarchical_select_select']['function'] = 'proyectos_operativos_hierarchical_select_select';
4891}
4892
4893
4894/**
4895 * Format a select in the .hierarchial-select div: prevent it from being
4896 * wrapped in a div. This simplifies the CSS and JS code.
4897 *
4898 * @param $element
4899 *   An associative array containing the properties of the element.
4900 * @return
4901 *   A themed HTML string representing the form element.
4902 */
4903function proyectos_operativos_hierarchical_select_select($element) {
4904  $display_label = '';
4905  foreach($element['#options'] as $id => $label) {
4906    if ($label && !is_numeric($id)) {
4907      $display_label = '<label>' . $label . ':</label>';
4908      $element['#options'][$id] = t('seleccione');
4909    }
4910  }
4911  $select = '';
4912  $size = $element['#size'] ? ' size="'. $element['#size'] .'"' : '';
4913  $class = array('form-select');
4914  if (form_get_error($element) === '') {
4915    $class = array_merge($class, array('error'));
4916  }
4917  _form_set_class($element, $class);
4918  $multiple = isset($element['#multiple']) && $element['#multiple'];
4919  return $display_label . '<select name="'. $element['#name'] .''. ($multiple ? '[]' : '') .'"'. ($multiple ? ' multiple="multiple" ' : '') . drupal_attributes($element['#attributes']) .' id="'. $element['#id'] .'" '. $size .'>'. _hierarchical_select_options($element) .'</select>';
4920}
4921
4922/**
4923 * Implementation of hook_block().
4924 *
4925 * Genera un bloque con el estatus de la planificación
4926 */
4927function proyectos_operativos_block($op = 'list', $delta = 0) {
4928  if (module_exists('workflow')) {
4929    $wid = workflow_get_workflow_for_type('proyectos_operativos');
4930    if ($wid) {
4931      if ($op == 'list') {
4932        $blocks[0]['info'] = t('Estatus del Avance de proyectos');
4933        return $blocks;
4934      }
4935      else if ($op == 'view' && user_access('ver planificador')) {
4936        if((arg(0) == 'proyectosop' && is_numeric(arg(1)))) {
4937          $states = workflow_get_states($wid);
4938          $proyecto = node_load(arg(1));
4939          $block['subject'] = t('Avance del Proyecto');
4940          $block['content'] = _proyecto_operativos_flujo_avance_theme($proyecto, $states);
4941        }
4942        return $block;
4943      }
4944    }
4945  }
4946}
4947
4948/**
4949 * Implementation of _proyecto_operativos_flujo_avance_theme().
4950 */
4951function _proyecto_operativos_flujo_avance_theme($proyecto = 0, $states = 0) {
4952  if (count($states)) {
4953    return theme('proyecto_operativos_flujo_avance', $proyecto, $states);
4954  }
4955  else {
4956    return t('No se han definido estados para Proyectos Operativos');
4957  }
4958}
4959
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.