Example #1
1
 /**
  * Parse a csv file
  * 
  * @return array
  */
 public function parseCSV()
 {
     $finder = new Finder();
     $rows = array();
     $convert_utf8 = function ($s) {
         if (!mb_check_encoding($s, 'UTF-8')) {
             $s = utf8_encode($s);
         }
         return $s;
     };
     $finder->files()->in($this->path)->name($this->fileName);
     foreach ($finder as $file) {
         $csv = $file;
     }
     if (($handle = fopen($csv->getRealPath(), "r")) !== false) {
         $i = 0;
         while (($data = fgetcsv($handle, null, ";")) !== false) {
             $i++;
             if ($this->ignoreFirstLine && $i == 1) {
                 continue;
             }
             $rows[] = array_map($convert_utf8, $data);
         }
         fclose($handle);
     }
     return $rows;
 }
Example #2
1
/**
 * Returns a stock by symbol (case-insensitively) else false if not found.
 */
function lookup($symbol)
{
    // reject symbols that start with ^
    if (preg_match("/^\\^/", $symbol)) {
        return false;
    }
    // reject symbols that contain commas
    if (preg_match("/,/", $symbol)) {
        return false;
    }
    // open connection to Yahoo
    $handle = @fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={$symbol}", "r");
    if ($handle === false) {
        // trigger (big, orange) error
        trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
        exit;
    }
    // download first line of CSV file
    $data = fgetcsv($handle);
    if ($data === false || count($data) == 1) {
        return false;
    }
    // close connection to Yahoo
    fclose($handle);
    // ensure symbol was found
    if ($data[2] === "0.00") {
        return false;
    }
    // return stock as an associative array
    return ["symbol" => $data[0], "name" => $data[1], "price" => $data[2]];
}
Example #3
0
 function get($max_lines = 0)
 {
     //if $max_lines is set to 0, then get all the data
     $data = array();
     if ($max_lines > 0) {
         $line_count = 0;
     } else {
         $line_count = -1;
     }
     // so loop limit is ignored
     while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE) {
         if ($this->parse_header) {
             foreach ($this->header as $i => $heading_i) {
                 $row_new[$heading_i] = $row[$i];
             }
             $data[] = $row_new;
         } else {
             $data[] = $row;
         }
         if ($max_lines > 0) {
             $line_count++;
         }
     }
     return $data;
 }
 public function rechazadas($q)
 {
     $url = 'https://docs.google.com/spreadsheets/d/1qxVqiUQNXyl26pY7f16OP5oWSCbp4wmykwgAJi762bc/pub?output=csv';
     $headers = false;
     $list = array();
     // open file for reading
     if (($handle = fopen($url, "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
             if ($headers) {
                 $totalrows = count($data) - 1;
                 $temp = array();
                 for ($row = 0; $row <= $totalrows; $row++) {
                     $temp[$headers[$row]] = $data[$row];
                 }
                 $list[] = $temp;
             } else {
                 $headers = $data;
             }
         }
         fclose($handle);
     }
     $collection = collect($list)->reject(function ($r) use($q) {
         return !(strpos(strtolower($r['materia_resumen']), strtolower($q)) > -1);
     });
     $resp = array('q' => $q, 'list' => $collection);
     return response()->json($resp);
 }
 public function initialize($params)
 {
     $this->_mapping = array();
     $dlist = glob(dirname(__FILE__) . "/mappings/default/*.csv");
     if ($dlist == false) {
         $dlist = array();
         $this->log("No default mapping found", "warning");
     }
     $slist = glob(dirname(__FILE__) . "/mappings/*.csv");
     if ($slist == false) {
         $slist = array();
         $this->log("No custom mapping found", "startup");
     }
     $flist = array_merge($dlist, $slist);
     foreach ($flist as $fname) {
         $idx = basename($fname);
         if (!isset($this->_mapping[$idx])) {
             $this->_mapping[$idx] = array("DIRECT" => array(), "RE" => array());
         }
         $mf = fopen("{$fname}", "r");
         while (($data = fgetcsv($mf, 1000, ",")) !== false) {
             if (substr($data[0], 0, 4) == "_RE:") {
                 $target = "RE";
                 $key = substr($data[0], 4);
             } else {
                 $target = "DIRECT";
                 $key = $data[0];
             }
             $this->_mapping[$idx][$target][$key] = $data[1];
         }
     }
 }
Example #6
0
 /**
  * load the locale
  *
  * @access public
  * @param  string $code
  */
 public static function load($code)
 {
     if (self::$_directory === null) {
         self::$_directory = dirname(dirname(__FILE__)) . '/locale/';
     }
     // must be in lower case
     $code = strtolower($code);
     // must be [a-z-0-9]
     if (!preg_match('/^([a-z0-9]+)$/isU', $code)) {
         throw new HTML2PDF_exception(0, 'invalid language code [' . self::$_code . ']');
     }
     // save the code
     self::$_code = $code;
     // get the name of the locale file
     $file = self::$_directory . self::$_code . '.csv';
     // the file must exist
     if (!is_file($file)) {
         throw new HTML2PDF_exception(0, 'language code [' . self::$_code . '] unknown. You can create the translation file [' . $file . '] and send it to the webmaster of html2pdf in order to integrate it into a future release');
     }
     // load the file
     self::$_list = array();
     $handle = fopen($file, 'r');
     while (!feof($handle)) {
         $line = fgetcsv($handle);
         if (count($line) != 2) {
             continue;
         }
         self::$_list[trim($line[0])] = trim($line[1]);
     }
     fclose($handle);
 }
Example #7
0
 function _getSubscriberCSV()
 {
     $keys = array();
     $subscribers = array();
     $subscriber = array();
     jimport('joomla.filesystem.file');
     $allowedExts = array('csv');
     $csvFile = $_FILES['csv_subscribers'];
     $csvFileName = $csvFile['tmp_name'];
     $fileName = $csvFile['name'];
     $fileExt = strtolower(JFile::getExt($fileName));
     if (in_array($fileExt, $allowedExts)) {
         $line = 0;
         $fp = fopen($csvFileName, 'r');
         while (($cells = fgetcsv($fp)) !== FALSE) {
             if ($line == 0) {
                 foreach ($cells as $key) {
                     $keys[] = $key;
                 }
                 $line++;
             } else {
                 $i = 0;
                 foreach ($cells as $cell) {
                     $subscriber[$keys[$i]] = $cell;
                     $i++;
                 }
                 $subscribers[] = $subscriber;
             }
         }
         fclose($fp);
         return $subscribers;
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = $input->getArgument('file');
     if (!file_exists($file) || !($fh = fopen($file, 'r'))) {
         $output->writeln('<error>Can\'t read data from file</error>');
         return null;
     }
     //собираем из файла популярные города
     $popular = [];
     while (($data = fgetcsv($fh)) !== false) {
         //без идентификатора не обрабатываем
         if (empty($data[0])) {
             continue;
         }
         //пробуем найти указанный город
         $popular[] = $data[0];
     }
     fclose($fh);
     $popular = array_unique($popular);
     $id = 0;
     //перебираем все города
     while ($list = \bxpimple\Locator::$item->get('cityFinder')->mergeFilterWith(['>ID' => $id])->setOrder(['id' => 'asc'])->setLimit(50)->all()) {
         foreach ($list as $city) {
             $pop = in_array($city->name->value, $popular);
             $city->property_city_is_popular->value = $pop ? '1' : '';
             $city->save();
             $output->writeln('<info>Proceed city ' . $city->name->value . '. City is ' . ($pop ? 'popular' : 'not popular') . '</info>');
             $id = $city->id->value;
         }
     }
 }
Example #9
0
function readTempSDB()
{
    $delimiter = ',';
    $header = NULL;
    $d = array();
    if (($handle = fopen("plugins/TEMP/db.sdb", 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
            if (!$header) {
                $header = $row;
            } else {
                $d[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    foreach ($d as $data) {
        foreach ($data as $row) {
            $r = explode(";", $row);
            $data1 = $r[0];
            $data2 = $r[1];
            $return[$data1] = $data2;
        }
    }
    return $return;
}
 public function import(Request $request)
 {
     $file = $request->file('arquivo');
     $extension = $file->getClientOriginalExtension();
     $import = new Import();
     $import->user_id = 1;
     $import->save();
     Storage::disk('local')->put($import->id . '.' . $extension, File::get($file));
     $handle = fopen($file, "r");
     $firstTime = true;
     while (($line = fgetcsv($handle, 1000, "\t")) !== false) {
         if ($firstTime) {
             $firstTime = false;
         } else {
             $produto = new Product();
             $produto->import_id = $import->id;
             $produto->purchaser_name = $line[0];
             $produto->item_description = $line[1];
             $produto->item_price = floatval($line[2]);
             $produto->purchase_count = intval($line[3]);
             $produto->merchant_address = $line[4];
             $produto->merchant_name = $line[5];
             $produto->save();
         }
     }
     return view('index', ['imports' => Import::all()]);
 }
Example #11
0
 /**
  * Load translation data
  *
  * @param  string|array  $filename  Filename and full path to the translation source
  * @param  string        $locale    Locale/Language to add data for, identical with locale identifier,
  *                                  see Zend_Locale for more information
  * @param  array         $option    OPTIONAL Options to use
  * @return array
  */
 protected function _loadTranslationData($filename, $locale, array $options = array())
 {
     $this->_data = array();
     $options = $options + $this->_options;
     $this->_file = @fopen($filename, 'rb');
     if (!$this->_file) {
         // require_once 'Zend/Translate/Exception.php';
         throw new Zend_Translate_Exception('Error opening translation file \'' . $filename . '\'.');
     }
     while (($data = fgetcsv($this->_file, $options['length'], $options['delimiter'], $options['enclosure'])) !== false) {
         if (substr($data[0], 0, 1) === '#') {
             continue;
         }
         if (!isset($data[1])) {
             continue;
         }
         if (count($data) == 2) {
             $this->_data[$locale][$data[0]] = $data[1];
         } else {
             $singular = array_shift($data);
             $this->_data[$locale][$singular] = $data;
         }
     }
     return $this->_data;
 }
Example #12
0
 function get_csv_header_fields()
 {
     $this->arr_csv_columns = array();
     $fpointer = fopen($this->file_name, "r");
     if ($fpointer) {
         $arr = fgetcsv($fpointer, 10 * 1024, $this->field_separate_char);
         if (is_array($arr) && !empty($arr)) {
             if ($this->use_csv_header) {
                 foreach ($arr as $val) {
                     if (trim($val) != "") {
                         $this->arr_csv_columns[] = $val;
                     }
                 }
             } else {
                 $i = 1;
                 foreach ($arr as $val) {
                     if (trim($val) != "") {
                         $this->arr_csv_columns[] = "column" . $i++;
                     }
                 }
             }
         }
         unset($arr);
         fclose($fpointer);
     } else {
         $this->error = "file cannot be opened: " . ("" == $this->file_name ? "[empty]" : @mysql_escape_string($this->file_name));
     }
     return $this->arr_csv_columns;
 }
 public function test5Transactions()
 {
     $inputFile = fopen('php://memory', 'w+');
     $outputFile = fopen('php://memory', 'w+');
     $csv = array(array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555554530114002', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'));
     fputcsv($inputFile, array_keys(current($csv)), ';');
     foreach ($csv as $line) {
         fputcsv($inputFile, $line, ';');
     }
     rewind($inputFile);
     $batchApi = Be2bill_Api_ClientBuilder::buildSandboxBatchClient($this->getIdentifier(), $this->getPassword());
     $batchApi->setInputFile($inputFile);
     $batchApi->attach(new Be2bill_Api_Batch_Observer_Debug());
     $batchApi->attach(new Be2bill_Api_Batch_Observer_FileReport($outputFile));
     $batchApi->run();
     rewind($outputFile);
     $i = 0;
     while (!feof($outputFile)) {
         $line = fgetcsv($outputFile, null, ';');
         // HACK for phpunit version >= 5.2
         if ($line) {
             $i++;
         }
     }
     $this->expectOutputRegex('/Line 1.+\\nLine 2.+\\nLine 3.+\\nLine 4.+\\n/');
     $this->assertEquals(5, $i);
 }
 /**
  * @param (String) $filePath
  * @return (Array) $result
  **/
 private function parseAccountReport($filePath)
 {
     $i = 0;
     if (($handle = fopen($filePath, "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
             if ($i >= 2) {
                 //On saute les 2 première lignes qui sont "nom du rapport" et nom des champs
                 //Si le compte à aucune datas, on corrige le bug du rapport
                 for ($i = 0; $i < count($data); $i++) {
                     if ($data[$i] == "Total") {
                         $data[$i] = 0;
                     }
                 }
                 $result[] = $data;
             }
             $i++;
         }
         fclose($handle);
     }
     if (count($result) > 1) {
         array_pop($result);
     }
     // On supprime la ligne Total
     return $result;
 }
 public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state)
 {
     // Check to make sure that the file was uploaded to the server properly
     $userInputValues = $form_state->getUserInput();
     $uri = db_select('file_managed', 'f')->condition('f.fid', $userInputValues['import']['fids'], '=')->fields('f', array('uri'))->execute()->fetchField();
     if (!empty($uri)) {
         if (file_exists(\Drupal::service("file_system")->realpath($uri))) {
             // Open the csv
             $handle = fopen(\Drupal::service("file_system")->realpath($uri), "r");
             // Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters.
             // If you want commas are any other character, replace the pipe with it.
             while (($data = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
                 $operations[] = ['csvimport_import_batch_processing', [$data]];
             }
             // Once everything is gathered and ready to be processed... well... process it!
             $batch = ['title' => t('Importing CSV...'), 'operations' => $operations, 'finished' => $this->csvimport_import_finished(), 'error_message' => t('The installation has encountered an error.'), 'progress_message' => t('Imported @current of @total products.')];
             batch_set($batch);
             fclose($handle);
         } else {
             drupal_set_message(t('Not able to find file path.'), 'error');
         }
     } else {
         drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error');
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     /** @var Keytype $keytype */
     $keytype = Keytype::create(['name' => 'countries', 'description' => 'ISO 3166 Country Codes', 'created_by' => 'loader', 'updated_by' => 'loader']);
     $handle = fopen($this->filename, 'r');
     // Get this in advance by calling wc -l $file
     $count = 246;
     $bar = $this->output->createProgressBar($count);
     while ($data = fgetcsv($handle)) {
         try {
             list($country_code, $country_name) = $data;
         } catch (\Exception $e) {
             continue;
         }
         // progress advance
         $bar->advance();
         // Skip the first line
         if ($country_code == "country_code") {
             continue;
         }
         // Create the entry
         Keyvalue::create(['keytype_id' => $keytype->id, 'keyvalue' => $country_code, 'keyname' => $country_name, 'created_by' => 'loader', 'updated_by' => 'loader']);
     }
     fclose($handle);
     $bar->finish();
     $this->output->writeln('Finished');
 }
Example #17
0
 function fgethandle(&$handle, &$contents)
 {
     $line = 0;
     $contents = array();
     $is_utf8 = true;
     while ($row = fgetcsv($handle)) {
         foreach ($row as $num => $col) {
             if ($line == 0 && $num == 0) {
                 // 判断下文档的字符集.
                 if (!$this->charset->is_utf8($col)) {
                     $is_utf8 = false;
                 } else {
                     if ($col_tmp = $this->charset->replace_utf8bom($col)) {
                         // 替换两个双引号
                         $col = substr($col_tmp, 1, -1);
                     }
                 }
             }
             if (!$is_utf8) {
                 $contents[$line][$num] = $this->charset->local2utf((string) $col);
             } else {
                 $contents[$line][$num] = (string) $col;
             }
         }
         $line++;
     }
 }
Example #18
0
 function _getData()
 {
     $urlCSV = "http://www.schachbund.de/dwz/db/spieler-csv.php?zps=" . $this->zps . "-" . $this->mglnr;
     $this->url = "http://www.schachbund.de/dwz/db/spieler.html?zps=" . $this->zps . "-" . $this->mglnr;
     if (!($handle = fopen($urlCSV, "r"))) {
         JError::raiseNotice(100, JText::_('NO_CONNECTION'));
     } else {
         // INIT
         $counter = 0;
         $this->rows = array();
         while ($row = fgetcsv($handle, 500, "|")) {
             $counter++;
             // Zeile 1: Datum
             if ($counter == 1) {
                 $this->date = $row[0];
                 // Teile 2: Vereinsnummer, Mitgliedsnummer, Status, Name, Geschlecht, Geburtsjahr, FIDE-Titel, Woche der letzten Auswertung, DWZ, DWZ-Index
             } elseif ($counter == 2) {
                 $this->playerData = $row;
                 // Zeile 3: FIDE-Elo, Partien, Titel, ID, Land
             } elseif ($counter == 3) {
                 $this->fideData = $row;
                 // Zeile 4++: Eintragsnummer, Turniercode, Turniername, Punkte, Partien, Erwartungswert, Gegner, Leistung, DWZ, DWZ-Index
             } elseif ($row[0] != "") {
                 // leere Zeilen ausscheiden
                 $this->rows[] = $row;
             }
         }
     }
 }
Example #19
0
 public function byimsitestAction()
 {
     $working_dir = "/home/shani/Documents/S.D.O.C/BillRun/Files/Docs/Tests/";
     $row = 1;
     if (($handle = fopen($working_dir . "billing_crm_diff_with_sid_and_imsi-1.csv", "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 0, "\t")) !== FALSE) {
             error_log($row);
             if ($row++ == 1) {
                 continue;
             }
             $this->subscriber = Billrun_Factory::subscriber();
             $params['time'] = "2013-10-24 23:59:59";
             $params['IMSI'] = $data[5];
             $params_arr[] = array('time' => $params['time'], 'DATETIME' => $params['time'], 'IMSI' => $params['IMSI']);
             $details = $this->subscriber->load($params);
             $data['normal_plan'] = $details->plan;
             $newCsvData[$data[4]] = $data;
         }
         fclose($handle);
         $list = Subscriber_Golan::requestList($params_arr);
         foreach ($list as $arr) {
             $newCsvData[$arr['subscriber_id']]['bulk_plan'] = $arr['plan'];
         }
         $handle = fopen('/tmp/result.csv', 'w');
         foreach ($newCsvData as $line) {
             fputcsv($handle, $line);
         }
         fclose($handle);
     }
 }
Example #20
0
File: fdp.php Project: bilel99/oge
 function _chargePays()
 {
     // On place le redirect sur la home
     $_SESSION['request_url'] = $this->url;
     // On masque les Head, header et footer originaux plus le debug
     $this->autoFireHeader = false;
     $this->autoFireHead = false;
     $this->autoFireFooter = false;
     $this->autoFireDebug = false;
     $this->autoFireView = false;
     // Chargement des datas
     $this->pays = $this->loadData('pays');
     // On purge les pays en cours
     $this->pays->purgePays();
     // Initialisation de la 1ère ligne du csv
     $row = 1;
     // Ouverture du fichier en lecture seule
     $fp = fopen($this->path . 'protected/pays.csv', 'r');
     $i = 1;
     // Traitement du csv
     while ($data = fgetcsv($fp, 1000, ";")) {
         // Enregistrement des donnees
         $this->pays->id_langue = trim(strtolower($data[2]));
         $this->pays->fr = trim(utf8_encode(ucfirst(strtolower($data[0]))));
         $this->pays->en = trim(utf8_encode(ucfirst(strtolower($data[1]))));
         $this->pays->zone = 0;
         $this->pays->create();
         // Affichage des messages
         echo $this->pays->id_langue . '&nbsp;|&nbsp;' . $this->pays->fr . '&nbsp;|&nbsp;' . $this->pays->en . '&nbsp;|&nbsp;' . $this->pays->zone . '<br />';
         $row++;
         $i++;
     }
 }
Example #21
0
 /**
  * Dissect country code from phone number.
  *
  * @param  Phone                    $phone
  * @return $this
  * @throws InvalidArgumentException
  * @throws RuntimeException
  */
 public function injectPhoneProperties(Phone $phone)
 {
     if (!file_exists($this->getCountriesPath()) || !is_readable($this->getCountriesPath())) {
         throw new RuntimeException("File doesn't exists or isn't readable.");
     }
     if (($handle = fopen($this->getCountriesPath(), 'rb')) !== false) {
         while (($data = fgetcsv($handle, 1000)) !== false) {
             if (strpos($phone->getPhoneNumber(), $data[1]) === 0) {
                 // Return the first appearance.
                 fclose($handle);
                 $mcc = explode("|", $data[2]);
                 $mcc = $mcc[0];
                 //hook:
                 //fix country code for North America
                 if (substr($data[1], 0, 1) == "1") {
                     $data[1] = "1";
                 }
                 $phone->setCountry($data[0])->setCc($data[1])->setPhone(substr($phone->getPhoneNumber(), strlen($data[1]), strlen($phone->getPhoneNumber())))->setMcc($mcc)->setIso3166(isset($data[3]) ? $data[3] : null)->setIso639(isset($data[4]) ? $data[4] : null)->setMnc(isset($data[5]) ? $data[5] : null);
                 return $this;
             }
         }
         fclose($handle);
     }
     throw new InvalidArgumentException("Phone number not recognized");
 }
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     $locale = $this->argument('locale');
     $group = $this->argument('group');
     $path = $this->option('path');
     $delimiter = $this->option('delimiter');
     $enclosure = $this->option('enclosure');
     $escape = $this->option('escape');
     $strings = [];
     // Create storage dir
     if (file_exists($path) == false) {
         mkdir($path, 0755, true);
     }
     // Create output device and write CSV.
     if (($input_fp = fopen("{$path}/{$group}.csv", 'r')) === false) {
         $this->error('Can\'t open the input file!');
         exit;
     }
     // Write CSV lintes
     while (($data = fgetcsv($input_fp, 0, $delimiter, $enclosure, $escape)) !== false) {
         $strings[$data[0]] = $data[1];
     }
     fclose($input_fp);
     $this->writeLangList($locale, $group, $strings);
     $this->line('');
     $this->info("Successfully imported file:");
     $this->info("{$path}/{$group}.csv");
     $this->line('');
 }
Example #23
0
 public static function getExtension($host, $addr)
 {
     $BBC_IP2EXT_PATH = dirname(__FILE__) . '/../ip2ext/';
     // generic extensions which need to be looked up first
     $gen_ext = array("ac", "aero", "ag", "arpa", "as", "biz", "cc", "cd", "com", "coop", "cx", "edu", "eu", "gb", "gov", "gs", "info", "int", "la", "mil", "ms", "museum", "name", "net", "nu", "org", "pro", "sc", "st", "su", "tc", "tf", "tk", "tm", "to", "tv", "vu", "ws");
     // hosts with reliable country extension don't need to be looked up
     $cnt_ext = array("ad", "ae", "af", "ai", "al", "am", "an", "ao", "aq", "ar", "at", "au", "aw", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cs", "cu", "cv", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es", "et", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "ru", "rs", "rw", "sa", "sb", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "sv", "sy", "sz", "td", "tg", "th", "tj", "tl", "tn", "tp", "tr", "tt", "tw", "tz", "ua", "ug", "uk", "um", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "wf", "ye", "yt", "yu", "za", "zm", "zr", "zw");
     $file = $BBC_IP2EXT_PATH . (substr($addr, 0, strpos($addr, ".")) . ".inc");
     $ext = strtolower(substr($host, strrpos($host, ".") + 1));
     // Don't look up if there's already a country extension
     if (in_array($ext, $cnt_ext)) {
         return $ext;
     }
     if (!is_readable($file)) {
         return self::legacy_ext($ext, $gen_ext);
     }
     $long = ip2long($addr);
     $long = sprintf("%u", $long);
     $fp = fopen($file, "rb");
     while (($range = fgetcsv($fp, 32, "|")) !== false) {
         if ($long >= $range[1] && $long <= $range[1] + $range[2] - 1) {
             // don't hose our stats if the database returns an unexpected extension
             $db_ext = in_array($range[0], $cnt_ext) || in_array($range[0], $gen_ext) ? $range[0] : self::legacy_ext($ext, $gen_ext);
             break;
         }
     }
     fclose($fp);
     return !empty($db_ext) ? $db_ext : self::legacy_ext($ext, $gen_ext);
 }
 public function donateAction()
 {
     $this->setAccess('frontend/dashboard/access');
     // collect some data
     $data = [];
     exec('git-summary', $gitSummary);
     exec('git log -1 --format=%cd', $gitLastCommit);
     $key = 'git-time-extractor-file';
     $timeStatsFilePath = ROOT_PATH . '/../data/git/stats.csv';
     $this->getCache()->getItem($key, $success);
     if (!$success || !file_exists($timeStatsFilePath)) {
         exec('git_time_extractor > ' . $timeStatsFilePath);
         $this->getCache()->setItem($key, 'true');
     }
     if (isset($gitSummary[2]) && isset($gitSummary[4]) && isset($gitSummary[5])) {
         // summary
         $data['project_age'] = trim(str_replace('repo age : ', '', $gitSummary[2]));
         $data['total_commits*'] = trim(str_replace('commits  : ', '', $gitSummary[4]));
         $data['total_project_files'] = trim(str_replace('files    : ', '', $gitSummary[5]));
     } else {
         $data['project_age'] = '';
         $data['total_commits*'] = '';
         $data['total_project_files'] = '';
     }
     // changelog
     $data['last_commit'] = isset($gitLastCommit[0]) ? $gitLastCommit[0] : '';
     $stats = fopen($timeStatsFilePath, 'r');
     $x = 0;
     $changelog = [];
     $totalTime = 0;
     while (!feof($stats)) {
         $line = fgetcsv($stats, 1024, ',', '"');
         if ($x++ == 0 || count($line) <= 1) {
             continue;
         }
         $changes = explode('---', $line[8]);
         unset($changes[0]);
         $changelog[] = ['date' => $line[0], 'changes' => $changes];
         $totalTime += $line[3];
     }
     $userRepo = $this->getEntityManager()->getRepository('Auth\\Entity\\Benutzer');
     $squadRepo = $this->getEntityManager()->getRepository('Frontend\\Squads\\Entity\\Squad');
     $memberRepo = $this->getEntityManager()->getRepository('Frontend\\Squads\\Entity\\Member');
     // total user
     $data['registered_users'] = $userRepo->createQueryBuilder('c')->select('count(c.id)')->getQuery()->getSingleScalarResult();
     // total squads
     $data['total_squads'] = $squadRepo->createQueryBuilder('c')->select('count(c.id)')->getQuery()->getSingleScalarResult();
     // total squads
     $data['total_squad_members'] = $memberRepo->createQueryBuilder('c')->select('count(c.squad)')->getQuery()->getSingleScalarResult();
     // total images
     $data['total_squad_logos'] = $squadRepo->createQueryBuilder('c')->select('count(c.logo)')->where('c.logo IS NOT NULL')->andWhere("c.logo != ''")->getQuery()->getSingleScalarResult();
     // total image file size
     $data['total_squad_logos_size'] = $this->directoryFileSize(ROOT_PATH . '/uploads/logos/');
     $viewModel = new ViewModel();
     $viewModel->setTemplate('/dashboard/donate.phtml');
     $viewModel->setVariable('data', $data);
     $viewModel->setVariable('changelog', array_reverse($changelog));
     $viewModel->setVariable('total_time', $totalTime);
     return $viewModel;
 }
Example #25
0
function CSVToArray($fp)
{
    $headers = array();
    $array = array();
    if (($data = fgetcsv($fp)) !== false) {
        $num = count($data);
        for ($i = 0; $i < $num; $i++) {
            $headers[$i] = $data[$i];
        }
    }
    if (sizeof($headers) == 0 || strpos($headers[0], 'html')) {
        fclose($fp);
        return $array;
    }
    $j = 0;
    while (($data = fgetcsv($fp)) !== false) {
        $num = count($data);
        for ($i = 0; $i < $num; $i++) {
            $array[$j][$headers[$i]] = $data[$i];
        }
        $j++;
    }
    fclose($fp);
    return $array;
}
Example #26
0
/**
 * Import KMS users.
 *
 * @todo update desc.
 * @param array $mapping
 *   Mapping configuration.
 * @param string $filename
 *   The absolute path to the csv file.
 * @param mixed $limit
 *   For debug use you can limit the number of users. FALSE = unlimited.
 *
 * @return mixed
 *   $users/FALSE - Either users or false.
 */
function import_users($mapping, $limit = FALSE)
{
    global $stdout, $settings;
    $users = array();
    $row_count = 0;
    if (($handle = fopen($settings['filename'], "r")) !== FALSE) {
        while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
            // Don't do anything at header row.
            if (!$row_count) {
                $row_count++;
                continue;
            }
            if ($limit === FALSE || $row_count <= $limit) {
                // Save user intially.
                $account = import_users_save_user($mapping, $row, $settings['roles']);
                import_users_save_pass_cleartext($account);
                $users[$account->uid] = $account;
                // Save fields on user.
                $user_wrapper = import_users_save_fields($mapping, $row, $account);
                fwrite($stdout, "[{$row_count}] Imported: {$account->name}\n");
                $row_count++;
            }
        }
        fclose($handle);
        fwrite($stdout, str_repeat('-', 30) . "\n");
        fwrite($stdout, $row_count - 1 . " users were imported\n");
        return $users;
    }
    return FALSE;
}
 /**
  * Function to convert csv data into an
  * associative array. Sourced from
  * http://pastebin.com/LtmGzpxF
  * @param $filename
  * @param string $delimiter
  * @return array|bool
  */
 protected function csv_to_array($filename, $delimiter = ',')
 {
     // If the file doesn't exist, or isn't readable,
     // return false. The seeding will fail at this point.
     if (!file_exists($filename) || !is_readable($filename)) {
         return false;
     }
     $header = NULL;
     $data = array();
     if (($handle = fopen($filename, 'r')) !== FALSE) {
         // While there are still rows in the file
         while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
             // Below conditional forms the associated array,
             // filling each array within with data from each
             // row.
             if (!$header) {
                 $header = $row;
             } else {
                 $data[] = array_combine($header, $row);
             }
         }
         // Close access to the file.
         fclose($handle);
     }
     return $data;
 }
Example #28
0
function extract_columns(&$columns, $file, $length)
{
    $fp = fopen($file, 'r');
    $index = 0;
    $z = 0;
    $mu = 0;
    $dmu = 0;
    while ($cols = fgetcsv($fp, 1024, ",")) {
        if (empty($cols[0])) {
            continue;
        }
        $pm_count = substr_count($cols[0], "±");
        if ($pm_count > 1) {
            $index += $pm_count - 1;
            $cols[0] = trim(skip($cols[0], " ", 4 * ($pm_count - 1)));
            echo $cols[0] . "\n";
        }
        if ($index == 1) {
            $z = $cols[0];
        }
        if ($index == 6) {
            $mu = (double) $cols[0];
            $dmu = trim(substr($cols[0], strpos($cols[0], "±") + 2));
        }
        if ($index >= $length - 1) {
            $index = 0;
            $columns[] = array($z, $mu, $dmu);
        } else {
            ++$index;
        }
    }
}
Example #29
0
	public function import($fn) {

		if (($handle = fopen($fn, "r")) !== FALSE) {
			$row = 0;

		    while (($data = fgetcsv($handle, 1000, $this->CSV_SEPARATOR, $this->CSV_ENCLOSURE)) !== FALSE) {
				$num = count($data);
				$row++;
				$item = array();

				for ($c=0; $c < $num; $c++) {
					$item[] = $data[$c];
				}

				if( count($item) == 6 ) {
					$this->db->query('UPDATE '. DB_PREFIX . 'product SET quantity = "'.$item[4].'", price = '.$item[5].' WHERE product_id = '.(int)$item[0]);
				} elseif ( count($item) == 3 ){
					$this->db->query('UPDATE '. DB_PREFIX . 'product SET quantity = "'.$item[1].'", price = '.$item[2].' WHERE model = "'.$item[0].'"');
				}elseif ( count($item) == 2 ){
					$this->db->query('UPDATE '. DB_PREFIX . 'product SET price = '.$item[1].' WHERE model = "'.$item[0].'"');
				}

				unset($item);
			}
		    fclose($handle);
		}
		$this->cache->delete('product');
	}
 /**
  * Обработать файл
  */
 public function processFile()
 {
     $file = file_get_contents($this->getAddress());
     $coding = mb_detect_encoding($file, mb_detect_order(), true);
     if (!$coding) {
         $file = iconv("WINDOWS-1251", "UTF-8", $file);
         file_put_contents($this->getAddress(), $file);
     }
     $file = fopen($this->getAddress(), 'r');
     $isFirst = true;
     $accidents = [];
     while (($data = fgetcsv($file, null, ';')) !== FALSE) {
         if ($isFirst) {
             $isFirst = false;
             continue;
         }
         $item = ['description' => $data[1], 'lng' => str_replace(',', '.', $data[2]), 'lat' => str_replace(',', '.', $data[3]), 'date' => \DateTime::createFromFormat('d.m.Y H:m', $data[0])->format('Y-m-d H:m:s')];
         if ($item['description'] == 'ДТП БЕЗ ПОТЕРПIЛИХ') {
             $item['status'] = Enum::ACCIDENT_STATUS_VICTIMS;
         } elseif ($item['description'] == 'ДТП З ПОТЕРПIЛИМИ') {
             $item['status'] = Enum::ACCIDENT_STATUS_DEATHS;
         } else {
             continue;
         }
         $accidents[] = $item;
     }
     return Accident::find()->insetBatchAccidents($accidents);
 }