[ Index ]
 

Code source de eGroupWare 1.2.106-2

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/infolog/ -> csv_import.php (source)

   1  <?php
   2    /**************************************************************************\
   3    * eGroupWare - InfoLog: CSV - Import                                       *
   4    * http://www.egroupware.org                                                *
   5    * Written by Ralf Becker <RalfBecker@outdoor-training.de>                  *
   6    * --------------------------------------------                             *
   7    *  This program is free software; you can redistribute it and/or modify it *
   8    *  under the terms of the GNU General Public License as published by the   *
   9    *  Free Software Foundation; either version 2 of the License, or (at your  *
  10    *  option) any later version.                                              *
  11    \**************************************************************************/
  12  
  13    /* $Id: csv_import.php 22409 2006-09-11 07:17:32Z ralfbecker $ */
  14  
  15      $GLOBALS['egw_info']['flags'] = array(
  16          'currentapp' => 'infolog',
  17          'noheader'   => True,
  18          'enable_contacts_class' => True,
  19      );
  20      include('../header.inc.php');
  21  
  22      if (!isset($GLOBALS['egw_info']['user']['apps']['admin']) ||
  23          !$GLOBALS['egw_info']['user']['apps']['admin'])        // no admin
  24      {
  25          $GLOBALS['egw']->redirect_link('/home.php');
  26      }
  27      if (isset($_FILES['csvfile']['tmp_name']))
  28      {
  29          $csvfile = tempnam($GLOBALS['egw_info']['server']['temp_dir'],$GLOBALS['egw_info']['flags']['currentapp']."_");
  30          $GLOBALS['egw']->session->appsession('csvfile','',$csvfile);
  31          $_POST['action'] = move_uploaded_file($_FILES['csvfile']['tmp_name'],$csvfile) ?
  32              'download' : '';
  33      }
  34      else
  35      {
  36          $csvfile = $GLOBALS['egw']->session->appsession('csvfile');
  37      }
  38      if ($_POST['cancel'])
  39      {
  40          @unlink($csvfile);
  41          $GLOBALS['egw']->redirect_link('/admin/index.php');
  42      }
  43      $GLOBALS['egw_info']['flags']['app_header'] = lang('InfoLog - Import CSV-File');
  44      $GLOBALS['egw']->common->egw_header();
  45  
  46      $boinfolog = createobject('infolog.boinfolog');
  47  
  48      $GLOBALS['egw']->template->set_file(array('import_t' => 'csv_import.tpl'));
  49      $GLOBALS['egw']->template->set_block('import_t','filename','filenamehandle');
  50      $GLOBALS['egw']->template->set_block('import_t','fheader','fheaderhandle');
  51      $GLOBALS['egw']->template->set_block('import_t','fields','fieldshandle');
  52      $GLOBALS['egw']->template->set_block('import_t','ffooter','ffooterhandle');
  53      $GLOBALS['egw']->template->set_block('import_t','imported','importedhandle');
  54      $GLOBALS['egw']->template->set_block('import_t','import','importhandle');
  55  
  56  
  57      if(($_POST['action'] == 'download' || $_POST['action'] == 'continue') && (!$_POST['fieldsep'] || !$csvfile || !($fp=fopen($csvfile,'rb'))))
  58      {
  59          $_POST['action'] = '';
  60      }
  61      $GLOBALS['egw']->template->set_var("action_url",$GLOBALS['egw']->link("/infolog/csv_import.php"));
  62  
  63      $PSep = '||'; // Pattern-Separator, separats the pattern-replacement-pairs in trans
  64      $ASep = '|>'; // Assignment-Separator, separats pattern and replacesment
  65      $VPre = '|#'; // Value-Prefix, is expanded to \ for ereg_replace
  66      $CPre = '|['; $CPreReg = '\|\['; // |{csv-fieldname} is expanded to the value of the csv-field
  67      $CPos = ']';  $CPosReg = '\]';    // if used together with @ (replacement is eval-ed) value gets autom. quoted
  68  
  69  function addr_id( $n_family,$n_given=null,$org_name=null )
  70  {        // find in Addressbook, at least n_family AND (n_given OR org_name) have to match
  71      static $contacts;
  72      if (!is_object($contacts))
  73      {
  74          $contacts =& CreateObject('phpgwapi.contacts');
  75      }
  76      if (!is_null($org_name))    // org_name given?
  77      {
  78          $addrs = $contacts->read( 0,0,array('id'),'',"n_family=$n_family,n_given=$n_given,org_name=$org_name" );
  79          if (!count($addrs))
  80          {
  81              $addrs = $contacts->read( 0,0,array('id'),'',"n_family=$n_family,org_name=$org_name",'','n_family,org_name');
  82          }
  83      }
  84      if (!is_null($n_given) && (is_null($org_name) || !count($addrs)))    // first name given and no result so far
  85      {
  86          $addrs = $contacts->read( 0,0,array('id'),'',"n_family=$n_family,n_given=$n_given",'','n_family,n_given' );
  87      }
  88      if (is_null($n_given) && is_null($org_name))    // just one name given, check against fn (= full name)
  89      {
  90          $addrs = $contacts->read( 0,0,array('id'),'',"fn=$n_family",'','fn' );
  91      }
  92      if (count($addrs))
  93      {
  94          return $addrs[0]['id'];
  95      }
  96      return False;
  97  }
  98  
  99  function project_id($num_or_title)
 100  {
 101      static $boprojects;
 102  
 103      if (!$num_or_title) return false;
 104  
 105      if (!is_object($boprojects))
 106      {
 107          $boprojects =& CreateObject('projectmanager.boprojectmanager');
 108      }
 109      if (($projects = $boprojects->search(array('pm_number' => $num_or_title))) ||
 110          ($projects = $boprojects->search(array('pm_title'  => $num_or_title))))
 111      {
 112          return $projects[0]['pm_id'];
 113      }
 114      return false;
 115  }
 116  
 117  $cat2id = array( );
 118  
 119  function cat_id($cats)
 120  {
 121      if (!$cats)
 122      {
 123          return '';
 124      }
 125  
 126      // no multiple cat's in InfoLog atm.
 127      foreach(array($cats) /*split('[,;]',$cats)*/ as $cat)
 128      {
 129          if (isset($cat2id[$cat]))
 130          {
 131              $ids[$cat] = $cat2id[$cat];    // cat is in cache
 132          }
 133          else
 134          {
 135              if (!is_object($GLOBALS['egw']->categories))
 136              {
 137                  $GLOBALS['egw']->categories = createobject('phpgwapi.categories');
 138              }
 139              if (is_numeric($cat) && $GLOBALS['egw']->categories->id2name($cat) != '--')
 140              {
 141                  $cat2id[$cat] = $ids[$cat] = $cat;
 142              }    
 143              elseif (($id = $GLOBALS['egw']->categories->name2id( addslashes($cat) )))
 144              {    // cat exists
 145                  $cat2id[$cat] = $ids[$cat] = $id;
 146              }
 147              else
 148              {    // create new cat
 149                  $GLOBALS['egw']->categories->add( array('name' => $cat,'descr' => $cat ));
 150                  $cat2id[$cat] = $ids[$cat] = $GLOBALS['egw']->categories->name2id( addslashes($cat) );
 151              }
 152          }
 153      }
 154      $id_str = implode( ',',$ids );
 155  
 156      if (count($ids) > 1)        // multiple cats need to be in ','
 157      {
 158          $id_str = ",$id_str,";
 159      }
 160      return  $id_str;
 161  }
 162  
 163      if (!is_object($GLOBALS['egw']->html))
 164      {
 165          $GLOBALS['egw']->html =& CreateObject('phpgwapi.html');
 166      }
 167  
 168      if ($_POST['next']) $_POST['action'] = 'next';
 169      switch ($_POST['action'])
 170      {
 171      case '':    // Start, ask Filename
 172          $GLOBALS['egw']->template->set_var('lang_csvfile',lang('CSV-Filename'));
 173          $GLOBALS['egw']->template->set_var('lang_fieldsep',lang('Fieldseparator'));
 174          $GLOBALS['egw']->template->set_var('lang_charset',lang('Charset of file'));
 175          $GLOBALS['egw']->template->set_var('select_charset',
 176              $GLOBALS['egw']->html->select('charset','',
 177              $GLOBALS['egw']->translation->get_installed_charsets()+
 178              array('utf-8' => 'utf-8 (Unicode)'),True));
 179          $GLOBALS['egw']->template->set_var('fieldsep',$_POST['fieldsep'] ? $_POST['fieldsep'] : ';');
 180          $GLOBALS['egw']->template->set_var('submit',lang('Import'));
 181          $GLOBALS['egw']->template->set_var('enctype','ENCTYPE="multipart/form-data"');
 182  
 183          $GLOBALS['egw']->template->parse('rows','filename');
 184          break;
 185  
 186      case 'continue':
 187      case 'download':
 188          $GLOBALS['egw']->preferences->read_repository();
 189          $defaults = $GLOBALS['egw_info']['user']['preferences']['infolog']['cvs_import'];
 190          if (!is_array($defaults))
 191          {
 192              $defaults = array();
 193          }
 194          $GLOBALS['egw']->template->set_var('lang_csv_fieldname',lang('CSV-Fieldname'));
 195          $GLOBALS['egw']->template->set_var('lang_info_fieldname',lang('InfoLog-Fieldname'));
 196          $GLOBALS['egw']->template->set_var('lang_translation',lang("Translation").' <a href="#help">'.lang('help').'</a>');
 197          $GLOBALS['egw']->template->set_var('submit',
 198              $GLOBALS['egw']->html->submit_button('convert','Import') . '&nbsp;'.
 199              $GLOBALS['egw']->html->submit_button('cancel','Cancel'));
 200          $GLOBALS['egw']->template->set_var('lang_debug',lang('Test Import (show importable records <u>only</u> in browser)'));
 201          $GLOBALS['egw']->template->parse('rows','fheader');
 202  
 203          $info_names = array(    
 204              'type'        => 'Type: char(10) task,phone,note',
 205              'from'        => 'From: text(255) free text if no Addressbook-entry assigned',
 206              'addr'        => 'Addr: text(255) phone-nr/email-address',
 207              'subject'     => 'Subject: text(255)',
 208              'des'         => 'Description: text long free text',
 209              'location'    => 'Location: text(255)',
 210              'responsible' => 'Responsible: int(11) user-id or user-name',
 211              'owner'       => 'Owner: int(11) user-id/-name of owner, if empty current user',
 212              'access'      => 'Access: public,private',
 213              'cat'         => 'Category: int(11) category-id or -name (new ones got created)',
 214              'startdate'   => 'Start Date: DateTime: Timestamp or eg. YYYY-MM-DD hh:mm',
 215              'enddate'     => 'End Date: DateTime',
 216              'datecompleted'=> 'Date completed: DateTime',
 217              'datemodified'=> 'Date Last Modified: DateTime, if empty = Date Created',
 218              'modifier'    => 'Modifier: int(11) user-id, if empty current user',
 219              'priority'    => 'Priority: 3=urgent, 2=high, 1=normal, 0=low',
 220              'planned_time'=> 'planned Time: int(11) time used in min',
 221              'used_time'   => 'used Time: int(11) time used in min',
 222              'status'      => 'Status: char(10) offer,not-started,ongoing,call,will-call,done,billed,cancelled',
 223              'percent'     => 'Percent completed: int',
 224  //            'confirm'     => 'Confirmation: char(10) not,accept,finish,both when to confirm',
 225              'project_id'  => 'Link to Projectmanager, use Project-ID, Title or @project_id(id_or_title)',
 226              'addr_id'     => 'Link to Addressbook, use nlast,nfirst[,org] or @addr_id(nlast,nfirst,org)',
 227              'link_1'      => '1. link: appname:appid the entry should be linked to, eg.: addressbook:123',
 228              'link_2'      => '2. link: appname:appid the entry should be linked to, eg.: addressbook:123',
 229              'link_3'      => '3. link: appname:appid the entry should be linked to, eg.: addressbook:123',
 230          );
 231          // add custom fields
 232          if ($boinfolog->customfields)
 233          {
 234              foreach($boinfolog->customfields as $name => $field)
 235              {
 236                  if ($field['type'] == 'label' || !count($field['values']) && $field['rows'] <= 1 && $field['len'] <= 0) continue;
 237  
 238                  $info_names['#'.$name] = lang('custom fields').': '.$field['label'];
 239              }
 240          }
 241  
 242          // the next line is used in the help-text too
 243          $mktime_lotus = "$PSep}0?([0-9]+)[ .:-]+0?([0-9]*)[ .:-]+0?([0-9]*)[ .:-]+0?([0-9]*)[ .:-]+0?([0-9]*)[ .:-]+0?([0-9]*).*$ASep@mktime($VPre}4,$VPre}5,$VPre}6,$VPre}2,$VPre}3,$VPre}1)";
 244  
 245          /* this are settings to import from Lotus Organizer
 246          $defaults += array(    'Land'            => "addr$PSep.*[(]+([0-9]+)[)]+$ASep+${VPre}1 (${CPre}Ortsvorwahl$CPos) ${CPre}Telefon$CPos$PSep${CPre}Telefon$CPos",
 247                                      'Notiz'            => 'des',
 248                                      'Privat'            => "access${PSep}1${ASep}private${PSep}public",
 249                                      'Startdatum'    =>    'startdate'.$mktime_lotus,
 250                                      'Enddatum'        =>    'enddate'.$mktime_lotus,
 251                                      'Erledigt'        =>    "status${PSep}1${ASep}done${PSep}call",
 252                                      'Nachname'        => "addr_id${PSep}@addr_id(${CPre}Nachname$CPos,${CPre}Vorname$CPos,${CPre}Firma$CPos)",
 253                                      'Firma'            =>    "from${PSep}.+$ASep${CPre}Firma$CPos: ${CPre}Nachname$CPos, ${CPre}Vorname$CPos".
 254                                                                          "${PSep}${CPre}Nachname$CPos, ${CPre}Vorname$CPos",
 255                                      'no CSV 1'        =>    "type${PSep}phone",
 256                                      'no CSV 2'        =>    "subject${PSep}@substr(${CPre}Notiz$CPos,0,60).' ...'" );
 257          */
 258          $info_name_options = "<option value=\"\">none\n";
 259          foreach($info_names as $field => $name) 
 260          {
 261              $info_name_options .= "<option value=\"$field\">".$GLOBALS['egw']->strip_html($name)."\n";
 262          }
 263          $csv_fields = fgetcsv($fp,8000,$_POST['fieldsep']);
 264          $csv_fields = $GLOBALS['egw']->translation->convert($csv_fields,$_POST['charset']);
 265          $csv_fields[] = 'no CSV 1';                         // eg. for static assignments
 266          $csv_fields[] = 'no CSV 2';
 267          $csv_fields[] = 'no CSV 3';
 268          foreach($csv_fields as $csv_idx => $csv_field) 
 269          {
 270              $GLOBALS['egw']->template->set_var('csv_field',$csv_field);
 271              $GLOBALS['egw']->template->set_var('csv_idx',$csv_idx);
 272              
 273              if (($def = $defaults[$csv_field]))
 274              {
 275                  list( $info,$trans ) = explode($PSep,$def,2);
 276                  $GLOBALS['egw']->template->set_var('trans',$trans);
 277                  $GLOBALS['egw']->template->set_var('info_fields',str_replace('="'.$info.'">','="'.$info.'" selected>',$info_name_options));
 278              } 
 279              else 
 280              {
 281                  $GLOBALS['egw']->template->set_var('trans','');
 282                  $GLOBALS['egw']->template->set_var('info_fields',$info_name_options);
 283              }
 284              $GLOBALS['egw']->template->parse('rows','fields',True);
 285          }
 286          $GLOBALS['egw']->template->set_var('lang_start',lang('Startrecord'));
 287          $GLOBALS['egw']->template->set_var('start',get_var('start',array('POST'),1));
 288          $msg = ($safe_mode = ini_get('safe_mode') == 'On') ? lang('to many might exceed your execution-time-limit'):
 289              lang('empty for all');
 290          $GLOBALS['egw']->template->set_var('lang_max',lang('Number of records to read (%1)',$msg));
 291          $GLOBALS['egw']->template->set_var('max',get_var('max',array('POST'),$safe_mode ? 200 : ''));
 292          $GLOBALS['egw']->template->set_var('debug',get_var('debug',array('POST'),True)?' checked':'');
 293          $GLOBALS['egw']->template->parse('rows','ffooter',True);
 294          fclose($fp);
 295  
 296          $hiddenvars = $GLOBALS['egw']->html->input_hidden(array(
 297              'action'  => 'import',
 298              'fieldsep'=> $_POST['fieldsep'],
 299              'charset' => $_POST['charset']
 300          ));
 301          $help_on_trans =     "<a name=\"help\"></a><b>How to use Translation's</b><p>".
 302              "Translations enable you to change / adapt the content of each CSV field for your needs. <br>".
 303              "General syntax is: <b>pattern1 $ASep} replacement1 $PSep} ... $PSep} patternN $ASep} replacementN</b><br>".
 304              "If the pattern-part of a pair is ommited it will match everything ('^.*$'), which is only ".
 305              "usefull for the last pair, as they are worked from left to right.<p>".
 306              "First example: <b>1$ASep}private$PSep}public</b><br>".
 307              "This will translate a '1' in the CVS field to 'privat' and everything else to 'public'.<p>".
 308              "Patterns as well as the replacement can be regular expressions (the replacement is done via ereg_replace). ".
 309              "If, after all replacements, the value starts with an '@' the whole value is eval()'ed, so you ".
 310              "may use all php, phpgw plus your own functions. This is quiet powerfull, but <u>circumvents all ACL</u>.<p>".
 311              "Example using regular expressions and '@'-eval(): <br><b>$mktime_lotus</b><br>".
 312              "It will read a date of the form '2001-05-20 08:00:00.00000000000000000' (and many more, see the regular expr.). ".
 313              "The&nbsp;[&nbsp;.:-]-separated fields are read and assigned in different order to @mktime(). Please note to use ".
 314              "$VPre} insted of a backslash (I couldn't get backslash through all the involved templates and forms.) ".
 315              "plus the field-number of the pattern.<p>".
 316              "In addintion to the fields assign by the pattern of the reg.exp. you can use all other CSV-fields, with the ".
 317              "syntax <b>$CPre}CVS-FIELDNAME$CPos</b>. Here is an example: <br>".
 318              "<b>.+$ASep$CPre}Company$CPos: $CPre}NFamily$CPos, $CPre}NGiven$CPos$PSep$CPre}NFamily$CPos, $CPre}NGiven$CPos</b><br>".
 319              "It is used on the CVS-field 'Company' and constructs a something like <i>Company: FamilyName, GivenName</i> or ".
 320              "<i>FamilyName, GivenName</i> if 'Company' is empty.<p>".
 321              "You can use the 'No CVS #'-fields to assign cvs-values to more than on field, the following example uses the ".
 322              "cvs-field 'Note' (which gots already assingned to the description) and construct a short subject: ".
 323              "<b>@substr($CPre}Note$CPos,0,60).' ...'</b><p>".
 324              "Their is two important user-function for the InfoLog:<br>".
 325              "<b>@addr_id($CPre}NFamily$CPos,$CPre}NGiven$CPos,$CPre}Company$CPos)</b> ".
 326              "searches the addressbook for an address and returns the id if it founds an exact match of at least ".
 327              "<i>NFamily</i> AND (<i>NGiven</i> OR <i>Company</i>). This is necessary to link your imported InfoLog-entrys ".
 328              "with the addressbook.<br>".
 329              "<b>@cat_id(Cat-name)</b> returns a numerical cat_id. If a category isn't found, it ".
 330              "will be automaticaly added.<p>".
 331              "I hope that helped to understand the features, if not <a href='mailto:egroupware-users@lists.sf.net'>ask</a>.";
 332  
 333          $GLOBALS['egw']->template->set_var('help_on_trans',lang($help_on_trans));    // I don't think anyone will translate this
 334          break;
 335  
 336      case 'next':
 337          $_POST['info_fields'] = unserialize(stripslashes($_POST['info_fields']));
 338          $_POST['trans']       = unserialize(stripslashes($_POST['trans']));
 339          // fall-through
 340      case 'import':
 341          $hiddenvars = $GLOBALS['egw']->html->input_hidden(array(
 342              'action'  => 'continue',
 343              'fieldsep'=> $_POST['fieldsep'],
 344              'charset' => $_POST['charset'],
 345              'start'   => $_POST['start']+(!$_POST['debug'] ? $_POST['max'] : 0),
 346              'max'     => $_POST['max'],
 347              'debug'   => $_POST['debug'],
 348              'info_fields' => $_POST['info_fields'],
 349              'trans'   => $_POST['trans']
 350          ));
 351          @set_time_limit(0);
 352          $fp=fopen($csvfile,'r');
 353          $csv_fields = fgetcsv($fp,8000,$_POST['fieldsep']);
 354          $csv_fields = $GLOBALS['egw']->translation->convert($csv_fields,$_POST['charset']);
 355          $csv_fields[] = 'no CSV 1';                         // eg. for static assignments
 356          $csv_fields[] = 'no CSV 2';
 357          $csv_fields[] = 'no CSV 3';
 358  
 359          $info_fields = array_diff($_POST['info_fields'],array( '' ));    // throw away empty / not assigned entrys
 360  
 361          $defaults = array();
 362          foreach($info_fields as $csv_idx => $info)
 363          {    // convert $trans[$csv_idx] into array of pattern => value
 364              $defaults[$csv_fields[$csv_idx]] = $info;
 365              if ($_POST['trans'][$csv_idx])
 366              {
 367                  $defaults[$csv_fields[$csv_idx]] .= $PSep.addslashes($_POST['trans'][$csv_idx]);
 368              }
 369          }
 370  
 371          $GLOBALS['egw']->preferences->read_repository();
 372          $GLOBALS['egw']->preferences->add('infolog','cvs_import',$defaults);
 373          $GLOBALS['egw']->preferences->save_repository(True);
 374  
 375          $log = "<table border=1>\n\t<tr><td>#</td>\n";
 376  
 377          foreach($info_fields as $csv_idx => $info)
 378          {    // convert $trans[$csv_idx] into array of pattern => value
 379              // if (!$debug) echo "<p>$csv_idx: ".$csv_fields[$csv_idx].": $info".($trans[$csv_idx] ? ': '.$trans[$csv_idx] : '')."</p>";
 380              $pat_reps = explode($PSep,stripslashes($_POST['trans'][$csv_idx]));
 381              $replaces = ''; $values = '';
 382              if ($pat_reps[0] != '') 
 383              {
 384                  foreach($pat_reps as $k => $pat_rep) 
 385                  {
 386                      list($pattern,$replace) = explode($ASep,$pat_rep,2);
 387                      if ($replace == '') 
 388                      { 
 389                          $replace = $pattern; $pattern = '^.*$'; 
 390                      }
 391                      $values[$pattern] = $replace;    // replace two with only one, added by the form
 392                      $replaces .= ($replaces != '' ? $PSep : '') . $pattern . $ASep . $replace;
 393                  }
 394                  $trans[$csv_idx] = $values;
 395              } /*else
 396                  unset( $trans[$csv_idx] );*/
 397  
 398              $log .= "\t\t<td><b>$info</b></td>\n";
 399          }
 400          if (!in_array('access',$info_fields))    // autocreate public access if not set by user
 401          {
 402              $log .= "\t\t<td><b>access</b></td>\n";
 403          }
 404          $start = $_POST['start'] < 1 ? 1 : $_POST['start'];
 405  
 406          // ignore empty lines, is_null($fields[0]) is returned on empty lines !!!
 407          for($i = 1; $i < $start; ++$i)     // overread lines before our start-record
 408          {
 409              while(($fields = fgetcsv($fp,8000,$_POST['fieldsep'])) && is_null($fields[0])) ;
 410          }
 411          for($anz = 0; !$_POST['max'] || $anz < $_POST['max']; ++$anz)
 412          {
 413              while(($fields = fgetcsv($fp,8000,$_POST['fieldsep'])) && is_null($fields[0])) ;
 414              if (!$fields)
 415              {
 416                  break;    // EOF
 417              }
 418              $fields = $GLOBALS['egw']->translation->convert($fields,$_POST['charset']);
 419  
 420              $log .= "\t</tr><tr><td>".($start+$anz)."</td>\n";
 421  
 422              $values = array();
 423              foreach($info_fields as $csv_idx => $info)
 424              {
 425                  //echo "<p>$csv: $info".($trans[$csv] ? ': '.$trans[$csv] : '')."</p>";
 426                  $val = $fields[$csv_idx];
 427                  if (isset($trans[$csv_idx]))
 428                  {
 429                      $trans_csv = $trans[$csv_idx];
 430                      while (list($pattern,$replace) = each($trans_csv))
 431                      {
 432                          if (ereg((string) $pattern,$val))
 433                          {
 434                              // echo "<p>csv_idx='$csv_idx',info='$info',trans_csv=".print_r($trans_csv).",ereg_replace('$pattern','$replace','$val') = ";
 435                              $val = ereg_replace((string) $pattern,str_replace($VPre,'\\',$replace),(string) $val);
 436                              // echo "'$val'</p>";
 437  
 438                              $reg = $CPreReg.'([a-zA-Z_0-9]+)'.$CPosReg;
 439                              while (ereg($reg,$val,$vars))
 440                              {    // expand all CSV fields
 441                                  $val = str_replace($CPre.$vars[1].$CPos,$val[0] == '@' ? "'".addslashes($fields[array_search($vars[1],$csv_fields)])."'" : $fields[array_search($vars[1],$csv_fields)],$val);
 442                              }
 443                              if ($val[0] == '@')
 444                              {
 445                                  // removing the $ to close security hole of showing vars, which contain eg. passwords
 446                                  $val = 'return '.substr(str_replace('$','',$val),1).';';
 447                                  // echo "<p>eval('$val')=";
 448                                  $val = eval($val);
 449                                  // echo "'$val'</p>";
 450                              }
 451                              if ($pattern[0] != '@' || $val)
 452                                  break;
 453                          }
 454                      }
 455                  }
 456                  $values[$info] = $val;
 457  
 458                  $log .= "\t\t<td>$val</td>\n";
 459              }
 460              $empty = !count($values);
 461  
 462              // convert the category name to an id
 463              if ($values['cat'] && !is_numeric($values['cat']))
 464              {
 465                  $values['cat'] = cat_id($values['cat']);
 466              }
 467  
 468              // convert dates to timestamps
 469              foreach(array('startdate','enddate','datemodified','datecompleted') as $date)
 470              {
 471                  if (isset($values[$date]) && !is_numeric($date))
 472                  {
 473                      if (ereg('(.*)\.[0-9]+',$values[$date],$parts)) $values[$date] = $parts[1];
 474                      $values[$date] = strtotime($values[$date]);
 475                  }
 476              }
 477              if (!isset($values['datemodified'])) $values['datemodified'] = $values['startdate'];
 478  
 479              // convert user-names to user-id's
 480              if (isset($values['owner']) && !is_numeric($values['owner']))
 481              {
 482                  $values['owner'] = $GLOBALS['egw']->accounts->name2id($values['owner']);
 483              }
 484              if (isset($values['responsible']))
 485              {
 486                  $responsible = $values['responsible'];
 487                  $values['responsible'] = array();
 488                  foreach(split('[,;]',$responsible) as $user)
 489                  {
 490                      if ($user && !is_numeric($user)) $user = $GLOBALS['egw']->accounts->name2id($user);
 491                      if ($user) $values['responsible'][] = $user;
 492                  }
 493              }
 494              if (!in_array('access',$info_fields))
 495              {
 496                  $values['access'] = 'public';    // public access if not set by user
 497                  $log .= "\t\t<td>".$values['access']."</td>\n";
 498              }
 499              if(!$_POST['debug'] && !$empty)    // dont import empty contacts
 500              {
 501                  // create new names with info_ prefix
 502                  $to_write = array();
 503                  foreach($values as $name => $value)
 504                  {
 505                      $to_write[substr($name,0,5) != 'info_' && $name{0} != '#' ? 'info_'.$name : $name] = $value;
 506                  }
 507                  if ($values['addr_id'] && !is_numeric($values['addr_id']))
 508                  {
 509                      list($lastname,$firstname,$org_name) = explode(',',$values['addr_id']);
 510                      $values['addr_id'] = addr_id($lastname,$firstname,$org_name);
 511                  }
 512                  if ($values['project_id'] && !is_numeric($values['project_id']))
 513                  {
 514                      $values['project_id'] = project_id($values['project_id']);
 515                  }
 516                  if (($id = $boinfolog->write($to_write,True,False)))
 517                  {
 518                      $info_link_id = false;
 519                      foreach(array(
 520                          'projectmanager:'.$values['project_id'],
 521                          'addressbook:'.$values['addr_id'],
 522                          $values['link_1'],$values['link_2'],$values['link_3'],
 523                      ) as $value)
 524                      {
 525                          list($app,$app_id) = explode(':',$value);
 526                          if ($app && $app_id)
 527                          {
 528                              //echo "<p>linking infolog:$id with $app:$app_id</p>\n";
 529                              $link_id = $boinfolog->link->link('infolog',$id,$app,$app_id);
 530                              if ($link_id && !$info_link_id)
 531                              {
 532                                  $to_write = array(
 533                                      'info_id'      => $id,
 534                                      'info_link_id' => $link_id,
 535                                  );
 536                                  $boinfolog->write($to_write);
 537                                  $info_link_id = true;
 538                              }
 539                          }
 540                      }
 541                  }
 542              }
 543          }
 544          $log .= "\t</tr>\n</table>\n";
 545  
 546          $GLOBALS['egw']->template->set_var('anz_imported',($_POST['debug'] ?
 547              lang('%1 records read (not yet imported, you may go %2back%3 and uncheck Test Import)',
 548              $anz,'','') :
 549              lang('%1 records imported',$anz)). '&nbsp;'.
 550              (!$_POST['debug'] && $fields ? $GLOBALS['egw']->html->submit_button('next','Import next set') . '&nbsp;':'').
 551              $GLOBALS['egw']->html->submit_button('continue','Back') . '&nbsp;'.
 552              $GLOBALS['egw']->html->submit_button('cancel','Cancel'));
 553          $GLOBALS['egw']->template->set_var('log',$log);
 554          $GLOBALS['egw']->template->parse('rows','imported');
 555          break;
 556      }
 557      $GLOBALS['egw']->template->set_var('hiddenvars',str_replace('{','&#x7B;',$hiddenvars));
 558      $GLOBALS['egw']->template->pfp('phpgw_body','import');
 559      $GLOBALS['egw']->common->egw_footer();


Généré le : Sun Feb 25 17:20:01 2007 par Balluche grâce à PHPXref 0.7