source: sipes/0.3-modules/proyectos_operativos/proyectos_operativos.module @ 9ea43e0

stableversion-3.0
Last change on this file since 9ea43e0 was a62ef16, checked in by root <root@…>, 8 años ago

se establecio como valor 1 la cantidad por defecto del repita de los beneficiarios

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