protected static function checkFileContent() { $fileContent = file_get_contents(static::$tmpFilepath); // check encoding and convert to utf-8 when necessary $detectedEncoding = mb_detect_encoding($fileContent, 'UTF-8, ISO-8859-1, WINDOWS-1252', true); if ($detectedEncoding) { if ($detectedEncoding !== 'UTF-8') { $fileContent = iconv($detectedEncoding, 'UTF-8', $fileContent); } } else { echo 'Zeichensatz der CSV-Date stimmt nicht. Der sollte UTF-8 oder ISO-8856-1 sein.'; return false; } //prepare data array $tmpData = str_getcsv($fileContent, PHP_EOL); array_shift($tmpData); $preparedData = []; $data = array_map(function ($row) use(&$preparedData) { $tmpDataArray = str_getcsv($row, ';'); $tmpKey = trim($tmpDataArray[0]); array_shift($tmpDataArray); $preparedData[$tmpKey] = $tmpDataArray; }, $tmpData); // generate json $jsonContent = json_encode($preparedData, JSON_HEX_TAG | JSON_HEX_AMP); self::$jsonContent = $jsonContent; return true; }
/** * Unserializes a CSV string to an array * * @param string $src * @param array $opts * * @return array */ function csv_unserialize(string $src, array $opts = []) : array { $opts = array_replace(CSV_OPTS, $opts); if (!($rows = str_getcsv($src, "\n"))) { return []; } $data = []; $keys = []; if ($opts['first_row_as_keys']) { $keys = $rows[0]; unset($rows[0]); } elseif ($opts['keys'] && is_array($opts['keys'])) { $keys = $opts['keys']; } $k = count($keys); $skel = array_fill(0, $k, null); foreach ($rows as $row => $item) { $item = str_getcsv($item, $opts['delimiter'], $opts['enclosure'], $opts['escape']); if ($opts['single_item']) { $data[$item[0]] = $item[1]; } elseif ($keys) { $item = $k >= count($item) ? array_replace($skel, $item) : array_slice($item, 0, $k); $data[] = array_combine($keys, $item); } else { $data[] = $item; } } return $data; }
function smarty_function_mtarraymerge($args, &$ctx) { if (isset($args['name'])) { $names = $args['name']; } if (isset($args['set'])) { $set = $args['set']; } if (!$names) { return ''; } if (!is_array($names)) { if (strpos($names, ':') !== FALSE) { $names = str_getcsv($names, ':'); $_names = array(); foreach ($names as $name) { array_push($_names, $name); } $names = $_names; } } $new_var = array(); foreach ($names as $name) { $var = $ctx->__stash['vars'][$name]; if (!$var) { $var = $ctx->__stash['vars'][strtolower($name)]; } $new_var = array_merge($new_var, $var); } $ctx->__stash['vars'][$set] = $new_var; $ctx->__stash['vars'][strtolower($set)] = $new_var; }
protected function csvToContactCollection($input) { $input = str_getcsv($input, "\n"); //parse the rows $headings = array_shift($input); $headings = str_getcsv($headings, ','); $contacts = array(); while ($row = array_shift($input)) { $row = str_getcsv($row, ","); //parse the items in rows $item = array(); $reason = $row[0]; $email = $row[1]; $contact = new ContactWithReason(array('email' => $email, 'reason' => $reason)); foreach ($row as $idx => $value) { if ($idx < 2) { continue; } $contact->setDataField(strtoupper($headings[$idx]), $value); } $contacts[] = $contact; } $collection = new ContactCollection($contacts); return $collection; }
/** * Read the resource as CSV data * * @param uri * The resource uri * @param args default null * If not null, will process the csv using mustache template * @param fields default null * If not null, will take this as the fields, if not, will use the first line * @param flat default true * If true, will flattern all the fields * @param enclosure default " * The enclosure of the CSV * @param escape default \ * The escape character of the CSV */ public function read($uri, $args = null, $fields = null, $flat = true, $delimiter = ",", $enclosure = '"', $escape = "\\") { $r = new Resource($uri); $c = $r->contents(); if ($c) { if ($args) { $c = \Clips\out("string://" . $c, $args, false); } $ret = array(); foreach (explode("\n", $c) as $line) { $s = trim($line); if ($s) { $data = str_getcsv($s); if ($fields) { $d = array(); for ($i = 0; $i < count($fields); $i++) { $d[$fields[$i]] = $data[$i]; } $ret[] = $d; } else { if ($flat) { $fields = array_map(function ($item) { return \Clips\to_flat($item); }, $data); } else { $fields = $data; } } } } return $ret; } return array(); }
protected function __construct() { $idFile = wfTempDir() . '/mw-' . __CLASS__ . '-UID-nodeid'; $nodeId = is_file( $idFile ) ? file_get_contents( $idFile ) : ''; // Try to get some ID that uniquely identifies this machine (RFC 4122)... if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) { wfSuppressWarnings(); if ( wfIsWindows() ) { // http://technet.microsoft.com/en-us/library/bb490913.aspx $csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) ); $line = substr( $csv, 0, strcspn( $csv, "\n" ) ); $info = str_getcsv( $line ); $nodeId = isset( $info[0] ) ? str_replace( '-', '', $info[0] ) : ''; } elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X // See http://linux.die.net/man/8/ifconfig $m = array(); preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/', wfShellExec( '/sbin/ifconfig -a' ), $m ); $nodeId = isset( $m[1] ) ? str_replace( ':', '', $m[1] ) : ''; } wfRestoreWarnings(); if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) { $nodeId = MWCryptRand::generateHex( 12, true ); $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 ); // set multicast bit } file_put_contents( $idFile, $nodeId ); // cache } $this->nodeId32 = wfBaseConvert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 ); $this->nodeId48 = wfBaseConvert( $nodeId, 16, 2, 48 ); // If different processes run as different users, they may have different temp dirs. // This is dealt with by initializing the clock sequence number and counters randomly. $this->lockFile88 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-88'; $this->lockFile128 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-128'; }
private function logRainMessage() { $parts = str_getcsv($this->message_obj->message); $date = explode('/', $parts[0]); $time = explode(':', $parts[1]); $measuring_timestamp = mktime($time[0], $time[1], 0, $date[1], $date[2], '20' . $date[0]); $criteria = new CDbCriteria(); $criteria->condition = "DATE_FORMAT(measuring_timestamp, '%Y-%m-%d %H:%i:%s') = :measuring_timestamp AND sensor_id = :sensor_id"; $criteria->params = array(':measuring_timestamp' => date('Y-m-d H:i:s', $measuring_timestamp), ':sensor_id' => $this->_sensor->station_sensor_id); $sensor_data = SensorDataMinute::model()->find($criteria); if (!$sensor_data || $sensor_data->is_tmp || $this->message_obj->rewrite_prev_values) { if (!$sensor_data) { $sensor_data = new SensorDataMinute(); $sensor_data->sensor_id = $this->_sensor->station_sensor_id; $sensor_data->station_id = $this->message_obj->station_id; } $sensor_data->sensor_value = $parts[3]; $sensor_data->bucket_size = $this->_sensor->bucket_size; $sensor_data->listener_log_id = $this->message_obj->log_id; $sensor_data->measuring_timestamp = date('Y-m-d H:i:s', $measuring_timestamp); $sensor_data->battery_voltage = $parts[2]; $sensor_data->is_tmp = 0; $sensor_data->save(); } }
public function main() { // load CURL class require dirname(__FILE__) . '/lib/CURL.php'; // iterator over hashes foreach ($this->hashes as $index => $hash) { // check if csv line data $fields = str_getcsv($hash, ';'); if (count($fields) > 1) { $this->out('Trying hash: ' . implode(', ', $fields) . ' … ', false); $hash = $fields[count($fields) - 1]; } else { $this->out('Trying hash: ' . $hash . ' … ', false); } // use curl to send request to md5crack $CURL = new CURL('http://md5crack.com/crackmd5.php', array(CURLOPT_POSTFIELDS => array('term' => $hash, 'crackbtn' => true))); // search for result string if (preg_match('@Found:\\s+md5\\("(?P<source>.+)"\\)\\s=\\s+([a-z0-9]+)@mi', $CURL->read(), $found)) { $this->out($found['source']); } else { $this->out('not found'); } } $this->quit('done!'); }
public function localSqlSync() { $dump_dir = UNISH_SANDBOX . "/dump-dir"; if (!is_dir($dump_dir)) { mkdir($dump_dir); } // Create a user in the staging site $name = 'joe.user'; $mail = "*****@*****.**"; $options = array('root' => $this->webroot(), 'uri' => 'stage', 'yes' => NULL); $this->drush('user-create', array($name), $options + array('password' => 'password', 'mail' => $mail)); // Copy stage to dev with --sanitize $sync_options = array('sanitize' => NULL, 'yes' => NULL, 'dump-dir' => $dump_dir); $this->drush('sql-sync', array('@stage', '@dev'), $sync_options); // Confirm that the sample user has the correct email address on the staging site $this->drush('user-information', array($name), $options + array('pipe' => NULL)); $output = $this->getOutput(); $row = str_getcsv($output); $uid = $row[1]; $this->assertEquals($mail, $row[2], 'email address is unchanged on source site.'); $this->assertEquals($name, $row[0]); $options = array('root' => $this->webroot(), 'uri' => 'dev', 'yes' => NULL); // Confirm that the sample user's email address has been sanitized on the dev site $this->drush('user-information', array($name), $options + array('pipe' => NULL)); $output = $this->getOutput(); $row = str_getcsv($output); $uid = $row[1]; $this->assertEquals("user+{$uid}@localhost", $row[2], 'email address was sanitized on destination site.'); $this->assertEquals($name, $row[0]); }
/** * Initialize CSV data * * @param string|array $data CSV data * * @throws InvalidArgumentException if the $data value is not a string or array * @throws UnexpectedValueException if a row cannot be parsed */ public function __construct($data) { if (is_array($data)) { if (!isset($data[0])) { throw new InvalidArgumentException('Data rows must be numerically keyed'); } $this->fieldNames = array_keys($data[0]); $this->rows = $data; } else { if (is_string($data)) { // Split rows by newlines $this->rows = str_getcsv($data, "\n"); foreach ($this->rows as &$row) { // Split columns by tab $row = str_getcsv($row, "\t"); } // First row is the header, use as array keys $this->fieldNames = array_shift($this->rows); // Iterate over remaining rows, parse into columns foreach ($this->rows as $i => &$row) { if (count($this->fieldNames) != count($row)) { //throw new UnexpectedValueException('Error parsing row ' . $i); continue; } $row = array_combine($this->fieldNames, $row); } } else { throw new InvalidArgumentException('$data must be a string or an array'); } } unset($data); }
/** * Upload graduate attributes and insert all entries to graduateattributes table. * @param object $mform form definition * @return void */ private function upload_graduate_attributes($mform) { global $DB, $CFG, $USER; $gradatt_was_uploaded = $mform->getSubmitValue('upload_gradatt'); if ($gradatt_was_uploaded) { $files = $this->get_draft_files('temp_gradatt'); if (!empty($files)) { $file = reset($files); $content = $file->get_content(); $all_rows = explode("\n", $content); $current_parent = 0; foreach ($all_rows as $row) { $parsed = str_getcsv($row); if (!is_null($parsed[0])) { // $parsed[0] is not empty, then it is the main level if ($parsed[0] != '') { $parent = new stdClass(); $parent->attribute = $parsed[1]; $insert_gradatt = $DB->insert_record('graduateattributes', $parent, true, false); $current_parent = $insert_gradatt; $node = new stdClass(); $node->attribute = $parsed[3]; $node->node = $current_parent; $insert_sub_gradatt = $DB->insert_record('graduateattributes', $node, true, false); } else { $node = new stdClass(); $node->attribute = $parsed[3]; $node->node = $current_parent; $insert_sub_gradatt = $DB->insert_record('graduateattributes', $node, true, false); } } } } } }
/** * @param string $input * @param string $delimiter * @param array $options * @throws ParseException * @return array */ public function parse($input, $delimiter = ';', array $options = array()) { $default_options = array('encoding_source' => 'UTF-8', 'encoding_target' => 'UTF-8'); $options = array_merge($default_options, $options); try { $input = iconv($options['encoding_source'], $options['encoding_target'], $input); } catch (\Exception $e) { throw new ParseException('The file might not be a CSV file after all.'); } if (preg_split('/$\\R?^/m', $input) > explode("\r\n", $input)) { $lines = preg_split('/$\\R?^/m', $input); } else { $lines = explode("\r\n", $input); } $lines = array_map('trim', $lines); $header = trim($lines[0]); unset($lines[0]); $keys = explode($delimiter, $header); $result = array(); foreach ($lines as $line_no => $line) { if (0 === strlen($line)) { continue; } $values = str_getcsv($line, $delimiter); try { if (is_array($keys) && is_array($values) && count($keys) !== count($values)) { throw new \DomainException(); } $result[] = array_combine($keys, $values); } catch (\DomainException $e) { throw new ParseException(sprintf('The CSV-file seems to be damaged. Found %d header columns but %d data columns on line %d.', count($keys), count($values), $line_no)); } } return $result; }
/** * Given a CSV file, generate a resulting XML tree * * @param string $data * @return string */ public static function convertToXML($data) { $headers = array(); // Get CSV settings $settings = array('csv-delimiter' => ',', 'csv-enclosure' => '"', 'csv-escape' => '\\'); $settings = array_merge($settings, (array) Symphony::Configuration()->get('remote_datasource')); // DOMDocument $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = $doc->createElement('data'); $doc->appendChild($root); foreach (str_getcsv($data, PHP_EOL) as $i => $row) { if (empty($row)) { continue; } if ($i == 0) { foreach (str_getcsv($row, $settings['csv-delimiter'], $settings['csv-enclosure'], $settings['csv-escape']) as $i => $head) { if (class_exists('Lang')) { $head = Lang::createHandle($head); } $headers[] = $head; } } else { self::addRow($doc, $root, str_getcsv($row, $settings['csv-delimiter'], $settings['csv-enclosure'], $settings['csv-escape']), $headers); } } $output = $doc->saveXML($doc->documentElement); return trim($output); }
public function __construct($harvester, $name, $parameters) { parent::__construct($harvester, $name, $parameters); // Load in the corrections from the datafile. if (array_key_exists('datafile', $parameters)) { $datafile = $parameters['datafile']; $datafile = $harvester->resolvePath($datafile); if ($datafile) { $datafile = file_get_contents($datafile); $datafile_rows = str_getcsv($datafile, "\n"); foreach ($datafile_rows as $row) { $row = str_getcsv($row, ";"); if (count($row) != 3) { throw new \RuntimeException("Malformed datafile, all rows have to have exact 3 collumns, seperated by semicolons."); } $brokenProductionID = strval($row[0]); $correctProductionID = strval($row[1]); $assetID = strval($row[2]); if (is_numeric($correctProductionID) && is_numeric($assetID)) { $this->_translationsByBrokenProductionID[$brokenProductionID] = $correctProductionID; $this->_translationsByAssetID[$assetID] = $correctProductionID; } else { $harvester->debug("A line in the {$name} " . __CLASS__ . " datafile had non-nummeric values: It was skipped."); } } } else { throw new \Exception("The " . __CLASS__ . " has to have a datafile parameter that points to a datafile."); } } else { throw new \Exception("The " . __CLASS__ . " has to have a datafile parameter."); } }
/** * Format csv into array. * @param string of csv to be formatted * @return array of formatted csv values */ public static function csvToArray($csv = false) { if ($csv) { return str_getcsv($csv); } return false; }
/** * Load Matrix. * Load csv file containing the Database translation information. * * @param string $filePath. * * @return array. */ public function LoadMatrix($filePath = null) { // Default file path if (empty($filePath)) { $filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . self::MARTIX_FILE_NAME; } // Ensure the path is readable if (!is_readable($filePath)) { throw new Exception('DB Roller: File not readable: ' . $filePath); } // Get the File Contents $dataString = file_get_contents($filePath); if (empty($dataString)) { throw new Exception('DB Roller: File was empty or failed to load: ' . $filePath); } // Normalise Linebreaks //$dataString = preg_replace('/\r\n|\r|\n/', PHP_EOL, $dataString); $dataString = str_replace(array("\r\n", "\r", "\n"), PHP_EOL, $dataString); // Create Matrix as a Multi-Dim Array $this->matrix = array_map(function ($row) { return array_map(function ($col) { return strtoupper(trim($col)); }, str_getcsv($row)); }, explode(PHP_EOL, $dataString)); // Return the Matrix return $this->matrix; }
function getWeatherData($strURL, $strCacheFile, $intLimitHours, &$strGeographicLocation) { if (!file_exists($strCacheFile) || filemtime($strCacheFile) + 60 * 60 * $intLimitHours < time()) { $arrCacheData = file($strURL); if (!$arrCacheData) { die('Problem Retrieving NOAA Data! Please try your request again.'); } $arrGeographicLocation = explode('"', $arrCacheData[1], 3); $strGeographicLocation = str_replace('"', '', $arrGeographicLocation[1]); $arrCacheData = array_filter($arrCacheData, "removeWeatherXMLCruft"); $arrCacheData = array_merge($arrCacheData); $fdCacheFile = fopen($strCacheFile, "w"); fputs($fdCacheFile, $strGeographicLocation . "\n"); for ($i = 0; $i < sizeof($arrCacheData); $i++) { fputs($fdCacheFile, $arrCacheData[$i]); } fclose($fdCacheFile); } $arrCacheData = array(); $fdCacheFile = fopen($strCacheFile, "r"); $strGeographicLocation = stream_get_line($fdCacheFile, 4096, "\n"); while (!feof($fdCacheFile)) { $arrCacheData[] = stream_get_line($fdCacheFile, 4096, "\n"); } fclose($fdCacheFile); $strWeatherData = implode("\r\n", $arrCacheData); $strWeatherData = strip_tags(str_replace(array(',', "\r\n"), array('', ','), $strWeatherData)); $arrCacheData = str_getcsv($strWeatherData); return array_chunk($arrCacheData, 3); }
/** * @param $csv * * @return array */ private function parseCSV($csv) { $rates = array(); $countries = array('Euro' => 'EUR', 'Japanese Yen' => 'JPY', 'U.K. Pound Sterling' => 'GBP', 'U.S. Dollar' => 'USD', 'Algerian Dinar' => 'DZD', 'Argentine Peso' => 'ARS', 'Australian Dollar' => 'AUD', 'Bahrain Dinar' => 'BHD', 'Botswana Pula' => 'BWP', 'Brazilian Real' => 'BRL', 'Brunei Dollar' => 'BND', 'Canadian Dollar' => 'CAD', 'Chilean Peso' => 'CLP', 'Chinese Yuan' => 'CNY', 'Colombian Peso' => 'COP', 'Czech Koruna' => 'CZK', 'Danish Krone' => 'DKK', 'Hungarian Forint' => 'HUF', 'Icelandic Krona' => 'ISK', 'Indian Rupee' => 'INR', 'Indonesian Rupiah' => 'IDR', 'Iranian Rial' => 'IRR', 'Israeli New Sheqel' => 'ILS', 'Kazakhstani Tenge' => 'KZT', 'Korean Won' => 'KPW', 'Kuwaiti Dinar' => 'KWD', 'Libyan Dinar' => 'LYD', 'Malaysian Ringgit' => 'MYR', 'Mauritian Rupee' => 'MUR', 'Mexican Peso' => 'MXN', 'Nepalese Rupee' => 'NPR', 'New Zealand Dollar' => 'NZD', 'Norwegian Krone' => 'NOK', 'Pakistani Rupee' => 'PKR', 'Nuevo Sol' => 'PEN', 'Philippine Peso' => 'PHP', 'Polish Zloty' => 'PLN', 'Qatar Riyal' => 'QAR', 'Russian Ruble' => 'RUB', 'Saudi Arabian Riyal' => 'SAR', 'Singapore Dollar' => 'SGD', 'South African Rand' => 'ZAR', 'Sri Lanka Rupee' => 'LKR', 'Swedish Krona' => 'SEK', 'Swiss Franc' => 'CHF', 'Thai Baht' => 'THB', 'Trinidad And Tobago Dollar' => 'TTD', 'Tunisian Dinar' => 'TND', 'U.A.E. Dirham' => 'AED', 'Peso Uruguayo' => 'UYU', 'Bolivar Fuerte' => 'VEF'); preg_match('/SDRs per Currency unit \\(2\\)\\s+(?P<rates>.*)Currency units per SDR\\(3\\)/isU', $csv, $csv); $records = explode("\n", trim($csv['rates'])); // SDR Values foreach ($records as $record) { $record = preg_replace('/\\t+/', "\t", $record); $fields = str_getcsv($record, "\t", '"', '\\'); if (!empty($fields[0]) && is_numeric($fields[1])) { $countries[$fields[0]] = !empty($countries[$fields[0]]) ? $countries[$fields[0]] : $fields[0]; $rates[$countries[$fields[0]]] = $fields[1]; } } // USD Exchange rates $baseRate = $rates['USD']; if ($baseRate > 0) { foreach ($rates as $currency => $rate) { if ($rate != 0) { $rates[$currency] = $rate / $baseRate; } } } return $rates; }
public function parse() { $i = null; list($headers, $this->csv) = explode("\n", $this->csv, 2); $headers = str_getcsv($headers, ',', '"'); foreach ($headers as $header) { $this->{$header} = []; $this->keymap[(int) $i++] = $header; } $i = null; $lines = explode("\n", $this->csv); foreach ($lines as $line) { $columns = str_getcsv($line, ',', '"'); if (count($columns) > count($this->keymap)) { continue; } foreach ($columns as $column) { $num = (int) $i++; $header = $this->keymap[$num]; $data[$header] = $column; } $this->data[] = $data; $data = null; $i = null; } return $this->data; }
function smarty_function_mtdeletevars($args, &$ctx) { if (isset($args['name'])) { $name = $args['name']; } if (!$name) { return ''; } $names = array(); if (!is_array($name)) { if (strpos($name, ':') !== FALSE) { $_names = str_getcsv($name, ':'); $__names = array(); foreach ($_names as $_name) { if (strpos($_name, 'Array.') === 0) { $_name = str_replace('Array.', '', $_name); $_name = $ctx->__stash['vars'][$_name]; } array_push($__names, $_name); } $names = $__names; } else { if (strpos($name, ' ') !== FALSE) { $names = explode(' ', $name); } else { $names = array($name); } } } foreach ($names as $name) { $name = trim($name); unset($ctx->__stash['vars'][$name]); } }
public function validate($value, Constraint $constraint) { $data = $this->ut->formatCsvOutput(file_get_contents($value)); $lines = str_getcsv($data, PHP_EOL); foreach ($lines as $line) { $linesTab = explode(';', $line); $nbElements = count($linesTab); if (trim($line) !== '') { if ($nbElements < 2) { $this->context->addViolation($constraint->message); return; } } } foreach ($lines as $i => $line) { $line = trim($line); $tab = explode(';', $line); $code = $tab[0]; $workspace = $this->om->getRepository('ClarolineCoreBundle:Workspace\\Workspace')->findOneByCode($code); if (!$workspace) { $msg = $this->translator->trans('workspace_not_exists', ['%code%' => $code, '%line%' => $i + 1], 'platform') . ' '; $this->context->addViolation($msg); } } }
public static function parse($text) { $Data = str_getcsv($text, "\n"); //parse the rows $arrFirstUser = false; foreach ($Data as $row) { $arrRow = str_getcsv($row); if ($arrRow[0] === 'Player') { continue; } if (!$arrFirstUser) { $arrFirstUser = $arrRow; } $data['members'][] = array(trim($arrRow[0]), '', '', 0); $data['times'][] = array(trim($arrRow[0]), strtotime($arrRow[4]), 'join'); $data['times'][] = array(trim($arrRow[0]), strtotime($arrRow[6]), 'leave'); //Loot, 9 $strLootLine = $arrRow[9]; if ($strLootLine != "") { $arrLootArray = array(); $intMatches = preg_match_all("/(.*)\\(([0-9]*)\\)/U", $strLootLine, $arrLootArray); if ($intMatches > 0) { foreach ($arrLootArray[0] as $key => $val) { $data['items'][] = array(trim($arrLootArray[1][$key]), trim($arrRow[0]), 0, trim($arrLootArray[2][$key]), strtotime($arrRow[4]) + 100); } } } } if ($arrFirstUser) { $data['zones'][] = array($arrFirstUser[5], strtotime($arrRow[4]), strtotime($arrRow[6])); } return $data; }
function xmldb_editor_tinymce_upgrade($oldversion) { global $CFG, $DB; if ($oldversion < 2014062900) { // We only want to delete DragMath from the customtoolbar setting if the directory no longer exists. If // the directory is present then it means it has been restored, so do not remove any settings. if (!check_dir_exists($CFG->libdir . '/editor/tinymce/plugins/dragmath', false)) { // Remove the DragMath plugin from the 'customtoolbar' setting (if it exists) as it has been removed. $currentorder = get_config('editor_tinymce', 'customtoolbar'); $newtoolbarrows = array(); $currenttoolbarrows = explode("\n", $currentorder); foreach ($currenttoolbarrows as $currenttoolbarrow) { $currenttoolbarrow = implode(',', array_diff(str_getcsv($currenttoolbarrow), array('dragmath'))); $newtoolbarrows[] = $currenttoolbarrow; } $neworder = implode("\n", $newtoolbarrows); unset_config('customtoolbar', 'editor_tinymce'); set_config('customtoolbar', $neworder, 'editor_tinymce'); } upgrade_plugin_savepoint(true, 2014062900, 'editor', 'tinymce'); } // Moodle v2.8.0 release upgrade line. // Put any upgrade step following this. // Moodle v2.9.0 release upgrade line. // Put any upgrade step following this. // Moodle v3.0.0 release upgrade line. // Put any upgrade step following this. // Moodle v3.1.0 release upgrade line. // Put any upgrade step following this. return true; }
/** * Retrieve the current process' memory usage using Windows command line interface * * @link http://technet.microsoft.com/en-us/library/bb491010.aspx * @param int $pid * @return int Memory usage in bytes */ protected function _getWinProcessMemoryUsage($pid) { $output = $this->_shell->execute('tasklist.exe /fi %s /fo CSV /nh', ["PID eq {$pid}"]); $arr = str_getcsv($output); $memory = $arr[4]; return self::convertToBytes($memory); }
/** * Convert a value * * @param mixed $input Input value * * @return mixed */ public function convert($input) { $input = str_getcsv($input, ' ', '"'); if ($input[0] == "issue") { switch ($input[1]) { case "add": $postData = array("project" => $input[2], "summary" => $input[3], "description" => $input[4]); $input["endpoint"] = "youtrack/rest/issue?" . http_build_query($postData); $input["requestType"] = "PUT"; $input["commandType"] = $input[1]; break; case "delete": $postData = array("issue" => $input[2]); $input["endpoint"] = "issue?" . http_build_query($postData); $input["requestType"] = "DELETE"; $input["commandType"] = $input[1]; break; default: $input["endpoint"] = null; $input["requestType"] = null; $input["commandType"] = null; break; } } if ($input[0] === "login") { $username = $input[1]; $password = $input[2]; $postData = array("login" => $username, "password" => $password); $input["endpoint"] = "youtrack/rest/user/login?" . http_build_query($postData); $input["requestType"] = "POST"; $input["commandType"] = "login"; } return $input; }
/** * {@inheritdoc} */ public function find($ip, $url, $limit, $method, $start = null, $end = null) { $file = $this->getIndexFilename(); if (!file_exists($file)) { return array(); } $file = fopen($file, 'r'); fseek($file, 0, SEEK_END); $result = array(); while (count($result) < $limit && ($line = $this->readLineFromFile($file))) { $values = str_getcsv($line); list($csvToken, $csvIp, $csvMethod, $csvUrl, $csvTime, $csvParent) = $values; $csvStatusCode = isset($values[6]) ? $values[6] : null; $csvTime = (int) $csvTime; if ($ip && false === strpos($csvIp, $ip) || $url && false === strpos($csvUrl, $url) || $method && false === strpos($csvMethod, $method)) { continue; } if (!empty($start) && $csvTime < $start) { continue; } if (!empty($end) && $csvTime > $end) { continue; } $result[$csvToken] = array('token' => $csvToken, 'ip' => $csvIp, 'method' => $csvMethod, 'url' => $csvUrl, 'time' => $csvTime, 'parent' => $csvParent, 'status_code' => $csvStatusCode); } fclose($file); return array_values($result); }
public static function fromString($headerLine) { list($fieldName, $fieldValue) = GenericHeader::splitHeaderLine($headerLine); $decodedValue = HeaderWrap::mimeDecodeValue($fieldValue); $wasEncoded = $decodedValue !== $fieldValue; $fieldValue = $decodedValue; if (strtolower($fieldName) !== static::$type) { throw new Exception\InvalidArgumentException(sprintf('Invalid header line for "%s" string', __CLASS__)); } $header = new static(); if ($wasEncoded) { $header->setEncoding('UTF-8'); } // split value on "," $fieldValue = str_replace(Headers::FOLDING, ' ', $fieldValue); $fieldValue = preg_replace('/[^:]+:([^;]*);/', '$1,', $fieldValue); $values = str_getcsv($fieldValue, ','); array_walk($values, function (&$value) { $value = trim($value); $value = self::stripComments($value); }); $values = array_filter($values); $addressList = $header->getAddressList(); foreach ($values as $address) { $addressList->addFromString($address); } return $header; }
/** * {@inheritdoc} */ public function find($ip, $url, $limit, $method) { $file = $this->getIndexFilename(); if (!file_exists($file)) { return array(); } $file = fopen($file, 'r'); fseek($file, 0, SEEK_END); $result = array(); while ($limit > 0) { $line = $this->readLineFromFile($file); if (false === $line) { break; } if ($line === '') { continue; } list($csvToken, $csvIp, $csvMethod, $csvUrl, $csvTime, $csvParent) = str_getcsv($line); if ($ip && false === strpos($csvIp, $ip) || $url && false === strpos($csvUrl, $url) || $method && false === strpos($csvMethod, $method)) { continue; } $result[$csvToken] = array('token' => $csvToken, 'ip' => $csvIp, 'method' => $csvMethod, 'url' => $csvUrl, 'time' => $csvTime, 'parent' => $csvParent); --$limit; } fclose($file); return array_values($result); }
/** maximum row size to be used for decoding */ function parse_file($p_Filepath) { $file = fopen($p_Filepath, 'r'); $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure); $keys = str_getcsv($this->fields[0]); $i = 1; while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) { if ($row != null) { // skip empty lines $values = str_getcsv($row[0]); if (count($keys) == count($values)) { $arr = array(); for ($j = 0; $j < count($keys); $j++) { if ($keys[$j] != "") { $arr[$keys[$j]] = $values[$j]; } } $content[$i] = $arr; $i++; } } } fclose($file); return $content; }
public function getActiveStocks() { /* $url = 'http://bsx.jlparry.com/data/stocks'; $data = array( ); // use key 'http' even if you send the request to https://... $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false); if ($result == FALSE) { /* Handle error } $actStocks = array(); $actStocks =str_getcsv ( string $result [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] ) //$gameState['stockinfo']= return $actStocks; //var_dump($result); */ $url = DATAPATH . 'data/' . 'stocks'; $csv = file_get_contents($url); $csvData = file_get_contents($csv); $lines = explode(PHP_EOL, $csvData); $array = array(); foreach ($lines as $line) { $array[] = str_getcsv($line); } print_r($array); }