Index: 0.3-modules/ente_planificador_importar/ente_planificador_importar.module
===================================================================
--- 0.3-modules/ente_planificador_importar/ente_planificador_importar.module	(revision f9d3d85ccc786ac30fedc5fa653eeab9a22bb7c4)
+++ 0.3-modules/ente_planificador_importar/ente_planificador_importar.module	(revision 546c8631b28be300fbc5318f032986c83f12aac2)
@@ -2,5 +2,5 @@
 
   /**
-  * Modulo para importar entes y terminos 
+  * Modulo para importar entes y terminos
   * Sistema Automatizado para la PlanificaciÃ³n EstratÃ©gico-Situacional en la AdministraciÃ³n PÃºblica Venezolana
   * @file ente_planificador_importar.module
@@ -12,10 +12,10 @@
   * the Free Software Foundation; either version 2 of the License, or
   * (at your option) any later version.
-  * 
+  *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
-  * 
+  *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
@@ -59,4 +59,11 @@
     'type' => MENU_CALLBACK,
   );
+  $items['ente_planificador_importar/updb_proyectos'] = array(
+    'title' => 'Importar Entes Planificadores',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('ente_planificador_importar_updb_proyectos_form'),
+    'access arguments' => array('import entes planificadores'),
+    'type' => MENU_CALLBACK,
+  );
   $items['ente_planificador_importar/terminos'] = array(
     'title' => 'Importar Terminos',
@@ -120,5 +127,5 @@
     $links['entes'] = array(
       'data' => l(t('Importar Entes Planificadores'), 'ente_planificador_importar/entes'),
-      'class' => 'ente-planificador-importar-entes', 
+      'class' => 'ente-planificador-importar-entes',
     );
   }
@@ -126,13 +133,13 @@
     $links['term1'] = array(
       'data' => l(t('Importar terminos'), 'ente_planificador_importar/terminos'),
-      'class' => 'ente-planificador-importar-term', 
+      'class' => 'ente-planificador-importar-term',
     );
     $links['term2'] = array(
       'data' => l(t('Importar Campos de terminos'), 'ente_planificador_importar/terminos/fields'),
-      'class' => 'ente-planificador-importar-term-fields', 
+      'class' => 'ente-planificador-importar-term-fields',
     );
     $links['term_parent'] = array(
       'data' => l(t('Relacionar taxonomias y guardar valores en un campo del termino'), 'ente_planificador_importar/terminos/relations_fields'),
-      'class' => 'ente-planificador-importar-term-parents-fields', 
+      'class' => 'ente-planificador-importar-term-parents-fields',
     );
   }
@@ -140,5 +147,5 @@
     $links['estadoproyecto'] = array(
       'data' => l(t('Actualizar estado de proyectos'), 'ente_planificador_importar/estadoproyecto'),
-      'class' => 'ente-planificador-importar-estado-proyecto', 
+      'class' => 'ente-planificador-importar-estado-proyecto',
     );
   }
@@ -147,5 +154,5 @@
 /**
  * Implementation of ente_planificador_importar_terminos_form().
- * Form to load cvs file in term import 
+ * Form to load cvs file in term import
  */
 function ente_planificador_importar_terminos_relations_fields_form(&$form_state) {
@@ -193,5 +200,5 @@
 /**
  * Implementation of ente_planificador_importar_terminos_form_submit().
- * Submit cvs file in term import 
+ * Submit cvs file in term import
  */
 function ente_planificador_importar_terminos_relations_fields_form_submit($form, &$form_state) {
@@ -279,11 +286,5 @@
 
 function ente_planificador_importar_terminos_relations_fields_name($vid) {
-  $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);
-  
+  $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);
   while ($term = db_fetch_object($result)) {
     $terms[trim($term->name)] = $term;
@@ -422,5 +423,5 @@
   $output = drupal_render($new_form);
   print drupal_to_js(array('data' => $output, 'status' => true));
-  exit(); 
+  exit();
   print '';
   exit();
@@ -431,5 +432,5 @@
  * Implementation of _batch_ente_planificador_importar_term_fields().
  * display term saved (used in _ente_planificador_importar_terminos_execute)
- * Batch run callback  
+ * Batch run callback
  */
 function _batch_ente_planificador_importar_term_relations_fields($term, &$context) {
@@ -460,6 +461,264 @@
 
 /**
+ * Update values of field to type content
+ */
+function ente_planificador_importar_updb_proyectos_form(&$form_state) {
+  $form = array();
+  // If this #attribute is not present, upload will fail on submit
+  $form['#attributes']['enctype'] = 'multipart/form-data';
+  $form['file_import_entes'] = array(
+    '#title' => t('Archivo a importar'),
+    '#type'  => 'file',
+    '#description' => t('Archivo cvs con el contenido de los terminos a importar'),
+    '#weight' => -1,
+  );
+
+  $options = array();
+  for ($i = 0;$i < 30; $i++) {
+    if (!$i) {
+      $options[$i] = t('N/A');
+    }
+    else {
+      $options[$i] = t('Fila') . ' ' . $i;
+    }
+  }
+
+  $delimiter_option = array(",",";");
+  $form['delimiter']= array(
+    '#type' => 'select',
+    '#title' => t('Tipo de Delimitador'),
+    '#options' => $delimiter_option,
+    '#description' => t("Delimitador del archivo csv."),
+    '#required' => TRUE,
+    '#weight' => -1,
+    '#default_value' => ",",
+  );
+
+  $form['field_name'] = array(
+    '#type' => 'select',
+    '#title' => t('Nombre del campo'),
+    '#options' => $options,
+    '#description' => t("La fila donde se encuentra el nombre del Campo a modificar."),
+    '#required' => TRUE,
+    '#weight' => 0,
+    '#default_value' => 1,
+  );
+
+  $form['field_nid'] = array(
+    '#type' => 'select',
+    '#title' => t('Nid del nodo'),
+    '#options' => $options,
+    '#description' => t("La fila donde se encuentra el nid del nodo a modificar."),
+    '#required' => TRUE,
+    '#weight' => 1,
+    '#default_value' => 2,
+  );
+
+  $form['field_vid'] = array(
+    '#type' => 'select',
+    '#title' => t('Vid del campo'),
+    '#options' => $options,
+    '#description' => t("La fila donde se encuentra el vid del nodo a modificar."),
+    '#required' => TRUE,
+    '#weight' => 2,
+    '#default_value' => 3,
+  );
+
+  $form['type_content'] = array(
+    '#type' => 'select',
+    '#title' => t('tipo de contenido del campo'),
+    '#options' => $options,
+    '#description' => t("seleccione la columna donde se encuentre el tipo de contenido del campo."),
+    '#required' => TRUE,
+    '#weight' => 3,
+    '#default_value' => 4,
+  );
+
+  $form['field_delta'] = array(
+    '#type' => 'select',
+    '#title' => t('Delta del campo'),
+    '#options' => $options,
+    '#description' => t("si el campo es multiple seleccione la columna donde se encuentre el delta."),
+    '#required' => TRUE,
+    '#weight' => 4,
+  );
+
+  $form['field_tid'] = array(
+    '#type' => 'select',
+    '#title' => t('tid del campo'),
+    '#options' => $options,
+    '#description' => t("si el campo es multiple seleccione la columna donde se encuentre el tid."),
+    '#required' => TRUE,
+    '#weight' => 5,
+  );
+
+  $form['fields'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Campos'),
+    '#weight' => 6,
+  );
+  for ($i=0; $i<12; $i++) {
+    $form['fields']['field_value_' . $i] = array(
+      '#type' => 'select',
+      '#title' => t('Valor del campo ' . $i),
+      '#options' => $options,
+      '#description' => t("La fila donde se encuentra el valor del nodo a modificar."),
+      '#required' => TRUE,
+      '#weight' => $i,
+      '#default_value' => ($i==0) ? 7 : 0 ,
+    );
+  }
+
+  $form['encabezado'] = array(
+    '#title' => 'Primera columna como encabezado',
+    '#type' => 'checkbox',
+    '#return_value' => '1',
+    '#weight' => 7,
+    '#default_value' => TRUE,
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => 'Submit',
+    '#weight' => 35,
+  );
+  return $form;
+}
+
+/**
+ * Implementation of function ente_planificador_importar_updb_proyectos_form().
+ * Update values of field to type content
+ */
+function ente_planificador_importar_updb_proyectos_form_submit($form, &$form_state) {
+  global $user;
+  $validators = array('file_validate_extensions' => array('csv'));
+  // Check for a new uploaded file.
+  $file = file_save_upload('file_import_entes', $validators);
+  if (isset($file)) {
+    include_once('./'. drupal_get_path('module', 'content') .'/content.install');
+    drupal_load('module', 'content');
+    // $types = content_types_install();
+    // if (empty($types)) {
+    //   return $ret;
+    // }
+
+    // File upload was attempted.
+    if ($file) {
+
+      // Put the temporary file in form_values so we can save it on submit.
+      $csv = $file->filepath;
+      $file = fopen($csv, 'r');
+      $time = time();
+      $i = 1;
+      $batch = array(
+        'title' => t('Update value proyects and acciones ...', array('@format' => $format)),
+        'operations' => array(),
+        'init_message' => t('Commencing'),
+        'progress_message' => t('Processed @current out of @total.'),
+        'error_message' => t('An error occurred during processing'),
+        'finished' => '_batch_ente_planificador_importar_finished',
+      );
+
+      //read the csv archive
+      $data_all =  fread($file, filesize($csv));
+      $fgetslines = explode("\n",$data_all);
+      $process = count($fgetslines);
+      $process = $form_state['values']['encabezado'] && $i == 1 ? $process-1 : $process ;
+      $encabezado = $form_state['values']['encabezado'] && $i == 1 ? 1 : 0 ;
+
+      for ($k=$encabezado; $k < $process; $k++) {
+        $data_line = explode("\n",$data_all);
+        $data_line_all = $data_line[$k];
+        $delimet = $form_state['values']['delimiter'] ? ";" : "," ;
+        $data = explode($delimet,$data_line_all);
+
+        $batch['operations'][] = array('_ente_planificador_importar_updb_proyectos_importar', array( $data, $form_state['values']));
+      }
+
+      batch_set($batch);
+      batch_process('ente_planificador_importar/updb_proyectos');
+    }
+    else {
+
+      // File upload failed.
+      form_set_error('file_import_entes', t('The entes file could not be uploaded.'));
+    }
+  }
+}
+
+/**
+ * Update values of field to type content
+ * Batch run callback
+ */
+ function _ente_planificador_importar_updb_proyectos_importar( $data, $formstate_values, &$context) {
+
+   $fields_update = trim($data[$formstate_values['field_name']-1]);
+   $field = content_fields($fields_update, $data[$formstate_values['type_content']-1]);
+   $values[] = $field;
+   $index = array();
+   for ($i=0; $i<12; $i++) {
+     $index[] = $i === 0? 'value' : 'value_' . $i;
+   }
+
+   $rate = 100000;
+   $sql = '';
+   foreach ($values as $field) {
+     if ($field['multiple']) {
+       $sql.=' and delta = '. $data[$formstate_values['field_delta']-1];
+     }
+     $db_info = content_database_info($field);
+     if (array_key_exists('tid', $db_info['columns'])) {
+       $sql.= ' and ' . $db_info['columns']['tid']['column'] . ' = ' . $data[$formstate_values['field_tid']-1] ;
+
+     }
+     $table = $db_info['table'];
+     $columns = array();
+
+     foreach($index as $key => $id) {
+       if (isset($db_info['columns'][$id])) {
+         $value = trim($data[$formstate_values['field_value_' . $key]-1]);
+         $attributes = $db_info['columns'][$id];
+         $column = $attributes['column'];
+
+         $decimals = ($field['scale']) && is_numeric($field['scale']) ? $field['scale'] : 0;
+         if(!$value==0) {
+
+           //$columns[] = $column  . ' = round(' . $value . '/' . $rate . ', ' . 8 . ')';
+
+           // Divide monto 
+           // $value_table = round($value/$rate,8);
+
+           //Directamente sin dividir montos
+           $columns[] = $column .'='.$value;
+
+         } else {
+           $columns[] = $column  . ' = 0 ';
+         }
+       }
+     }
+
+     //sql que se va a pasar visto en Entradas recientes del registro
+     // $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 );
+     // watchdog('Test Sipes', '$decimals @filename.', array('@filename' => print_r($sql1,1)), WATCHDOG_ERROR);
+    //endsql que se va a pasar visto en Entradas recientes del registro
+
+     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 );
+   }
+
+   $context['message'] = t('Now processing nid of node: %submission', array('%submission' => trim($data[$formstate_values['field_nid']-1])));
+   $context['results'][] = 'Node update: ' . trim($data[$formstate_values['field_nid']-1]) . '</pre>';
+
+   if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
+     $context['finished'] = 1;
+   } else {
+     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
+   }
+ }
+
+
+
+/**
  * Implementation of ente_planificador_importar_terminos_form().
- * Form to load cvs file in term import 
+ * Form to load cvs file in term import
  */
 function ente_planificador_importar_terminos_fields_form(&$form_state) {
@@ -499,5 +758,5 @@
 /**
  * Implementation of ente_planificador_importar_terminos_form_submit().
- * Submit cvs file in term import 
+ * Submit cvs file in term import
  */
 function ente_planificador_importar_terminos_fields_form_submit($form, &$form_state) {
@@ -530,5 +789,5 @@
 
       while (($data = fgetcsv($file)) !== FALSE) {
-         $taxonomy = taxonomy_vocabulary_load($form_state['values']['vid']); 
+         $taxonomy = taxonomy_vocabulary_load($form_state['values']['vid']);
          $terms = taxonomy_get_tree($taxonomy->vid);
          $name_field = check_plain($data[$form_state['values']['nombre'] - 1]);
@@ -567,5 +826,5 @@
  * Implementation of _batch_ente_planificador_importar_term_fields().
  * display term saved (used in _ente_planificador_importar_terminos_execute)
- * Batch run callback  
+ * Batch run callback
  */
 function _batch_ente_planificador_importar_term_fields($term, &$context) {
@@ -697,5 +956,5 @@
   $output = drupal_render($new_form);
   print drupal_to_js(array('data' => $output, 'status' => true));
-  exit(); 
+  exit();
   print '';
   exit();
@@ -704,5 +963,5 @@
 /**
  * Implementation of ente_planificador_importar_terminos_form().
- * Form to load cvs file in term import 
+ * Form to load cvs file in term import
  */
 function ente_planificador_importar_terminos_form() {
@@ -787,5 +1046,5 @@
 /**
  * Implementation of ente_planificador_importar_terminos_form_submit().
- * Submit cvs file in term import 
+ * Submit cvs file in term import
  */
 function ente_planificador_importar_terminos_form_submit($form, &$form_state) {
@@ -850,5 +1109,5 @@
 /**
  * Implementation of _ente_planificador_importar_terminos_execute().
- * Batch 'execute' callback 
+ * Batch 'execute' callback
  */
 function _ente_planificador_importar_terminos_execute($execute_id){
@@ -882,5 +1141,5 @@
 /**
  * Implementation of _batch_ente_planificador_importar_term_finished().
- * Batch 'finished' callback 
+ * Batch 'finished' callback
  */
 function _batch_ente_planificador_importar_term_finished($success, $results, $operations) {
@@ -901,5 +1160,5 @@
  * Implementation of _batch_ente_planificador_importar_term().
  * display term saved (used in _ente_planificador_importar_terminos_execute)
- * Batch run callback  
+ * Batch run callback
  */
 function _batch_ente_planificador_importar_term($term, &$context) {
@@ -914,5 +1173,5 @@
           if ($parent->name == trim($term['search_parent']) && $parents_all[count($parents_all) - 1]->name == trim($term['term_parent'])) {
             $parents = array('name' => $parent->name, 'tid_parent' => $row['tid']);
-               
+
             $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']);
             $rows_query = db_fetch_array($db_query2);
@@ -941,5 +1200,5 @@
 /**
  * Implementation of ente_planificador_importar_form().
- * Form to load cvs file in entes import 
+ * Form to load cvs file in entes import
  */
 function ente_planificador_importar_form() {
@@ -1003,5 +1262,5 @@
     );
     foreach($fields as $field_id => $field) {
-      $campos[$field_id] =  $field; 
+      $campos[$field_id] =  $field;
       $form['campos'][$field_id] = array(
         '#type' => 'select',
@@ -1027,5 +1286,5 @@
 /**
  * Implementation of ente_planificador_importar_form_submit().
- * Submit cvs file in entes import 
+ * Submit cvs file in entes import
  */
 function ente_planificador_importar_form_submit($form, &$form_state) {
@@ -1114,5 +1373,5 @@
 /**
  * Implementation of _ente_planificador_importar_execute().
- * Batch 'execute' callback 
+ * Batch 'execute' callback
  */
 function _ente_planificador_importar_execute($execute_id){
@@ -1145,5 +1404,5 @@
 /**
  * Implementation of _ente_planificador_importar_usuarios().
- * Obtiene la cantidad de usuarios por tipo de ente 
+ * Obtiene la cantidad de usuarios por tipo de ente
  */
 function _ente_planificador_importar_usuarios($tipo = 0) {
@@ -1175,5 +1434,5 @@
  * Implementation of _batch_ente_planificador_importar().
  * Save entes (used in _ente_planificador_importar_execute)
- * Batch run callback  
+ * Batch run callback
  */
 function _batch_ente_planificador_importar($ente, &$context) {
@@ -1218,5 +1477,5 @@
       }
       else {
-        $acronimo = 'ente_' . $acronimo; 
+        $acronimo = 'ente_' . $acronimo;
       }
       //se crean los usuarios segun el tipo
@@ -1248,5 +1507,5 @@
 /**
  * Implementation of _batch_ente_planificador_importar_finished().
- * Batch 'finished' callback 
+ * Batch 'finished' callback
  */
 function _batch_ente_planificador_importar_finished($success, $results, $operations) {
@@ -1298,5 +1557,5 @@
 /**
  * Implementation of ente_planificador_importar_aprobar_proyectos_form().
- * Form to load cvs file and setting in proyectos estate update 
+ * Form to load cvs file and setting in proyectos estate update
  */
 function ente_planificador_importar_aprobar_proyectos_form() {
@@ -1401,5 +1660,5 @@
  * Implementation of _batch_proyecto_operativo_cambiar_estado_importar().
  * Update state proyectos (used in ente_planificador_importar_aprobar_proyectos_form_submit)
- * Batch run callback  
+ * Batch run callback
  */
 function _batch_proyecto_operativo_cambiar_estado_importar($proyecto, &$context) {
@@ -1434,5 +1693,5 @@
 /**
  * Implementation of _batch_ente_planificador_importar_finished().
- * Batch 'finished' callback 
+ * Batch 'finished' callback
  */
 function _batch_proyecto_operativo_cambiar_estado_importar_finished($success, $results, $operations) {
@@ -1449,3 +1708,2 @@
   drupal_set_message($message);
 }
-
