public function action_import() { if (!($acc_token = Session::instance()->get('g_oauth_access_token'))) { Message::instance()->set('You haven\'t given us permission to fetch spreadsheets.'); $this->request->redirect('/tools/import/google/'); } if (Request::$method !== 'POST') { Message::instance()->set('Please choose a spreadsheet to import.'); $this->request->redirect('/tools/import/google/list'); } // TODO: validation if (!isset($_POST['k'], $_POST['stops-wsid'])) { Message::instance()->set('Spreadsheet key and worksheet id required.'); $this->request->redirect('/tools/import/google/list'); } $csv = Sourcemap_Csv::arr2csv(Google_Spreadsheets::get_worksheet_cells($acc_token, $_POST['k'], $_POST['stops-wsid'])); if ($csv && isset($_POST['hops-wsid']) && $_POST['hops-wsid']) { $hops_csv = Sourcemap_Csv::arr2csv(Google_Spreadsheets::get_worksheet_cells($acc_token, $_POST['k'], $_POST['hops-wsid'])); } else { $hops_csv = null; } $new_sc = Sourcemap_Import_Csv::csv2sc($csv, $hops_csv, array('headers' => true)); if (isset($_POST['replace-into']) && $_POST['replace-into']) { $exists = ORM::factory('supplychain')->where('id', '=', $_POST['replace-into'])->find(); if ($exists && $exists->user_id == Auth::instance()->get_user()->id) { $replace_into = $exists->id; } else { Message::instance()->set('The supplychain you tried to replace is invalid.'); $this->request->redirect('/tools/import/google/worksheets/?k=' . $_POST['k']); } } else { $replace_into = null; } try { $new_sc->user_id = Auth::instance()->get_user()->id; $title = false; $title = isset($_POST['supplychain_name']) && $_POST['supplychain_name'] ? $_POST['supplychain_name'] : false; if ($replace_into && !$title && ($keeptitle = $exists->attributes->where('key', 'in', array('title', 'name'))->find())) { $title = $keeptitle->value; } $new_sc->attributes = (object) array('title' => $title ? $title : 'Imported Sourcemap'); $scid = ORM::factory('supplychain')->save_raw_supplychain($new_sc, $replace_into); $new_sc = ORM::factory('supplychain', $scid); $new_sc->other_perms |= Sourcemap::READ; $new_sc->save(); Message::instance()->set('Your spreadsheet was imported.', Message::SUCCESS); $this->request->redirect('view/' . $scid); } catch (Exception $e) { Message::instance()->set('There was a problem importing your spreadsheet: ' . $e); $this->request->redirect('/tools/import/google/worksheets/?k=' . $_POST['k']); } }