source: sipes/0.3-modules/ente_planificador_importar/ente_planificador_importar.module @ 546c863

stable
Last change on this file since 546c863 was 546c863, checked in by Miguel Angel Narvaez Montilva <miguelnarvaez31@…>, 5 años ago

Se modifica modulo ente planificador_importar para ingresar montor de reconversión monetaria

  • Propiedad mode establecida a 100644
File size: 59.8 KB
Línea 
1<?php
2
3  /**
4  * Modulo para importar entes y terminos
5  * Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana
6  * @file ente_planificador_importar.module
7  * Drupal part Module to code ente planificador module
8  * Copyright 2011 Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana (CENDITEL)
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23  *
24  * @author Cenditel Merida - Msc. Juan Vizcarrondo
25  * @date 2016-07-07 // (a&#241;o-mes-dia)
26  * @date 2017-03-22 // (a&#241;o-mes-dia)
27  * @version 0.2 // (0.1)
28  *
29  */
30
31/*
32 * Implementation of hook_perm
33 */
34function ente_planificador_importar_perm() {
35  return array(
36    'access import entes planificadores',
37    'import entes planificadores',
38    'import term',
39    'update proyecto state',
40  );
41}
42
43/*
44 * Implementation of hook_menu()
45 */
46function ente_planificador_importar_menu() {
47  $items = array();
48  $items['ente_planificador_importar'] = array(
49    'title' => 'Importar Entes Planificadores',
50    'page callback' => '_ente_planificador_importar_listar',
51    'access arguments' => array('access import entes planificadores'),
52    'type' => MENU_NORMAL_ITEM,
53  );
54  $items['ente_planificador_importar/entes'] = array(
55    'title' => 'Importar Entes Planificadores',
56    'page callback' => 'drupal_get_form',
57    'page arguments' => array('ente_planificador_importar_form'),
58    'access arguments' => array('import entes planificadores'),
59    'type' => MENU_CALLBACK,
60  );
61  $items['ente_planificador_importar/updb_proyectos'] = array(
62    'title' => 'Importar Entes Planificadores',
63    'page callback' => 'drupal_get_form',
64    'page arguments' => array('ente_planificador_importar_updb_proyectos_form'),
65    'access arguments' => array('import entes planificadores'),
66    'type' => MENU_CALLBACK,
67  );
68  $items['ente_planificador_importar/terminos'] = array(
69    'title' => 'Importar Terminos',
70    'page callback' => 'drupal_get_form',
71    'page arguments' => array('ente_planificador_importar_terminos_form'),
72    'access arguments' => array('import term'),
73    'type' => MENU_CALLBACK,
74  );
75  $items['ente_planificador_importar/terminos/fields'] = array(
76    'title' => 'Importar Campos de Terminos',
77    'page callback' => 'drupal_get_form',
78    'page arguments' => array('ente_planificador_importar_terminos_fields_form'),
79    'access arguments' => array('import term'),
80    'type' => MENU_CALLBACK,
81  );
82  $items['ente_planificador_importar/terminos/relations_fields'] = array(
83    'title' => 'Importar Campos de Terminos',
84    'page callback' => 'drupal_get_form',
85    'page arguments' => array('ente_planificador_importar_terminos_relations_fields_form'),
86    'access arguments' => array('import term'),
87    'type' => MENU_CALLBACK,
88  );
89  $items['ente_planificador_importar_terminos_js_util'] = array(
90    'title' => 'JS utilities',
91    'page callback' => 'ente_planificador_importar_fields_js_util',
92    'access arguments' => array('import term'),
93    'type' => MENU_CALLBACK,
94  );
95  $items['ente_planificador_importar_terminos_relations_js_util'] = array(
96    'title' => 'JS utilities',
97    'page callback' => 'ente_planificador_importar_fields_relations_js_util',
98    'access arguments' => array('import term'),
99    'type' => MENU_CALLBACK,
100  );
101  $items['ente_planificador_importar/estadoproyecto'] = array(
102    'title' => 'Modificar estado de poyectos',
103    'page callback' => 'drupal_get_form',
104    'page arguments' => array('ente_planificador_importar_aprobar_proyectos_form'),
105    'access arguments' => array('update proyecto state'),
106    'type' => MENU_CALLBACK,
107  );
108
109  return $items;
110}
111
112/*
113 * Implementation of _ente_planificador_importar_listar()
114 * Muestra las opciones de importacion disponibles
115 */
116function _ente_planificador_importar_listar() {
117  $links = array();
118  drupal_alter('ente_planificador_importar_links', $links);
119  return theme('item_list', $links);
120}
121
122/*
123 * Implementation of hook_ente_planificador_importar_links_alter()
124 */
125function ente_planificador_ente_planificador_importar_links_alter(&$links) {
126  if (user_access('import entes planificadores')) {
127    $links['entes'] = array(
128      'data' => l(t('Importar Entes Planificadores'), 'ente_planificador_importar/entes'),
129      'class' => 'ente-planificador-importar-entes',
130    );
131  }
132  if (user_access('import term')) {
133    $links['term1'] = array(
134      'data' => l(t('Importar terminos'), 'ente_planificador_importar/terminos'),
135      'class' => 'ente-planificador-importar-term',
136    );
137    $links['term2'] = array(
138      'data' => l(t('Importar Campos de terminos'), 'ente_planificador_importar/terminos/fields'),
139      'class' => 'ente-planificador-importar-term-fields',
140    );
141    $links['term_parent'] = array(
142      'data' => l(t('Relacionar taxonomias y guardar valores en un campo del termino'), 'ente_planificador_importar/terminos/relations_fields'),
143      'class' => 'ente-planificador-importar-term-parents-fields',
144    );
145  }
146  if (user_access('update proyecto state')) {
147    $links['estadoproyecto'] = array(
148      'data' => l(t('Actualizar estado de proyectos'), 'ente_planificador_importar/estadoproyecto'),
149      'class' => 'ente-planificador-importar-estado-proyecto',
150    );
151  }
152}
153
154/**
155 * Implementation of ente_planificador_importar_terminos_form().
156 * Form to load cvs file in term import
157 */
158function ente_planificador_importar_terminos_relations_fields_form(&$form_state) {
159  $form = array();
160  // If this #attribute is not present, upload will fail on submit
161
162  $form['#prefix'] = "<div id='fields-ahah-taxonomy'>";
163  $form['#suffix'] = "</div>";
164  $options[0] = t('_none');
165  foreach (taxonomy_get_vocabularies() as $key => $taxonomy) {
166     $options[$taxonomy->vid] = $taxonomy->name;
167  }
168
169  $form['vid'] = array(
170    '#type' => 'select',
171    '#title' => t('Taxonomia Origen'),
172    '#options' =>  $options,
173    '#weight' => 0,
174    '#required' => true,
175    '#default_value' => 0,
176  );
177
178  $form['vid_taxonomy'] = array(
179    '#type' => 'select',
180    '#title' => t('Taxonomy to relations'),
181    '#options' =>  $options,
182    '#weight' => 1,
183    '#required' => true,
184    '#default_value' => 0,
185    '#ahah' => array(
186      'path' => 'ente_planificador_importar_terminos_relations_js_util',
187      'wrapper' => 'fields-ahah-taxonomy',
188      'method' => 'replace',
189      'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
190    ),
191  );
192  $form['submit'] = array(
193    '#type' => 'submit',
194    '#value' => 'Submit',
195    '#weight' => 10,
196  );
197  return $form;
198}
199
200/**
201 * Implementation of ente_planificador_importar_terminos_form_submit().
202 * Submit cvs file in term import
203 */
204function ente_planificador_importar_terminos_relations_fields_form_submit($form, &$form_state) {
205  global $user;
206  $validators = array('file_validate_extensions' => array('csv'));
207  // Check for a new uploaded file.
208  $file = file_save_upload('file_import_terms', $validators);
209  if (isset($file)) {
210    // File upload was attempted.
211    if ($file) {
212      // Put the temporary file in form_values so we can save it on submit.
213      $csv = $file->filepath;
214      $file = fopen($csv, 'r');
215      $time = time();
216      $i = 1;
217      $datas = array();
218      $batch = array(
219        'title' => t('Importing terminos ...', array('@format' => $format)),
220        'operations' => array(),
221        'init_message' => t('Commencing'),
222        'progress_message' => t('Processed @current out of @total.'),
223        'error_message' => t('An error occurred during processing'),
224        'finished' => '_batch_ente_planificador_importar_term_finished',
225      );
226      $ids = array(
227        'field1' => t('Campo 1'),
228        'field2' => t('Campo 2'),
229        'field3' => t('Campo 3'),
230      );
231      $terms = ente_planificador_importar_terminos_relations_fields_name($form_state['values']['vid']);
232      $term_load = array();
233      while (($data = fgetcsv($file)) !== FALSE) {
234         if (!($form_state['values']['encabezado'] && $i == 1)) {
235           $taxonomy_relations = taxonomy_vocabulary_load($form_state['values']['vid']);
236           $taxonomy = taxonomy_vocabulary_load($form_state['values']['vid_taxonomy']);
237           $name_field = trim(check_plain($data[$form_state['values']['nombre'] - 1]));
238           $name_field2 = trim(check_plain($data[$form_state['values']['nombre2'] - 1]));
239
240           if ($terms[$name_field]->tid) {
241             $term = $terms[$name_field];
242           }
243           else if ($terms["$name_field."]->tid) {
244             $term = $terms["$name_field."];
245           }
246           else if ($terms[$name_field2]->tid) {
247             $term = $terms[$name_field2];
248           }
249           else if ($terms["$name_field2."]->tid) {
250             $term = $terms["$name_field2."];
251          }
252
253           if ($term->tid) {
254             $term_load = array(
255                'vid' => $taxonomy->vid, // Voacabulary ID
256                'name' => $term->name, // Term Name
257              );
258              taxonomy_save_term($term_load);
259              $term_load['fields'][$form_state['values']['relation']] = array(
260                'value' => $term->tid,
261              );
262           }
263           $j = 0;
264           foreach ($ids as $id => $name) {
265             if ($form_state['values'][$id] && $data[$form_state['values'][$id] - 1]) {
266               $values = array_values($form_state['values']['fields']);
267               $term_load['fields']["$values[$j]"] = array(
268                  'value' => check_plain($data[$form_state['values'][$id] - 1]),
269               );
270             }
271             $j++;
272           }
273           $batch['operations'][] = array('_batch_ente_planificador_importar_term_relations_fields', array($term_load));
274        }
275        $i++;
276      }
277      batch_set($batch);
278      batch_process('ente_planificador_importar/terminos/relations_fields');
279    }
280    else {
281      // File upload failed.
282      form_set_error('file_import_terms', t('The term file could not be uploaded.'));
283    }
284  }
285}
286
287function ente_planificador_importar_terminos_relations_fields_name($vid) {
288  $result = db_query(db_rewrite_sql('SELECT t.tid, t.*, parent FROM {term_data} t INNER JOIN {term_hierarchy} h ON t.tid = h.tid WHERE t.vid = %d ORDER BY weight, name', 't', 'tid'), $vid);
289  while ($term = db_fetch_object($result)) {
290    $terms[trim($term->name)] = $term;
291  }
292  return $terms;
293}
294
295/**
296 * Genera las repuestas ajax
297 */
298function ente_planificador_importar_fields_relations_js_util() {
299  $form_state = array('submitted' => FALSE);
300  $form_build_id = $_POST['form_build_id'];
301  // Add the new element to the stored form. Without adding the element to the
302  // form, Drupal is not aware of this new elements existence and will not
303  // process it. We retreive the cached form, add the element, and resave.
304  $form = form_get_cache($form_build_id, $form_state);
305
306  $args = $form['#parameters'];
307  $form_id = array_shift($args);
308  // We will run some of the submit handlers so we need to disable redirecting.
309  $form['#redirect'] = FALSE;
310  // We need to process the form, prepare for that by setting a few internals
311  // variables.
312  $form['#post'] = $_POST;
313  $form['#programmed'] = FALSE;
314  $form_state['post'] = $_POST;
315
316  $values = term_fields_get_fields('fields');
317
318  if (isset($_POST['vid_taxonomy'])) {
319    $values = term_fields_get_fields('fields');
320    $i = 1;
321    $k = 1;
322    $fields[0] = t("_none");
323    $fields_op[0] = t("_none");
324    foreach ($values as $value) {
325      foreach ($value->vids as $key => $vid) {
326        $taxonomy = taxonomy_vocabulary_load($vid['vid']);
327        if ($value->type == 'numeric' && $taxonomy->vid == $_POST['vid_taxonomy']) {
328          $fields_op["$value->fid"] = t('@title (Valor del Campo n@campo)', array('@title' => $value->title, '@campo' => $k));
329          $k++;
330        }
331        else if ($taxonomy->vid == $_POST['vid_taxonomy']) {
332          $fields["$value->fid"] = t('@title (Valor del Campo n@campo)', array('@title' => $value->title, '@campo' => $i));
333        $i++;
334        }
335      }
336    }
337    $form['relation'] = array(
338      '#type' => 'select',
339      '#title' => t('Campos Numerico a relacionar'),
340      '#options' => $fields_op,
341      '#weight' => 2,
342      '#default_value' => $fields[0],
343    );
344    $form['fields'] = array(
345      '#type' => 'checkboxes',
346      '#title' => t('Campos a recolectar'),
347      '#options' => $fields,
348      '#weight' => 2,
349      '#default_value' => $fields[0],
350    );
351    if (count($fields)) {
352      $form['#attributes']['enctype'] = 'multipart/form-data';
353      $form['file_import_terms'] = array(
354        '#title' => t('Archivo (Terminos a importar)'),
355        '#type'  => 'file',
356        '#description' => t('Archivo cvs con el contenido de los terminos a importar'),
357        '#weight' => 3,
358      );
359      $options = array();
360      for ($i = 0;$i < 11; $i++) {
361        if (!$i) {
362          $options[$i] = t('N/A');
363        }
364        else {
365          $options[$i] = t('Fila') . ' ' . $i;
366        }
367      }
368      $form['fieldset'] = array(
369        '#title' => t('Nombres'),
370        '#type' => 'fieldset',
371        '#weight' => 4,
372      );
373      $form['fieldset']['nombre'] = array(
374        '#type' => 'select',
375        '#title' => t('Nombre del Termino'),
376        '#options' => $options,
377        '#description' => t("La fila donde se encuentra el valor del Campo."),
378        '#required' => TRUE,
379        '#weight' => 4,
380      );
381      $form['fieldset']['nombre2'] = array(
382        '#type' => 'select',
383        '#title' => t('Nombre del Termino 2'),
384        '#options' => $options,
385        '#description' => t("La fila donde se encuentra el valor del Campo de no presentarse un valor en el primer campo."),
386        '#required' => TRUE,
387        '#weight' => 4,
388      );
389      $ids = array(
390        'field1' => t('Campo 1'),
391        'field2' => t('Campo 2'),
392        'field3' => t('Campo 3'),
393      );
394      $i = 0;
395      foreach ($ids as $id =>$text) {
396        $i++;
397        $form[$id] = array(
398          '#type' => 'select',
399          '#title' => $text,
400          '#options' => $options,
401          '#weight' => 5 + $i,
402        );
403      }
404      $form['encabezado'] = array(
405        '#title' => 'Primera columna como encabezado',
406        '#type' => 'checkbox',
407        '#return_value' => '1',
408        '#weight' => 9,
409      );
410    }
411  }
412  form_set_cache($form_build_id, $form, $form_state);
413  $form += array(
414    '#post' => $_POST,
415    '#programmed' => FALSE,
416  );
417  // Rebuild the form.
418  $form = form_builder($_POST['form_id'], $form, $form_state);
419  // Render the new output.
420  $new_form = array();
421  $new_form = $form;
422  unset($new_form['#prefix'], $new_form['#suffix']); // Prevent duplicate wrappers.
423  $output = drupal_render($new_form);
424  print drupal_to_js(array('data' => $output, 'status' => true));
425  exit();
426  print '';
427  exit();
428}
429
430
431/**
432 * Implementation of _batch_ente_planificador_importar_term_fields().
433 * display term saved (used in _ente_planificador_importar_terminos_execute)
434 * Batch run callback
435 */
436function _batch_ente_planificador_importar_term_relations_fields($term, &$context) {
437  $parents = taxonomy_get_parents($term['tid']);
438  if ($parents) {
439    $parent = array_shift($parents);
440    $parent = $parent->tid;
441  }
442  else {
443    $parent = 0;
444  }
445  $term['parent'] = $parent;
446  taxonomy_save_term($term);
447
448//watchdog('example', 'taxonomy term <pre>@filename</pre>.', array('@filename' => print_r($term, 1)), WATCHDOG_ERROR);
449
450  $context['message'] = t('Now processing ente: %submission', array('%submission' => $term['name']));
451  $context['results'][] = 'term importado: ' . $term['name'] . '</pre>';
452
453  if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
454    $context['finished'] = 1;
455  } else {
456    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
457  }
458
459}
460
461
462/**
463 * Update values of field to type content
464 */
465function ente_planificador_importar_updb_proyectos_form(&$form_state) {
466  $form = array();
467  // If this #attribute is not present, upload will fail on submit
468  $form['#attributes']['enctype'] = 'multipart/form-data';
469  $form['file_import_entes'] = array(
470    '#title' => t('Archivo a importar'),
471    '#type'  => 'file',
472    '#description' => t('Archivo cvs con el contenido de los terminos a importar'),
473    '#weight' => -1,
474  );
475
476  $options = array();
477  for ($i = 0;$i < 30; $i++) {
478    if (!$i) {
479      $options[$i] = t('N/A');
480    }
481    else {
482      $options[$i] = t('Fila') . ' ' . $i;
483    }
484  }
485
486  $delimiter_option = array(",",";");
487  $form['delimiter']= array(
488    '#type' => 'select',
489    '#title' => t('Tipo de Delimitador'),
490    '#options' => $delimiter_option,
491    '#description' => t("Delimitador del archivo csv."),
492    '#required' => TRUE,
493    '#weight' => -1,
494    '#default_value' => ",",
495  );
496
497  $form['field_name'] = array(
498    '#type' => 'select',
499    '#title' => t('Nombre del campo'),
500    '#options' => $options,
501    '#description' => t("La fila donde se encuentra el nombre del Campo a modificar."),
502    '#required' => TRUE,
503    '#weight' => 0,
504    '#default_value' => 1,
505  );
506
507  $form['field_nid'] = array(
508    '#type' => 'select',
509    '#title' => t('Nid del nodo'),
510    '#options' => $options,
511    '#description' => t("La fila donde se encuentra el nid del nodo a modificar."),
512    '#required' => TRUE,
513    '#weight' => 1,
514    '#default_value' => 2,
515  );
516
517  $form['field_vid'] = array(
518    '#type' => 'select',
519    '#title' => t('Vid del campo'),
520    '#options' => $options,
521    '#description' => t("La fila donde se encuentra el vid del nodo a modificar."),
522    '#required' => TRUE,
523    '#weight' => 2,
524    '#default_value' => 3,
525  );
526
527  $form['type_content'] = array(
528    '#type' => 'select',
529    '#title' => t('tipo de contenido del campo'),
530    '#options' => $options,
531    '#description' => t("seleccione la columna donde se encuentre el tipo de contenido del campo."),
532    '#required' => TRUE,
533    '#weight' => 3,
534    '#default_value' => 4,
535  );
536
537  $form['field_delta'] = array(
538    '#type' => 'select',
539    '#title' => t('Delta del campo'),
540    '#options' => $options,
541    '#description' => t("si el campo es multiple seleccione la columna donde se encuentre el delta."),
542    '#required' => TRUE,
543    '#weight' => 4,
544  );
545
546  $form['field_tid'] = array(
547    '#type' => 'select',
548    '#title' => t('tid del campo'),
549    '#options' => $options,
550    '#description' => t("si el campo es multiple seleccione la columna donde se encuentre el tid."),
551    '#required' => TRUE,
552    '#weight' => 5,
553  );
554
555  $form['fields'] = array(
556    '#type' => 'fieldset',
557    '#title' => t('Campos'),
558    '#weight' => 6,
559  );
560  for ($i=0; $i<12; $i++) {
561    $form['fields']['field_value_' . $i] = array(
562      '#type' => 'select',
563      '#title' => t('Valor del campo ' . $i),
564      '#options' => $options,
565      '#description' => t("La fila donde se encuentra el valor del nodo a modificar."),
566      '#required' => TRUE,
567      '#weight' => $i,
568      '#default_value' => ($i==0) ? 7 : 0 ,
569    );
570  }
571
572  $form['encabezado'] = array(
573    '#title' => 'Primera columna como encabezado',
574    '#type' => 'checkbox',
575    '#return_value' => '1',
576    '#weight' => 7,
577    '#default_value' => TRUE,
578  );
579
580  $form['submit'] = array(
581    '#type' => 'submit',
582    '#value' => 'Submit',
583    '#weight' => 35,
584  );
585  return $form;
586}
587
588/**
589 * Implementation of function ente_planificador_importar_updb_proyectos_form().
590 * Update values of field to type content
591 */
592function ente_planificador_importar_updb_proyectos_form_submit($form, &$form_state) {
593  global $user;
594  $validators = array('file_validate_extensions' => array('csv'));
595  // Check for a new uploaded file.
596  $file = file_save_upload('file_import_entes', $validators);
597  if (isset($file)) {
598    include_once('./'. drupal_get_path('module', 'content') .'/content.install');
599    drupal_load('module', 'content');
600    // $types = content_types_install();
601    // if (empty($types)) {
602    //   return $ret;
603    // }
604
605    // File upload was attempted.
606    if ($file) {
607
608      // Put the temporary file in form_values so we can save it on submit.
609      $csv = $file->filepath;
610      $file = fopen($csv, 'r');
611      $time = time();
612      $i = 1;
613      $batch = array(
614        'title' => t('Update value proyects and acciones ...', array('@format' => $format)),
615        'operations' => array(),
616        'init_message' => t('Commencing'),
617        'progress_message' => t('Processed @current out of @total.'),
618        'error_message' => t('An error occurred during processing'),
619        'finished' => '_batch_ente_planificador_importar_finished',
620      );
621
622      //read the csv archive
623      $data_all =  fread($file, filesize($csv));
624      $fgetslines = explode("\n",$data_all);
625      $process = count($fgetslines);
626      $process = $form_state['values']['encabezado'] && $i == 1 ? $process-1 : $process ;
627      $encabezado = $form_state['values']['encabezado'] && $i == 1 ? 1 : 0 ;
628
629      for ($k=$encabezado; $k < $process; $k++) {
630        $data_line = explode("\n",$data_all);
631        $data_line_all = $data_line[$k];
632        $delimet = $form_state['values']['delimiter'] ? ";" : "," ;
633        $data = explode($delimet,$data_line_all);
634
635        $batch['operations'][] = array('_ente_planificador_importar_updb_proyectos_importar', array( $data, $form_state['values']));
636      }
637
638      batch_set($batch);
639      batch_process('ente_planificador_importar/updb_proyectos');
640    }
641    else {
642
643      // File upload failed.
644      form_set_error('file_import_entes', t('The entes file could not be uploaded.'));
645    }
646  }
647}
648
649/**
650 * Update values of field to type content
651 * Batch run callback
652 */
653 function _ente_planificador_importar_updb_proyectos_importar( $data, $formstate_values, &$context) {
654
655   $fields_update = trim($data[$formstate_values['field_name']-1]);
656   $field = content_fields($fields_update, $data[$formstate_values['type_content']-1]);
657   $values[] = $field;
658   $index = array();
659   for ($i=0; $i<12; $i++) {
660     $index[] = $i === 0? 'value' : 'value_' . $i;
661   }
662
663   $rate = 100000;
664   $sql = '';
665   foreach ($values as $field) {
666     if ($field['multiple']) {
667       $sql.=' and delta = '. $data[$formstate_values['field_delta']-1];
668     }
669     $db_info = content_database_info($field);
670     if (array_key_exists('tid', $db_info['columns'])) {
671       $sql.= ' and ' . $db_info['columns']['tid']['column'] . ' = ' . $data[$formstate_values['field_tid']-1] ;
672
673     }
674     $table = $db_info['table'];
675     $columns = array();
676
677     foreach($index as $key => $id) {
678       if (isset($db_info['columns'][$id])) {
679         $value = trim($data[$formstate_values['field_value_' . $key]-1]);
680         $attributes = $db_info['columns'][$id];
681         $column = $attributes['column'];
682
683         $decimals = ($field['scale']) && is_numeric($field['scale']) ? $field['scale'] : 0;
684         if(!$value==0) {
685
686           //$columns[] = $column  . ' = round(' . $value . '/' . $rate . ', ' . 8 . ')';
687
688           // Divide monto
689           // $value_table = round($value/$rate,8);
690
691           //Directamente sin dividir montos
692           $columns[] = $column .'='.$value;
693
694         } else {
695           $columns[] = $column  . ' = 0 ';
696         }
697       }
698     }
699
700     //sql que se va a pasar visto en Entradas recientes del registro
701     // $sql1 =('UPDATE {'. $db_info['table'] . '} AS tab SET '. implode(', ', $columns) . ' FROM {node} AS n WHERE n.nid = tab.nid AND n.vid = tab.vid AND n.vid = ' . $data[$formstate_values['field_vid']-1] . ' AND n.nid =' . $data[$formstate_values['field_nid']-1] . $sql );
702     // watchdog('Test Sipes', '$decimals @filename.', array('@filename' => print_r($sql1,1)), WATCHDOG_ERROR);
703    //endsql que se va a pasar visto en Entradas recientes del registro
704
705     update_sql('UPDATE {'. $db_info['table'] . '} AS tab SET '. implode(', ', $columns) . ' FROM {node} AS n WHERE n.nid = tab.nid AND n.vid = tab.vid AND n.vid = ' . $data[$formstate_values['field_vid']-1] . ' AND n.nid =' . $data[$formstate_values['field_nid']-1] . $sql );
706   }
707
708   $context['message'] = t('Now processing nid of node: %submission', array('%submission' => trim($data[$formstate_values['field_nid']-1])));
709   $context['results'][] = 'Node update: ' . trim($data[$formstate_values['field_nid']-1]) . '</pre>';
710
711   if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
712     $context['finished'] = 1;
713   } else {
714     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
715   }
716 }
717
718
719
720/**
721 * Implementation of ente_planificador_importar_terminos_form().
722 * Form to load cvs file in term import
723 */
724function ente_planificador_importar_terminos_fields_form(&$form_state) {
725  $form = array();
726  // If this #attribute is not present, upload will fail on submit
727
728  $form['#prefix'] = "<div id='fields-ahah-taxonomy'>";
729  $form['#suffix'] = "</div>";
730  $options[0] = t('_none');
731  foreach (taxonomy_get_vocabularies() as $key => $taxonomy) {
732     $options[$taxonomy->vid] = $taxonomy->name;
733  }
734
735  $form['vid'] = array(
736    '#type' => 'select',
737    '#title' => t('Taxonomy'),
738    '#options' =>  $options,
739    '#weight' => 0,
740    '#required' => true,
741    '#default_value' => 0,
742    '#ahah' => array(
743      'path' => 'ente_planificador_importar_terminos_js_util',
744      'wrapper' => 'fields-ahah-taxonomy',
745      'method' => 'replace',
746      'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
747    ),
748  );
749
750  $form['submit'] = array(
751    '#type' => 'submit',
752    '#value' => 'Submit',
753    '#weight' => 10,
754  );
755  return $form;
756}
757
758/**
759 * Implementation of ente_planificador_importar_terminos_form_submit().
760 * Submit cvs file in term import
761 */
762function ente_planificador_importar_terminos_fields_form_submit($form, &$form_state) {
763  global $user;
764  $validators = array('file_validate_extensions' => array('csv'));
765  // Check for a new uploaded file.
766  $file = file_save_upload('file_import_terms', $validators);
767  if (isset($file)) {
768    // File upload was attempted.
769    if ($file) {
770      // Put the temporary file in form_values so we can save it on submit.
771      $csv = $file->filepath;
772      $file = fopen($csv, 'r');
773      $time = time();
774      $i = 1;
775      $datas = array();
776      $batch = array(
777        'title' => t('Importing terminos ...', array('@format' => $format)),
778        'operations' => array(),
779        'init_message' => t('Commencing'),
780        'progress_message' => t('Processed @current out of @total.'),
781        'error_message' => t('An error occurred during processing'),
782        'finished' => '_batch_ente_planificador_importar_term_finished',
783      );
784      $ids = array(
785        'field1' => t('Campo 1'),
786        'field2' => t('Campo 2'),
787        'field3' => t('Campo 3'),
788      );
789
790      while (($data = fgetcsv($file)) !== FALSE) {
791         $taxonomy = taxonomy_vocabulary_load($form_state['values']['vid']);
792         $terms = taxonomy_get_tree($taxonomy->vid);
793         $name_field = check_plain($data[$form_state['values']['nombre'] - 1]);
794         foreach ($terms as $term) {
795           if (preg_match("/\b$name_field/i", trim($term->name))) { //not found
796              $term_load = taxonomy_get_term($term->tid);
797              $term_load = (array) $term_load;
798              $j = 0;
799              foreach ($ids as $id => $name) {
800                if ($form_state['values'][$id] && $data[$form_state['values'][$id] - 1]) {
801                  $values = array_values($form_state['values']['fields']);
802                  $term_load['fields']["$values[$j]"] = array(
803                     'value' => check_plain($data[$form_state['values'][$id] - 1]),
804                  );
805               }
806               $j++;
807             }
808             if (!($form_state['values']['encabezado'] && $i == 1)) {
809               $batch['operations'][] = array('_batch_ente_planificador_importar_term_fields', array($term_load));
810             }
811           }
812         }
813         $i++;
814      }
815      batch_set($batch);
816      batch_process('ente_planificador_importar/terminos/fields');
817    }
818    else {
819      // File upload failed.
820      form_set_error('file_import_terms', t('The term file could not be uploaded.'));
821    }
822  }
823}
824
825/**
826 * Implementation of _batch_ente_planificador_importar_term_fields().
827 * display term saved (used in _ente_planificador_importar_terminos_execute)
828 * Batch run callback
829 */
830function _batch_ente_planificador_importar_term_fields($term, &$context) {
831  $parents = taxonomy_get_parents($term['tid']);
832  if ($parents) {
833    $parent = array_shift($parents);
834    $parent = $parent->tid;
835  }
836  else {
837    $parent = 0;
838  }
839  $term['parent'] = $parent;
840  taxonomy_save_term($term);
841
842//watchdog('example', 'taxonomy term <pre>@filename</pre>.', array('@filename' => print_r($term, 1)), WATCHDOG_ERROR);
843
844  $context['message'] = t('Now processing ente: %submission', array('%submission' => $term['name']));
845  $context['results'][] = 'term importado: ' . $term['name'] . '</pre>';
846
847  if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
848    $context['finished'] = 1;
849  } else {
850    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
851  }
852}
853
854/**
855 * Genera las repuestas ajax
856 */
857function ente_planificador_importar_fields_js_util() {
858  $form_state = array('submitted' => FALSE);
859  $form_build_id = $_POST['form_build_id'];
860  // Add the new element to the stored form. Without adding the element to the
861  // form, Drupal is not aware of this new elements existence and will not
862  // process it. We retreive the cached form, add the element, and resave.
863  $form = form_get_cache($form_build_id, $form_state);
864
865  $args = $form['#parameters'];
866  $form_id = array_shift($args);
867  // We will run some of the submit handlers so we need to disable redirecting.
868  $form['#redirect'] = FALSE;
869  // We need to process the form, prepare for that by setting a few internals
870  // variables.
871  $form['#post'] = $_POST;
872  $form['#programmed'] = FALSE;
873  $form_state['post'] = $_POST;
874
875  $values = term_fields_get_fields('fields');
876
877  if (isset($_POST['vid'])) {
878    $values = term_fields_get_fields('fields');
879    $i = 0;
880    foreach ($values as $value) {
881      foreach ($value->vids as $key => $vid) {
882        $taxonomy = taxonomy_vocabulary_load($vid['vid']);
883        if ($taxonomy->vid == $_POST['vid']) {
884          $fields["$value->fid"] = t('@title (Valor del Campo n@campo)', array('@title' => $value->title, '@campo' => $i));
885        }
886        $i++;
887      }
888    }
889    $form['fields'] = array(
890      '#type' => 'checkboxes',
891      '#title' => t('Campos'),
892      '#options' => $fields,
893      '#weight' => 1,
894      '#required' => true,
895    );
896
897    if (count($fields)) {
898      $form['#attributes']['enctype'] = 'multipart/form-data';
899      $form['file_import_terms'] = array(
900        '#title' => t('Archivo (Terminos a importar)'),
901        '#type'  => 'file',
902        '#description' => t('Archivo cvs con el contenido de los terminos a importar'),
903        '#weight' => 2,
904      );
905      $options = array();
906      for ($i = 0;$i < 11; $i++) {
907        if (!$i) {
908          $options[$i] = t('N/A');
909        }
910        else {
911          $options[$i] = t('Fila') . ' ' . $i;
912        }
913      }
914      $form['nombre'] = array(
915        '#type' => 'select',
916        '#title' => t('Nombre del Termino'),
917        '#options' => $options,
918        '#description' => t("La fila donde se encuentra el valor del Campo."),
919        '#required' => TRUE,
920        '#weight' => 3,
921      );
922      $ids = array(
923        'field1' => t('Campo 1'),
924        'field2' => t('Campo 2'),
925        'field3' => t('Campo 3'),
926      );
927      $i = 0;
928      foreach ($ids as $id =>$text) {
929        $i++;
930        $form[$id] = array(
931          '#type' => 'select',
932          '#title' => $text,
933          '#options' => $options,
934          '#weight' => 4 + $i,
935        );
936      }
937      $form['encabezado'] = array(
938        '#title' => 'Primera columna como encabezado',
939        '#type' => 'checkbox',
940        '#return_value' => '1',
941        '#weight' => 9,
942      );
943    }
944  }
945  form_set_cache($form_build_id, $form, $form_state);
946  $form += array(
947    '#post' => $_POST,
948    '#programmed' => FALSE,
949  );
950  // Rebuild the form.
951  $form = form_builder($_POST['form_id'], $form, $form_state);
952  // Render the new output.
953  $new_form = array();
954  $new_form = $form;
955  unset($new_form['#prefix'], $new_form['#suffix']); // Prevent duplicate wrappers.
956  $output = drupal_render($new_form);
957  print drupal_to_js(array('data' => $output, 'status' => true));
958  exit();
959  print '';
960  exit();
961}
962
963/**
964 * Implementation of ente_planificador_importar_terminos_form().
965 * Form to load cvs file in term import
966 */
967function ente_planificador_importar_terminos_form() {
968  $form = array();
969  // If this #attribute is not present, upload will fail on submit
970  $form['#attributes']['enctype'] = 'multipart/form-data';
971  $form['file_import_entes'] = array(
972    '#title' => t('Terminos a importar'),
973    '#type'  => 'file',
974    '#description' => t('Archivo cvs con el contenido de los terminos a importar'),
975  );
976  $vocabularies = taxonomy_get_vocabularies();
977  $vocabulary_options = array();
978  foreach($vocabularies as $vocabulary) {
979    $vocabulary_options[$vocabulary->vid] = $vocabulary->name;
980  }
981  $form['vid'] = array(
982    '#type' => 'select',
983    '#title' => t('Taxonomy'),
984    '#default_value' => !empty($field['vid']) ? $field['vid'] : '',
985    '#options' => $vocabulary_options,
986  );
987  $options = array();
988  for($i = 0;$i < 15; $i++) {
989    if (!$i) {
990      $options[$i] = t('N/A');
991    }
992    else {
993      $options[$i] = t('Fila') . ' ' . $i;
994    }
995  }
996  for ($i=0; $i<=6; $i++) {
997    $form['fieldset_' . $i] = array(
998      '#type' => 'fieldset',
999      '#title' => t('Grupo ') . $i,
1000    );
1001    $form['fieldset_' . $i]['search_parent_' . $i] = array(
1002      '#type' => 'select',
1003      '#title' => t('Parent ') . $i,
1004      '#options' => $options,
1005      '#description' => t("La fila donde se encuentra el parent ") . $i,
1006      '#required' => TRUE,
1007    );
1008    $form['fieldset_' . $i]['nombre_' . $i] = array(
1009      '#type' => 'select',
1010      '#title' => t('Nombre ') . $i,
1011      '#options' => $options,
1012      '#description' => t("La fila donde se encuentra el nombre del termino ") . $i,
1013      '#required' => TRUE,
1014    );
1015    $form['fieldset_' . $i]['description_' . $i] = array(
1016      '#type' => 'select',
1017      '#title' => t('Description ') . $i,
1018      '#options' => $options,
1019      '#description' => t("La fila donde se encuentra el description del termino ") . $i,
1020      '#required' => TRUE,
1021    );
1022  }
1023  /*
1024  $ids = array(
1025    'code' => t('Código'),
1026  );
1027  foreach ($ids as $id =>$text) {
1028    $form[$id] = array(
1029      '#type' => 'select',
1030      '#title' => $text,
1031      '#options' => $options,
1032    );
1033  }*/
1034  $form['encabezado'] = array(
1035    '#title' => 'Primera columna como encabezado',
1036    '#type' => 'checkbox',
1037    '#return_value' => '1',
1038  );
1039  $form['submit'] = array(
1040    '#type' => 'submit',
1041    '#value' => 'Submit',
1042  );
1043  return $form;
1044}
1045
1046/**
1047 * Implementation of ente_planificador_importar_terminos_form_submit().
1048 * Submit cvs file in term import
1049 */
1050function ente_planificador_importar_terminos_form_submit($form, &$form_state) {
1051  global $user;
1052  $validators = array('file_validate_extensions' => array('csv'));
1053  // Check for a new uploaded file.
1054  $file = file_save_upload('file_import_entes');
1055
1056  if (isset($file)) {
1057    // File upload was attempted.
1058    if ($file) {
1059      // Put the temporary file in form_values so we can save it on submit.
1060      $csv = $file->filepath;
1061      $file = fopen($csv, 'r');
1062      $time = time();
1063      $i = 1;
1064      $datas = array();
1065      $batch = array(
1066        'title' => t('Importing terminos ...', array('@format' => $format)),
1067        'operations' => array(),
1068        'init_message' => t('Commencing'),
1069        'progress_message' => t('Processed @current out of @total.'),
1070        'error_message' => t('An error occurred during processing'),
1071        'finished' => '_batch_ente_planificador_importar_term_finished',
1072      );
1073      while (($data = fgetcsv($file)) !== FALSE) {
1074        for ($j=0; $j<=6; $j++) {
1075          if ($form_state['values']['nombre_' . $j] && $data[$form_state['values']['nombre_' . $j] - 1]) {
1076            $term = array(
1077              'vid' => $form_state['values']['vid'], // Voacabulary ID
1078              'name' => check_plain(trim($data[$form_state['values']['nombre_' . $j] - 1])), // Term Name
1079              'description' => check_plain($data[$form_state['values']['description_' . $j] - 1]), // Term description
1080              'search_parent' => FALSE,
1081              /*'fields' => array(
1082                'unidad_codigo1' =>  array(
1083                  'value' => check_plain($data[$form_state['values']['code'] - 1]),
1084                ),
1085              ),*/
1086            );
1087            if ($form_state['values']['search_parent_' . $j] && $data[$form_state['values']['search_parent_' . $j] - 1]) {
1088              $term['search_parent'] = check_plain($data[$form_state['values']['search_parent_' . $j] - 1]);
1089              $term['term_parent'] = check_plain($data[$form_state['values']['search_parent_0']]);
1090            }
1091            if (!($form_state['values']['encabezado'] && $i == 1)) {
1092              $batch['operations'][] = array('_batch_ente_planificador_importar_term', array($term));
1093            }
1094          }
1095        }
1096        $i++;
1097      }
1098      batch_set($batch);
1099      batch_process('ente_planificador_importar/terminos');
1100    }
1101    else {
1102
1103      // File upload failed.
1104      form_set_error('file_import_entes', t('The term file could not be uploaded.'));
1105    }
1106  }
1107}
1108
1109/**
1110 * Implementation of _ente_planificador_importar_terminos_execute().
1111 * Batch 'execute' callback
1112 */
1113function _ente_planificador_importar_terminos_execute($execute_id){
1114  if ($execute_id && isset($_SESSION['ente_planificador_importar_terminos'][$execute_id]) && is_array($_SESSION['ente_planificador_importar_terminos'][$execute_id])) {
1115    $batch = array(
1116      'title' => t('Importing terminos ...', array('@format' => $format)),
1117      'operations' => array(),
1118      'init_message' => t('Commencing'),
1119      'progress_message' => t('Processed @current out of @total.'),
1120      'error_message' => t('An error occurred during processing'),
1121      'finished' => '_batch_ente_planificador_importar_term_finished',
1122    );
1123    $datas = $_SESSION['ente_planificador_importar_terminos'][$execute_id];
1124
1125    unset($_SESSION['ente_planificador_importar_terminos'][$execute_id]);
1126    $cantidad = count($datas);
1127    $i = 1;
1128    foreach($datas as $data) {
1129      $batch['operations'][] = array('_batch_ente_planificador_importar_term', array($data));
1130      $i++;
1131    }
1132    batch_set($batch);
1133    batch_process('ente_planificador_importar/terminos');
1134  }
1135  else {
1136    drupal_set_message(t('Ocurrio un error al intentar importar los entes planificadores'));
1137    drupal_goto('ente_planificador_importar/terminos');
1138  }
1139}
1140
1141/**
1142 * Implementation of _batch_ente_planificador_importar_term_finished().
1143 * Batch 'finished' callback
1144 */
1145function _batch_ente_planificador_importar_term_finished($success, $results, $operations) {
1146  if ($success) {
1147    // Here we do something meaningful with the results.
1148    $message = t('!count_webform terminos processed', array('!count_webform' => count($results)));
1149  }
1150  else {
1151    // An error occurred.
1152    // $operations contains the operations that remained unprocessed.
1153    $error_operation = reset($operations);
1154    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
1155  }
1156  drupal_set_message($message);
1157}
1158
1159/**
1160 * Implementation of _batch_ente_planificador_importar_term().
1161 * display term saved (used in _ente_planificador_importar_terminos_execute)
1162 * Batch run callback
1163 */
1164function _batch_ente_planificador_importar_term($term, &$context) {
1165  //not create if exist
1166  if ($term['search_parent']) {
1167    $db_result = db_query(db_rewrite_sql("SELECT t.tid, t.name FROM {term_data} t WHERE LOWER(t.name) = LOWER('%s') AND vid = %d", 't', 'tid'), trim($term['search_parent']), $term['vid']);
1168    $result = array();
1169    while ($row = db_fetch_array($db_result)) {
1170      if (!empty($row)) {
1171        $parents_all = taxonomy_get_parents_all($row['tid']);
1172        foreach ($parents_all as $parent) {
1173          if ($parent->name == trim($term['search_parent']) && $parents_all[count($parents_all) - 1]->name == trim($term['term_parent'])) {
1174            $parents = array('name' => $parent->name, 'tid_parent' => $row['tid']);
1175
1176            $db_query2 = db_query(db_rewrite_sql("SELECT t.tid, t.name FROM {term_data} t inner join {term_hierarchy} as h on h.tid=t.tid WHERE LOWER(t.name) = LOWER('%s') AND t.vid = %d AND h.parent = %d", 't', 'tid'), trim($term['name']), $term['vid'], $row['tid']);
1177            $rows_query = db_fetch_array($db_query2);
1178            if (!$rows_query['tid']) {
1179              $term['parent'][] = $parents['tid_parent'];
1180              taxonomy_save_term($term);
1181             }
1182           }
1183         }
1184       }
1185     }
1186   }
1187   else {
1188     $db_result = db_query(db_rewrite_sql("SELECT t.tid, t.name FROM {term_data} t INNER JOIN {term_hierarchy} as h ON h.tid=t.tid WHERE LOWER(t.name) = LOWER('%s') AND t.vid = %d AND h.parent = %d", 't', 'tid'), trim($term['name']), $term['vid'], 0);
1189     $rows = db_fetch_array($db_result);
1190
1191     if (!taxonomy_get_term($rows['tid'])) {
1192       taxonomy_save_term($term);
1193     }
1194   }
1195
1196  $context['message'] = t('Now processing ente: %submission', array('%submission' => $term->name));
1197  $context['results'][] = 'term importado: ' . $term->name . '</pre>';
1198}
1199
1200/**
1201 * Implementation of ente_planificador_importar_form().
1202 * Form to load cvs file in entes import
1203 */
1204function ente_planificador_importar_form() {
1205  $form = array();
1206  // If this #attribute is not present, upload will fail on submit
1207  $form['#attributes']['enctype'] = 'multipart/form-data';
1208  $form['file_import_entes'] = array(
1209    '#title' => t('Entes a importar'),
1210    '#type'  => 'file',
1211    '#description' => t('Archivo cvs con el contenido de los entes planificadores a importar'),
1212  );
1213  $options = array();
1214  for($i = 0;$i < 30; $i++) {
1215    if (!$i) {
1216      $options[$i] = t('N/A');
1217    }
1218    else {
1219      $options[$i] = t('Fila') . ' ' . $i;
1220    }
1221  }
1222  $form['titulo'] = array(
1223    '#type' => 'select',
1224    '#title' => t('Titulo'),
1225    '#options' => $options,
1226    '#description' => t("La fila donde se encuentra el nombre del ente."),
1227    '#required' => TRUE,
1228  );
1229  $form['level'] = array(
1230    '#type' => 'select',
1231    '#title' => t('Nivel'),
1232    '#options' => $options,
1233    '#description' => t("La fila donde se encuentra el nivel de jerarquia del ente."),
1234    '#required' => TRUE,
1235  );
1236  $form['father'] = array(
1237    '#type' => 'select',
1238    '#title' => t('Ente padre'),
1239    '#options' => $options,
1240    '#description' => t("La fila donde se encuentra el ente padre del ente."),
1241    '#required' => TRUE,
1242  );
1243  $form['sector'] = array(
1244    '#type' => 'select',
1245    '#title' => t('Sector'),
1246    '#options' => $options,
1247    '#description' => t("La fila donde se encuentra el sector del ente."),
1248  );
1249  $form['acronimo'] = array(
1250    '#type' => 'select',
1251    '#title' => t('Acrónimo'),
1252    '#options' => $options,
1253    '#description' => t("La fila donde se encuentra el acrónimo del ente."),
1254  );
1255  $node_type = content_types('ente_planificador');
1256  $fields = $node_type['fields'];
1257  $campos = array();
1258  if (count($fields)) {
1259    $form['campos'] = array(
1260      '#type' => 'fieldset',
1261      '#title' => t('campos'),
1262    );
1263    foreach($fields as $field_id => $field) {
1264      $campos[$field_id] =  $field;
1265      $form['campos'][$field_id] = array(
1266        '#type' => 'select',
1267        '#title' => $field['widget']['label'],
1268        '#options' => $options,
1269        '#description' => t("La fila donde se encuentra el campo del ente."),
1270      );
1271    }
1272  }
1273  $form['encabezado'] = array(
1274    '#title' => 'Primera columna como encabezado',
1275    '#type' => 'checkbox',
1276    '#return_value' => '1',
1277  );
1278  $form['#ente_fields'] = $campos;
1279  $form['submit'] = array(
1280    '#type' => 'submit',
1281    '#value' => 'Submit',
1282  );
1283  return $form;
1284}
1285
1286/**
1287 * Implementation of ente_planificador_importar_form_submit().
1288 * Submit cvs file in entes import
1289 */
1290function ente_planificador_importar_form_submit($form, &$form_state) {
1291  global $user;
1292  $validators = array('file_validate_extensions' => array('csv'));
1293  // Check for a new uploaded file.
1294  $file = file_save_upload('file_import_entes', $validators);
1295  if (isset($file)) {
1296    // File upload was attempted.
1297    if ($file) {
1298      // Put the temporary file in form_values so we can save it on submit.
1299      $csv = $file->filepath;
1300      $file = fopen($csv, 'r');
1301      $time = time();
1302      $i = 1;
1303      $batch = array(
1304        'title' => t('Importing entes planificadores ...', array('@format' => $format)),
1305        'operations' => array(),
1306        'init_message' => t('Commencing'),
1307        'progress_message' => t('Processed @current out of @total.'),
1308        'error_message' => t('An error occurred during processing'),
1309        'finished' => '_batch_ente_planificador_importar_finished',
1310      );
1311      while (($data = fgetcsv($file)) !== FALSE) {
1312        $ente = new stdClass();
1313        if ($form_state['values']['encabezado'])
1314        $ente->type = 'ente_planificador';
1315        $ente->title = check_plain($data[$form_state['values']['titulo'] - 1]);
1316        $ente->father = $data[$form_state['values']['father'] - 1];
1317        if ($data[$form_state['values']['sector']] -1) {
1318          $ente->sector_social = $data[$form_state['values']['sector'] - 1];
1319        }
1320        if ($data[$form_state['values']['acronimo']] -1) {
1321          $ente->import_acronimo = check_plain($data[$form_state['values']['acronimo'] - 1]);
1322        }
1323        //se agregan los campos
1324        if (count($form['#ente_fields'])) {
1325          foreach($form['#ente_fields'] as $field_id => $field) {
1326            if ($data[$form_state['values'][$field_id]]) {
1327              $tipo = 'value';
1328              if ($field['type'] == 'nodereference') {
1329                $tipo = 'nid';
1330              }
1331              if ($field['type'] == 'userreference') {
1332                $tipo = 'uid';
1333              }
1334              if ($field['type'] == 'email') {
1335                $tipo = 'email';
1336              }
1337              if ($field['type'] == 'link') {
1338                $tipo = 'link';
1339              }
1340              if ($field['type'] == 'content_taxonomy') {
1341                $tipo = 'content_taxonomy';
1342              }
1343              $ente->{$field_id}[0][$tipo] = check_plain($data[$form_state['values'][$field_id] - 1]);
1344            }
1345          }
1346        }
1347        $ente->status = 1;
1348        $ente->tipo = $data[$form_state['values']['level']];
1349        $ente->promote = 0;
1350        $ente->promote = 0;
1351        $ente->sticky = 0;
1352        $ente->uid = $user->uid;
1353        $ente->revision = 1;
1354        $texto = t('Agregado el ente @nombre_ente', array('@nombre_ente' => $ente->title));
1355        $ente->log = $texto;
1356        if (!($form_state['values']['encabezado'] && $i == 1)) {
1357          $batch['operations'][] = array('_batch_ente_planificador_importar', array($ente));
1358          $datas[] = $ente;
1359        }
1360        $i++;
1361      }
1362      batch_set($batch);
1363      batch_process('ente_planificador_importar/entes');
1364    }
1365    else {
1366
1367      // File upload failed.
1368      form_set_error('file_import_entes', t('The entes file could not be uploaded.'));
1369    }
1370  }
1371}
1372
1373/**
1374 * Implementation of _ente_planificador_importar_execute().
1375 * Batch 'execute' callback
1376 */
1377function _ente_planificador_importar_execute($execute_id){
1378  if ($execute_id && isset($_SESSION['ente_planificador_importar'][$execute_id]) && is_array($_SESSION['ente_planificador_importar'][$execute_id])) {
1379    $batch = array(
1380      'title' => t('Importing entes planificadores ...', array('@format' => $format)),
1381      'operations' => array(),
1382      'init_message' => t('Commencing'),
1383      'progress_message' => t('Processed @current out of @total.'),
1384      'error_message' => t('An error occurred during processing'),
1385      'finished' => '_batch_ente_planificador_importar_finished',
1386    );
1387    $datas = $_SESSION['ente_planificador_importar'][$execute_id];
1388
1389    unset($_SESSION['ente_planificador_importar'][$execute_id]);
1390    $cantidad = count($datas);
1391    $i = 1;
1392    foreach($datas as $data) {
1393      $batch['operations'][] = array('_batch_ente_planificador_importar', array($data));
1394    }
1395    batch_set($batch);
1396    batch_process('ente_planificador_importar');
1397  }
1398  else {
1399    drupal_set_message(t('Ocurrio un error al intentar importar los entes planificadores'));
1400    drupal_goto('ente_planificador_importar');
1401  }
1402}
1403
1404/**
1405 * Implementation of _ente_planificador_importar_usuarios().
1406 * Obtiene la cantidad de usuarios por tipo de ente
1407 */
1408function _ente_planificador_importar_usuarios($tipo = 0) {
1409  $cant_usuarios = array();
1410  $cant_usuarios[1] = array(
1411    'for' => 0,
1412    'enl' => 5,
1413    'sup' => 5,
1414  );
1415  $cant_usuarios[2] = array(
1416    'for' => 0,
1417    'enl' => 3,
1418    'sup' => 3,
1419  );
1420  $cant_usuarios[3] = array(
1421    'for' => 10,
1422    'enl' => 2,
1423    'sup' => 1,
1424  );
1425  $cant_usuarios[4] = array(
1426    'for' => 3,
1427    'enl' => 0,
1428    'sup' => 1,
1429  );
1430  return $cant_usuarios[$tipo];
1431}
1432
1433/**
1434 * Implementation of _batch_ente_planificador_importar().
1435 * Save entes (used in _ente_planificador_importar_execute)
1436 * Batch run callback
1437 */
1438function _batch_ente_planificador_importar($ente, &$context) {
1439  $father = $ente->father;
1440  //Se consulta la jerarquia del ente padre
1441  $desc = _ente_planificador_hierarchical_get_descbyacronimo($ente->father);
1442  $count = count($desc);
1443  if ($count) {
1444    foreach($desc as $idfathers) {
1445      if ($idfathers['father']) {
1446        $parent = taxonomy_get_parents($ente->sector_social);
1447        $ente->sector = $ente->sector_social;
1448        $ente->ambito = key($parent);
1449        $ente->ente_planificador_hierarchical[$idfathers['level']] = $idfathers['father'];
1450        $ente->{'ente_planificador_hierarchical_father_' . $idfathers['level']} = $idfathers['father'];
1451      }
1452      else {
1453        $ente->ente_planificador_hierarchical[$idfathers['level']] = $idfathers['nid'];
1454        $ente->{'ente_planificador_hierarchical_father_' . $idfathers['level']} = $idfathers['nid'];
1455      }
1456    }
1457    $ente->{'ente_planificador_hierarchical_father_' . ($count + 1)} = 0;
1458  }
1459  $level = count($ente->ente_planificador_hierarchical[$idfathers['level']]);
1460  if ($level) {
1461    $level++;
1462    //Se ajusta el nivel
1463    if ($ente->tipo != $level) {
1464      $ente->tipo = $level;
1465    }
1466    $acronimo = isset($ente->import_acronimo)? $ente->import_acronimo : 0;
1467    $ente->sector = isset($ente->sector_social)? $ente->sector_social : 0;
1468    node_save($ente);
1469    $falla = $ente->nid ? '' : 'FALLA';
1470    //insert sector
1471
1472    $context['results'][] = 'ente importado: <pre>' . print_r($ente, 1) . $falla . '</pre>';
1473    if ($ente && $ente->nid) {
1474      //Se ingresa el acronimo si existe
1475      if ($acronimo) {
1476        db_query("UPDATE {ente_planificador_hierarchical} SET acronimo = '%s' WHERE nid = %d", $acronimo, $ente->nid);
1477      }
1478      else {
1479        $acronimo = 'ente_' . $acronimo;
1480      }
1481      //se crean los usuarios segun el tipo
1482      $roles_type = _ente_planificador_hierarchical_get_roles_type($ente->tipo);
1483      $cant_usuarios = _ente_planificador_importar_usuarios($ente->tipo);
1484      foreach ($roles_type as $rol => $text) {
1485        $array = array();
1486        $array['roles'] = array();
1487        $array['roles'][DRUPAL_AUTHENTICATED_RID] = DRUPAL_AUTHENTICATED_RID;
1488        $rol_tipo = variable_get('ente_planificador_hierarchical_rol_' . $rol . '_' . $ente->tipo, 2);
1489        //existe el rol para el usuario
1490        if ($rol_tipo && $cant_usuarios[$rol]) {
1491          for ($i = 0; $i < $cant_usuarios[$rol]; $i++) {
1492            $array['roles'][$rol_tipo] = $rol_tipo;
1493            $array['name'] = $acronimo . '_' . $rol . '_' . ($i + 1);
1494            $array['pass'] = $acronimo . '_' . $rol . '_' . ($i + 1);
1495            $array['mail'] = $rol . '_' . ($i + 1) . '@' . 'ente_' . $acronimo . '.com';
1496            $array['status'] = 1;
1497            $array['entes'] = $ente->nid;
1498            user_save(NULL, $array);
1499          }
1500        }
1501      }
1502    }
1503  }
1504  $context['message'] = t('Now processing ente: %submission', array('%submission' => $ente->title));
1505}
1506
1507/**
1508 * Implementation of _batch_ente_planificador_importar_finished().
1509 * Batch 'finished' callback
1510 */
1511function _batch_ente_planificador_importar_finished($success, $results, $operations) {
1512  if ($success) {
1513    // Here we do something meaningful with the results.
1514    $message = t('!count_webform entes processed', array('!count_webform' => print_r($results, TRUE)));
1515  }
1516  else {
1517    // An error occurred.
1518    // $operations contains the operations that remained unprocessed.
1519    $error_operation = reset($operations);
1520    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
1521  }
1522  drupal_set_message($message);
1523}
1524
1525/**
1526 * Implementation of _ente_planificador_hierarchical_get_descbyacronimo().
1527 * Obtiene los padres de un ente por el acronimo o nombre
1528 */
1529function _ente_planificador_hierarchical_get_descbyacronimo($acronimo = '') {
1530  $fathers = array();
1531  //get fathers
1532  if ($acronimo) {
1533    //Se verifica que el arconimo exista
1534    $query = db_query("SELECT * FROM {ente_planificador_hierarchical} WHERE acronimo = '%s'", $acronimo);
1535    $father_acronimo = db_fetch_object($query);
1536    if (!$father_acronimo || !$father_acronimo->acronimo) {
1537      $query = db_query("SELECT h.* FROM {node} AS n INNER JOIN {ente_planificador_hierarchical} AS h ON h.nid = n.nid WHERE n.title = '%s'", $acronimo);
1538      $father_acronimo = db_fetch_object($query);
1539    }
1540    if ($father_acronimo && $father_acronimo->nid) {
1541      $query = db_query('SELECT * FROM {ente_planificador_hierarchical} WHERE nid = %d', $father_acronimo->nid);
1542      while ($father = db_fetch_object($query)) {
1543        $fathers[] = array(
1544          'title' => $father->title,
1545          'nid' =>  $father->nid,
1546          'father' =>  $father->father,
1547          'level' =>  $father->level,
1548          'title' => $father->acronimo,
1549        );
1550      }
1551    }
1552  }
1553  return $fathers;
1554}
1555
1556
1557/**
1558 * Implementation of ente_planificador_importar_aprobar_proyectos_form().
1559 * Form to load cvs file and setting in proyectos estate update
1560 */
1561function ente_planificador_importar_aprobar_proyectos_form() {
1562  $form = array();
1563  // If this #attribute is not present, upload will fail on submit
1564  $form['#attributes']['enctype'] = 'multipart/form-data';
1565  $form['file_import_proyectos'] = array(
1566    '#title' => t('Proyectos a aprobar'),
1567    '#type'  => 'file',
1568    '#description' => t('Archivo cvs con el contenido de los proyectos a aprobar'),
1569  );
1570  $options = array();
1571  for($i = 0;$i < 11; $i++) {
1572    if (!$i) {
1573      $options[$i] = t('N/A');
1574    }
1575    else {
1576      $options[$i] = t('Fila') . ' ' . $i;
1577    }
1578  }
1579  $form['sipes'] = array(
1580    '#type' => 'select',
1581    '#title' => t('Código SIPES del proyecto'),
1582    '#options' => $options,
1583    '#description' => t("La fila donde se encuentra el código SIPES del proyecto."),
1584    '#required' => TRUE,
1585  );
1586  $estados = _proyectos_operativos_reformula_obtiene_estados();
1587  $form['workflow'] = array(
1588    '#type' => 'select',
1589    '#title' => t('Nuevo estado del proyecto'),
1590    '#options' => $estados['states'],
1591    '#description' => t("Seleccione el nuevo estado que se colocara a los proyectos contenidos en el archivo de importación."),
1592    '#required' => TRUE,
1593  );
1594  $form['encabezado'] = array(
1595    '#title' => 'Primera columna como encabezado',
1596    '#type' => 'checkbox',
1597    '#return_value' => '1',
1598  );
1599  $form['submit'] = array(
1600    '#type' => 'submit',
1601    '#value' => 'Submit',
1602  );
1603  return $form;
1604}
1605
1606
1607/**
1608 * Implementation of ente_planificador_importar_aprobar_proyectos_form_submit().
1609 * Submit cvs file in proyectos estate update
1610 */
1611function ente_planificador_importar_aprobar_proyectos_form_submit($form, &$form_state) {
1612  global $user;
1613  $validators = array('file_validate_extensions' => array('csv'));
1614  // Check for a new uploaded file.
1615  $file = file_save_upload('file_import_proyectos', $validators);
1616  if (isset($file)) {
1617    // File upload was attempted.
1618    if ($file) {
1619      // Put the temporary file in form_values so we can save it on submit.
1620      $csv = $file->filepath;
1621      $file = fopen($csv, 'r');
1622      $time = time();
1623      $i = 1;
1624      $datas = array();
1625      $batch = array(
1626        'title' => t('Importing proyectos ...', array('@format' => $format)),
1627        'operations' => array(),
1628        'init_message' => t('Commencing'),
1629        'progress_message' => t('Processed @current out of @total.'),
1630        'error_message' => t('An error occurred during processing'),
1631        'finished' => '_batch_proyecto_operativo_cambiar_estado_importar_finished',
1632      );
1633      while (($data = fgetcsv($file)) !== FALSE) {
1634        $sipes = check_plain($data[$form_state['values']['sipes'] - 1]);
1635        if ($sipes != '') {
1636          $proyecto = array(
1637            'sipes' => $sipes, // codigo sipes
1638            'workflow' => $form_state['values']['workflow'], // workflow
1639            'workflows' => $form['workflow']['#options'], // workflow options
1640          );
1641          if (!($form_state['values']['encabezado'] && $i == 1)) {
1642            $batch['operations'][] = array('_batch_proyecto_operativo_cambiar_estado_importar', array($proyecto));
1643          }
1644          $i++;
1645        }
1646      }
1647      batch_set($batch);
1648      batch_process('ente_planificador_importar/estadoproyecto');
1649    }
1650    else {
1651
1652      // File upload failed.
1653      form_set_error('file_import_proyectos', t('The proyectos file could not be uploaded.'));
1654    }
1655  }
1656}
1657
1658
1659/**
1660 * Implementation of _batch_proyecto_operativo_cambiar_estado_importar().
1661 * Update state proyectos (used in ente_planificador_importar_aprobar_proyectos_form_submit)
1662 * Batch run callback
1663 */
1664function _batch_proyecto_operativo_cambiar_estado_importar($proyecto, &$context) {
1665  $context['message'] = t('Now processing proyecto: %submission', array('%submission' => check_plain($proyecto['sipes'])));
1666  $query = db_query("SELECT nid FROM {node} WHERE title = '%s'", $proyecto['sipes']);
1667  $proyecto_nid = db_fetch_object($query);
1668  if ($proyecto_nid && $proyecto_nid->nid) {
1669    $node = node_load($proyecto_nid->nid);
1670    if ($node->nid) {
1671      if ($node->_workflow != $proyecto['workflow']) {
1672        $context['results'][] = t('Actualizado el proyecto @proyecto desde el estado @ant al @prox ', array('@proyecto' => $proyecto['sipes'], '@ant' => $proyecto['workflows'][$node->_workflow], '@prox' => $proyecto['workflows'][$proyecto['workflow']]));
1673        $node->_workflow = $proyecto['workflow'];
1674        $node->revision = 1;
1675        $texto = t('Se cambio el proyecto @nombre del estado @estado al @estado_next', array('@nombre' => $node->title, '@estado' => $proyecto['workflows'][$node->_workflow], '@estado_next' => $proyecto['workflows'][$proyecto['workflow']]));
1676        $node->log = $texto;
1677        $node->_workflow = $proyecto['workflow'];
1678        node_save($node);
1679      }
1680      else {
1681        $context['results'][] = t('El proyecto @proyecto ya se encuentra en el estado @prox ', array('@proyecto' => $proyecto['sipes'], '@prox' => $proyecto['workflows'][$proyecto['workflow']]));
1682      }
1683    }
1684    else {
1685      $context['results'][] = t('No se encontro el proyecto @proyecto', array('@proyecto' => $proyecto['sipes']));
1686    }
1687  }
1688  else {
1689    $context['results'][] = t('No se encontro el proyecto @proyecto', array('@proyecto' => $proyecto['sipes']));
1690  }
1691}
1692
1693/**
1694 * Implementation of _batch_ente_planificador_importar_finished().
1695 * Batch 'finished' callback
1696 */
1697function _batch_proyecto_operativo_cambiar_estado_importar_finished($success, $results, $operations) {
1698  if ($success) {
1699    // Here we do something meaningful with the results.
1700    $message = t('!count_webform entes processed', array('!count_webform' => '<pre>' . print_r($results, TRUE) . '</pre>'));
1701  }
1702  else {
1703    // An error occurred.
1704    // $operations contains the operations that remained unprocessed.
1705    $error_operation = reset($operations);
1706    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
1707  }
1708  drupal_set_message($message);
1709}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.