Example #1
0
/**
 * Handle POST submission
 *
 * @param array $options
 * @return void
 */
function process_unit_import($options)
{
    if (empty($_FILES['unit_import']['tmp_name'])) {
        $error = 'No file uploaded, aborting.';
        print_messages($error);
        return;
    }
    if (!current_user_can('import')) {
        $error = 'You don\'t have the permissions to import. Please contact the blog\'s administrator.';
        print_messages($error);
        return;
    }
    check_admin_referer('brave_blank_unit_import_verify');
    require_once 'DataSource.php';
    $time_start = microtime(true);
    $csv = new File_CSV_DataSource();
    $file = $_FILES['unit_import']['tmp_name'];
    stripBOM($file);
    if (!$csv->load($file)) {
        $error = 'Failed to load file, aborting.';
        print_messages($error);
        return;
    }
    // pad shorter rows with empty values
    // $csv->symmetrize();
    $skipped = 0;
    $imported = 0;
    foreach ($csv->connect() as $csv_data) {
        $id = create_unit($csv_data);
        if (is_numeric($id)) {
            $imported++;
        } else {
            print_messages($id);
            return;
        }
    }
    if (file_exists($file)) {
        @unlink($file);
    }
    $exec_time = microtime(true) - $time_start;
    $notice = "";
    if ($skipped) {
        $notice += "<b>Skipped {$skipped} posts (most likely due to empty title, body and excerpt).</b></br>";
    }
    $notice += sprintf("<b>Imported {$imported} posts %.2f seconds.</b>", $exec_time);
    print_messages($notice);
}
 /**
  * Проверяем структуру присланного файла
  * @return bool true если структура верна
  */
 private function _testStructure()
 {
     if (!$this->_csvDataSource->isSymmetric()) {
         return false;
     }
     $wantedHeaders = array('ReceiptDate', 'TransactionType', 'Account', 'Value', 'Currency', 'Category', 'Comment');
     $intersection = array_intersect($wantedHeaders, $this->_csvDataSource->getHeaders());
     if (count($wantedHeaders) != count($intersection)) {
         return false;
     }
     return true;
 }
 protected function _getCSV()
 {
     $csv = new File_CSV_DataSource();
     $csv->settings = $this->_csv_settings;
     if (!$csv->load($this->_file)) {
         print "\nERROR: file {$this->_file} not found!";
     }
     // Header Namen matchen - Ziel: technische Namen behalten, Beschreibung entfernen
     $headers = $csv->getHeaders();
     //print_r($headers);
     foreach ($headers as $k => $v) {
         $tmp = $v;
         if (preg_match('/\\[(.*)\\]"?$/', $tmp, $match)) {
             $tmp = preg_replace('/[^\\w\\d\\/\\.]/i', '', $match[1]);
         }
         $this->_headers[$k] = $tmp;
     }
     //print "\nHeaders: ";
     //print_r($this->_headers);
     return $csv;
 }
 public function load_file($file, $columns = FALSE)
 {
     ini_set("auto_detect_line_endings", "1");
     $csv = new File_CSV_DataSource();
     $csv->settings(array('eol' => $this->eol, 'delimiter' => $this->delimeter));
     $csv->settings['eol'] = $this->eol;
     if (!$csv->load($file)) {
         die('can not load csv file');
     }
     if (!$csv->isSymmetric()) {
         $csv->symmetrize();
     }
     $entries = $csv->connect();
     return $entries;
 }
function sf_add_schema_ajax()
{
    $file_url = $_REQUEST['file_url'];
    $file_id = $_REQUEST['file_id'];
    if ($file_id) {
        $url = wp_get_attachment_url($file_id);
        $uploads = wp_upload_dir();
        $file_path = str_replace($uploads['baseurl'], $uploads['basedir'], $url);
        require_once SF_INCLUDES_PATH . '/sf-colour-scheme/File_CSV_DataSource/DataSource.php';
        $time_start = microtime(true);
        $csv = new File_CSV_DataSource();
        sf_stripBOM($file_path);
        if (!$csv->load($file_path)) {
            echo 'Failed to load file, aborting.';
            // $this->print_messages();
            die;
        }
        $skipped = 0;
        $csv_array = array();
        foreach ($csv->connect() as $csv_data) {
            $csv_array[] = $csv_data;
        }
        // add new schema from csv data
        sf_add_schema($csv_array);
        // return back a list of schemes to populate the select box via ajax
        echo sf_get_schema_select_html();
        die;
    }
    die;
}
Example #6
0
 /**
  * Handle POST submission
  *
  * @param array $options
  * @return void
  */
 function post($options)
 {
     if (empty($_FILES['csv_import']['tmp_name'])) {
         $this->log['error'][] = 'No file uploaded, aborting.';
         $this->print_messages();
         return;
     }
     require_once 'File_CSV_DataSource/DataSource.php';
     $time_start = microtime(true);
     $csv = new File_CSV_DataSource();
     $file = $_FILES['csv_import']['tmp_name'];
     $this->stripBOM($file);
     if (!$csv->load($file)) {
         $this->log['error'][] = 'Failed to load file, aborting.';
         $this->print_messages();
         return;
     }
     // pad shorter rows with empty values
     $csv->symmetrize();
     // WordPress sets the correct timezone for date functions somewhere
     // in the bowels of wp_insert_post(). We need strtotime() to return
     // correct time before the call to wp_insert_post().
     $tz = get_option('timezone_string');
     if ($tz && function_exists('date_default_timezone_set')) {
         date_default_timezone_set($tz);
     }
     $skipped = 0;
     $imported = 0;
     $comments = 0;
     foreach ($csv->connect() as $csv_data) {
         if ($post_id = $this->create_post($csv_data, $options)) {
             $imported++;
             $comments += $this->add_comments($post_id, $csv_data);
             $this->create_custom_fields($post_id, $csv_data);
         } else {
             $skipped++;
         }
     }
     if (file_exists($file)) {
         @unlink($file);
     }
     $exec_time = microtime(true) - $time_start;
     if ($skipped) {
         $this->log['notice'][] = "<b>Skipped {$skipped} posts (most likely due to empty title, body and excerpt).</b>";
     }
     $this->log['notice'][] = sprintf("<b>Imported {$imported} posts and {$comments} comments in %.2f seconds.</b>", $exec_time);
     $this->print_messages();
 }
 public function install()
 {
     require_once PATH_THIRD . 'gmap/libraries/DataSource.php';
     $csv = new File_CSV_DataSource(PATH_THIRD . 'gmap/data/WorldBorders.csv');
     $this->db->insert_batch('gmap_world_borders', $csv->connect());
 }
Example #8
0
<?php

require_once "DataSource.php";
$url = !empty($_REQUEST['url']) ? $_REQUEST['url'] : 'tests/data/names.csv';
$DEBUG = false;
$csv = new File_CSV_DataSource($url);
//Headers
$headers = $csv->getHeaders();
// array('name', 'age');
$table = "<table border=1><tr>";
foreach ($headers as $h) {
    $table .= '<th style="background:#ccc">' . $h . "</th>";
}
$table .= "</tr>";
//Columns
$csv_array = $csv->connect();
if ($DEBUG) {
    print_r($csv_array);
}
foreach ($csv_array as $csv) {
    $table .= "<tr><td>" . $csv['name'] . "</td><td>" . $csv['age'] . "</td></tr>";
}
$table .= "</table>";
echo $table;
Example #9
0
 public function run()
 {
     $redis = new Redis();
     $redis->pconnect('127.0.0.1');
     echo "Run csvParser\n";
     $dbconn = pg_connect(DB_CONN_STR) or die('Не могу подключиться к БД: ' . pg_last_error());
     //Выберем все не занятые и включенные аккаунты с привязанным прокси
     $query = 'SELECT * FROM accounts WHERE status=0 AND busy<>1 AND proxy_ip<>0 ';
     $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     $accounts = pg_fetch_all($result);
     if (count($accounts) < 1) {
         exit;
     }
     pg_free_result($result);
     //Берем рандомный из этого списка
     $acc_arr = array_rand($accounts);
     //Выбранный аккаунт становится занятым
     $query = 'UPDATE accounts SET busy=1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
     pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     //Выберем список работающих прокси
     $query = 'SELECT * FROM proxys WHERE id = ' . $accounts[$acc_arr]['proxy_ip'];
     $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     $proxy_acc = pg_fetch_row($result);
     pg_free_result($result);
     //Берем случайный из списка
     $proxy = "{$proxy_acc[1]}:{$proxy_acc[2]}";
     $proxyauth = "{$proxy_acc[3]}:{$proxy_acc[4]}";
     //Получаем страну для которой запущен парсер
     $query = 'SELECT co."ID",co.full_name country, co.short_name cntr_code FROM countries co, params p ' . 'WHERE co."ID"=p.country_id';
     $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     $country = pg_fetch_object($result);
     pg_free_result($result);
     //Берем первый ключ в статусе "В ожидании" (keys_status = 1)
     //Если ключ в статусе "No Keywords" (keys_status = 2) - берем другой
     do {
         $key = $redis->sPop("keys_status:{$country->cntr_code}:1");
     } while ($redis->sIsMember("keys_status:{$country->cntr_code}:2", $key));
     //Увеличим количество использования аккаунта
     $query = 'UPDATE accounts SET cnt_work=cnt_work+1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
     pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     echo "--email={$accounts[$acc_arr]['gm_login']} --pass={$accounts[$acc_arr]['gm_pass']} \n\n        --proxy={$proxy} --proxy-auth={$proxyauth} \n\n        --key={$key}";
     //Получаем время запуска и запускаем скрипт casperjs
     $start = microtime(true);
     $q = "/usr/local/bin/casperjs {$this->baseDir}googleKeyPlaner.js --proxy=" . $proxy . " --cookies-file={$this->baseDir}cookies/{$key}.txt " . "--proxy-auth=" . $proxyauth . " --ignore-ssl-errors=yes --web-security=no --key='{$key}' " . "--email={$accounts[$acc_arr]['gm_login']} --pass={$accounts[$acc_arr]['gm_pass']} " . "--verphone={$accounts[$acc_arr]['gm_tel']} --country='{$country->country}' > {$this->baseDir}tempFiles/{$key}-exitParser.txt";
     exec($q, $ret_arr, $ret_val);
     //Если casperjs вернул код выхода 100 - нет keywords для данного ключа. Блокируем ключ
     if ($ret_val == 100) {
         //Блокируем ключ со статусом "No keywords" (keys_status = 2)
         $redis->sAdd("keys_status:{$country->cntr_code}:2", $key);
         //Уменьшаем количество использования аккаунта
         $query = 'UPDATE accounts SET cnt_work=cnt_work-1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
         pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
         //Останавливаем процесс
         exit;
     }
     //Скачиваем файл по полученной ссылке для ключа
     if (is_file($this->baseDir . 'tempFiles/dnld_' . $key . '.txt')) {
         $dnldUrl = file($this->baseDir . 'tempFiles/dnld_' . $key . '.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
         echo '=================Start DownLoad=================';
         $q = "/usr/local/bin/casperjs {$this->baseDir}downloader.js --proxy=" . $proxy . " --cookies-file={$this->baseDir}cookies/{$key}.txt " . "--proxy-auth=" . $proxyauth . " --ignore-ssl-errors=yes --web-security=no --key='{$key}' " . "--dnldUrl='{$dnldUrl[0]}' > {$this->baseDir}tempFiles/{$key}-exitDownloader.txt";
         exec($q, $ret_arr, $ret_val);
     }
     $work_time = microtime(true) - $start;
     //Проверяем наличие скачанного файла для продолжения
     if (is_file($this->baseDir . 'tempGrab/stats_' . $key . '.csv')) {
         $csvObj = new File_CSV_DataSource();
         $csvObj->settings(array('delimiter' => "\t", 'eol' => ''));
         $csvObj->load($this->baseDir . 'tempGrab/stats_' . $key . '.csv');
         $csvObj->symmetrize(0);
         if (!$csvObj->isSymmetric()) {
             echo 'Ошибка! Количество заголовков и столбцов в строках не совпадает в файле tempGrab/stats_' . $key . '.csv';
         }
         //Если файл не пустой
         if ($csvObj->countRows() > 0) {
             $arrForSHA1 = array(0, 0);
             $mainKeyRow = $csvObj->getRow(0);
             //Добавляем информацию для заданного ключа
             $mainKey['keyword'] = $mainKeyRow[1] != "" ? $mainKeyRow[1] : "";
             $mainKey['AMS'] = $mainKeyRow[3] != "" ? $mainKeyRow[3] : 0;
             $mainKey['suggested_bid'] = $mainKeyRow[5] != "" ? $mainKeyRow[5] : 0;
             $redis->delete("key:{$country->cntr_code}:{$key}");
             $redis->hMset("key:{$country->cntr_code}:{$key}", $mainKey);
             $arrForSHA1[0] = sha1(serialize($mainKey));
             //Добавляем keywords для заданного ключа
             $new_words = array();
             $keywordRow = array();
             for ($i = 1; $i < $csvObj->countRows(); $i++) {
                 $childKeyRow = $csvObj->getRow($i);
                 $keywordRow[$i]['keyword'] = $childKeyRow[1] != "" ? $childKeyRow[1] : "";
                 $keywordRow[$i]['AMS'] = $childKeyRow[3] != "" ? $childKeyRow[3] : 0;
                 $keywordRow[$i]['suggested_bid'] = $childKeyRow[5] != "" ? $childKeyRow[5] : 0;
                 //Получаем новые слова для словоря
                 $new_words = array_merge($new_words, explode(" ", $keywordRow[$i]['keyword']));
             }
             //Если есть новые слова для словаря
             if (count($new_words)) {
                 //Удаляем дубликаты
                 $new_words = array_unique($new_words);
                 //Удаляем стоп-слова
                 $query = 'SELECT "stop_words" FROM countries ' . 'WHERE "ID"=' . $country->ID;
                 $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
                 $st_words_str = pg_fetch_object($result)->stop_words;
                 pg_free_result($result);
                 if ($st_words_str) {
                     $st_words_arr = explode("\n", $st_words_str);
                     $new_words = array_diff($new_words, $st_words_arr);
                 }
                 //Если остались слова - продолжаем
                 if (count($new_words) > 0) {
                     //Удаляем однобуквенные слова и слова с запрещенными знаками
                     foreach ($new_words as $w_key => $value) {
                         if (!preg_match('|^[a-z]{2}[a-z0-9_-]*$|i', $value)) {
                             unset($new_words[$w_key]);
                             continue;
                         }
                     }
                     //Добавляем новые слова в словарь со статусом "В ожидании" (keys_status = 1)
                     if (count($new_words) > 0) {
                         $ins_arr = array();
                         foreach ($new_words as $word) {
                             if ($redis->exists("key:{$country->cntr_code}:{$word}") || $redis->sIsMember("keys_status:{$country->cntr_code}:2", $word)) {
                                 continue;
                             }
                             $redis->sAdd("keys_status:{$country->cntr_code}:1", strtolower(trim($word)));
                         }
                     }
                 }
             }
             //!!!! ПРОВЕРИТЬ КЛЮЧ В ХЭШ-ТАБЛИЦЕ !!!!!!!!!!!!!!!!!!!!
             //Добавляем keywords для ключа
             if (count($keywordRow) > 0) {
                 $arrForSHA1[1] = sha1(serialize($keywordRow));
                 $i = 1;
                 $redis->delete($redis->keys("keywords:{$country->cntr_code}:{$key}:*"));
                 foreach ($keywordRow as $row) {
                     $redis->hMset("keywords:{$country->cntr_code}:{$key}:{$i}", $row);
                     $i++;
                 }
             }
             $redis->delete("keys_hash:{$country->cntr_code}:{$key}");
             $redis->rPush("keys_hash:{$country->cntr_code}:{$key}", $arrForSHA1[0], $arrForSHA1[1]);
         } else {
             //Файл был пустой - разблокируем ключ (keys_status = 1)
             $redis->sAdd("keys_status:{$country->cntr_code}:1", $key);
             //Увеличиваем количество ошибок для аккаунта
             $query = 'UPDATE accounts SET cnt_fail=cnt_fail+1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
             pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
         }
         //Удаляем скачанный файл
         if (is_file($this->baseDir . 'tempGrab/stats_' . $key . '.csv')) {
             unlink($this->baseDir . 'tempGrab/stats_' . $key . '.csv');
         }
     } else {
         //Файл не скачался - разблокируем ключ(keys_status = 1)
         $redis->sAdd("keys_status:{$country->cntr_code}:1", $key);
         //Увеличиваем количество ошибок для аккаунта
         $query = 'UPDATE accounts SET cnt_fail=cnt_fail+1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
         pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     }
     sleep(1);
     pg_close($dbconn);
     echo "STOP Run csvParser\n";
 }
 function post($file)
 {
     $file = $file['file'];
     if (empty($file)) {
         $this->log['error'][] = 'No file uploaded, aborting.';
         //$messages             = $this->print_messages();
         //echo $messages[0];
         //echo $messages[1];
         return false;
     }
     $output = '<ol>';
     // Load the CSV processor
     require_once CTRL_LI_PLUGIN_DIR . 'inc/CSVParser.php';
     $time_start = microtime(true);
     $csv = new File_CSV_DataSource();
     if (!$csv->load($file)) {
         $this->log['error'][] = 'Failed to load file, aborting.';
         $messages = $this->print_messages();
         echo $messages[0];
         echo $messages[1];
         return false;
     }
     // pad shorter rows with empty values
     $csv->symmetrize();
     // WordPress sets the correct timezone for date functions somewhere
     // in the bowels of wp_insert_post(). We need strtotime() to return
     // correct time before the call to wp_insert_post().
     $tz = get_option('timezone_string');
     if ($tz && function_exists('date_default_timezone_set')) {
         date_default_timezone_set($tz);
     }
     $skipped = 0;
     $imported = 0;
     $comments = 0;
     $languagecheck = false;
     $languageInCsv = false;
     foreach ($csv->connect() as $csv_data) {
         // check if selected language is present in file, otherwise abort.
         if (false == $languagecheck) {
             $languageInCsv = $this->checkForLanguage($csv_data);
             if ($languageInCsv === false) {
                 break;
             }
             $languagecheck = true;
         }
         if ($output .= $this->create_post($csv_data)) {
             $imported++;
         } else {
             $skipped++;
         }
     }
     if (file_exists($file)) {
         @unlink($file);
     }
     $exec_time = microtime(true) - $time_start;
     if ($skipped) {
         $this->log['notice'][] = "<b>Skipped {$skipped} posts (most likely due to empty title, body and excerpt).</b>";
     }
     $this->log['notice'][] = sprintf("<b>Imported {$imported} posts and {$comments} comments in %.2f seconds.</b>", $exec_time);
     $output .= '</ol>';
     if ($languageInCsv === false) {
         $output = sprintf("<p>The language {$this->language} is not present in current CSV file.</p>");
     }
     $output .= '<p>' . $this->log['notice'][0] . '</p>';
     echo $output;
     return true;
 }
Example #11
0
    /**
     * Content for each step of the CSV import stages
     * Via switch statement
     */
    function step_content($steps)
    {
        global $eventon_csv;
        $evo_opt = get_option('evcal_options_evcal_1');
        $event_type_count = evo_get_ett_count($evo_opt);
        $cmd_count = evo_calculate_cmd_count($evo_opt);
        switch ($steps) {
            // Step nuber 1
            case 'uno':
                ?>
					
			<h2><?php 
                _e('Step 1: Upload CSV file', 'eventon');
                ?>
</h2>
			<?php 
                $this->form();
                $this->print_guidelines();
                break;
                // Step number 2
            // Step number 2
            case 'dos':
                if ($this->csv_verify_nonce_post('eventon_csvi_noncename')) {
                    ?>
				<h2><?php 
                    _e('Step 2: Verify uploaded events', 'eventon');
                    ?>
</h2>
				<p><?php 
                    _e('In this step you can see below the events we found from your uploaded CSV file. Please making sure the data is present correctly. You can also click on each event to deselect them from being imported to EventON - in the next step.', 'eventon');
                    ?>
</p>
				<?php 
                    // verified nonce
                    if (empty($_FILES['csv_import']['tmp_name'])) {
                        $this->log['error'][] = 'No file uploaded, Please try again!.';
                        $this->print_messages();
                        $this->step_content('uno');
                        return;
                    }
                    // get csv helper file
                    require_once $eventon_csv->plugin_path . '/assets/DataSource.php';
                    $time_start = microtime(true);
                    $csv = new File_CSV_DataSource();
                    $file = $_FILES['csv_import']['tmp_name'];
                    $this->stripBOM($file);
                    if (!$csv->load($file)) {
                        $this->log['error'][] = 'Failed to load file, Please try again!.';
                        $this->print_messages();
                        $this->step_content('uno');
                        return;
                    }
                    // pad shorter rows with empty values
                    $csv->symmetrize();
                    // correct wordpress time zone for event posts
                    $tz = get_option('timezone_string');
                    if ($tz && function_exists('date_default_timezone_set')) {
                        date_default_timezone_set($tz);
                    }
                    ?>
					<form class="" action='<?php 
                    echo admin_url();
                    ?>
admin.php?page=eventon&tab=evcal_csv&steps=thres' method="post" enctype="multipart/form-data">
					<?php 
                    settings_fields('eventon_csvi_field_grp');
                    wp_nonce_field($eventon_csv->plugin_path, 'eventon_csvi_dos_noncename');
                    echo "<table id='eventon_csv_data_list' class='wp-list-table widefat'>\r\n\t\t\t\t\t\t\t<thead>\r\n\t\t\t\t\t\t\t<th></th>\r\n\t\t\t\t\t\t\t<th title='Publish status for event'>Status</th>\r\n\t\t\t\t\t\t\t<th>Event Name</th>\r\n\t\t\t\t\t\t\t<th>Description</th>\r\n\t\t\t\t\t\t\t<th>Start Date & Time</th>\r\n\t\t\t\t\t\t\t<th>End Date & Time</th>\r\n\t\t\t\t\t\t\t<th>Location</th>\r\n\t\t\t\t\t\t\t<th>Organizer</th>\r\n\t\t\t\t\t\t\t</thead>";
                    // for each record
                    $x = 0;
                    foreach ($csv->connect() as $csv_data) {
                        $ev_desc_class = !empty($csv_data['event_description']) ? 'inner_check' : 'inner_check_no';
                        $ev_location_class = !empty($csv_data['event_location']) ? 'inner_check' : 'inner_check_no';
                        $ev_orga_class = !empty($csv_data['event_organizer']) ? 'inner_check' : 'inner_check_no';
                        // event date validation
                        if (!empty($csv_data['event_start_date'])) {
                            if (preg_match('/^(\\d{1,2})\\/(\\d{1,2})\\/((?:\\d{2}){1,2})$/', $csv_data['event_start_date'])) {
                                $event_start_date = $event_start_date_val = $csv_data['event_start_date'];
                            } else {
                                $event_start_date = "<p class='inner_check_no eventon_csv_icons'></p>";
                                $event_start_date_val = null;
                            }
                        } else {
                            $event_start_date = "<p class='inner_check_no eventon_csv_icons'></p>";
                            $event_start_date_val = null;
                        }
                        // event start time validation
                        if (!empty($csv_data['event_start_time'])) {
                            if (preg_match('/(1[0-2]|0?[0-9]):[0-5]?[0-9]?:(AM|PM)/', $csv_data['event_start_time'])) {
                                $event_start_time = $event_start_time_val = $csv_data['event_start_time'];
                            } else {
                                $event_start_time = "<p class='inner_check_no eventon_csv_icons'></p>";
                                $event_start_time_val = null;
                            }
                        } else {
                            $event_start_time = "<p class='inner_check_no eventon_csv_icons'></p>";
                            $event_start_time_val = null;
                        }
                        // end time
                        if (!empty($csv_data['event_end_time'])) {
                            if (preg_match('/(1[0-2]|0?[0-9]):[0-5]?[0-9]?:(AM|PM)/', $csv_data['event_end_time'])) {
                                $event_end_time = $event_end_time_val = $csv_data['event_end_time'];
                            } else {
                                $event_end_time = "<p class='inner_check_no eventon_csv_icons'></p>";
                                $event_end_time_val = $event_start_time_val;
                            }
                        } else {
                            $event_end_time = "<p class='inner_check_no eventon_csv_icons'></p>";
                            $event_end_time_val = $event_start_time_val;
                        }
                        // event end date
                        if (!empty($csv_data['event_end_date'])) {
                            if (preg_match('/^(\\d{1,2})\\/(\\d{1,2})\\/((?:\\d{2}){1,2})$/', $csv_data['event_end_date'])) {
                                $event_end_date = $event_end_date_val = $csv_data['event_end_date'];
                            } else {
                                $event_end_date = "<p class='inner_check_no eventon_csv_icons'></p>";
                                $event_end_date_val = $event_start_date_val;
                            }
                        } else {
                            // no end date present
                            $event_end_date = "<p class='inner_check_no eventon_csv_icons'></p>";
                            $event_end_date_val = $event_start_date_val;
                        }
                        // description
                        $event_description = !empty($csv_data['event_description']) ? convert_chars(addslashes($csv_data['event_description'])) : null;
                        // /print_r($csv_data);
                        $updated_csv_data = $csv_data;
                        $updated_csv_data['event_start_date'] = $event_start_date_val;
                        $updated_csv_data['event_start_time'] = $event_start_time_val;
                        $updated_csv_data['event_end_date'] = $event_end_date_val;
                        $updated_csv_data['event_end_time'] = $event_end_time_val;
                        $updated_csv_data['event_description'] = $event_description;
                        ?>
	
						<tr class='csv_list_row'>
							<?php 
                        echo $this->_html_get_hidden_input_fields($updated_csv_data, $x, $event_type_count, $cmd_count);
                        ?>
							<td class='col1'><p class='outter_check eventon_csv_icons'></p></td>
							<td><i><?php 
                        echo $csv_data['publish_status'];
                        ?>
</i></td>
							<td><?php 
                        echo $csv_data['event_name'];
                        ?>
</td>
							<td><p class='<?php 
                        echo $ev_desc_class;
                        ?>
 eventon_csv_icons'></p></td>
							<td><?php 
                        echo $event_start_date . '<br/>' . $event_start_time;
                        ?>
</td>
							<td><?php 
                        echo $event_end_date . '<br/>' . $event_end_time;
                        ?>
</td>
							<td title='<?php 
                        echo $csv_data['event_location'];
                        ?>
'><p class='<?php 
                        echo $ev_location_class;
                        ?>
 eventon_csv_icons'></p></td>
							<td title='<?php 
                        echo $csv_data['event_organizer'];
                        ?>
'><p class='<?php 
                        echo $ev_orga_class;
                        ?>
 eventon_csv_icons'></p></td>
						</tr>
						
						<?php 
                        $x++;
                    }
                    echo "</table><p class='submit'><input type='submit' class='evo_admin_btn btn_tritiary' name='submit' value='Next: Import selected events' /></p></form>";
                    if (file_exists($file)) {
                        @unlink($file);
                    }
                    $exec_time = microtime(true) - $time_start;
                    $this->log['notice'][] = sprintf("<b>Found {$x} events in %.2f seconds from the csv file.</b>", $exec_time);
                    $this->print_messages();
                }
                break;
                // Step three
            // Step three
            case 'thres':
                if ($this->csv_verify_nonce_post('eventon_csvi_dos_noncename')) {
                    if (isset($_POST['csvi'])) {
                        $skipped = 0;
                        $imported = 0;
                        $event_names_imp = array();
                        $event_names_skip = array();
                        $time_start = microtime(true);
                        //$date_format = eventon_get_timeNdate_format();
                        // Run through each event row and add them
                        foreach ($_POST['csvi'] as $event) {
                            // check is the event is selected to be imported
                            if ($event['status'] == 'yes') {
                                if ($post_id = $this->create_post($event)) {
                                    $imported++;
                                    $event_names_imp[] = $event['event_name'];
                                    /*	Event Start and end time and dates	*/
                                    if (isset($event['event_start_date']) && isset($event['event_end_date']) && isset($event['event_start_time']) && isset($event['event_end_time'])) {
                                        $start_time = explode(":", $event['event_start_time']);
                                        $end_time = explode(":", $event['event_end_time']);
                                        $date_array = array('evcal_start_date' => $event['event_start_date'], 'evcal_start_time_hour' => $start_time[0], 'evcal_start_time_min' => $start_time[1], 'evcal_st_ampm' => $start_time[2], 'evcal_end_date' => $event['event_end_date'], 'evcal_end_time_hour' => $end_time[0], 'evcal_end_time_min' => $end_time[1], 'evcal_et_ampm' => $end_time[2], 'evcal_allday' => !empty($event['all_day']) ? $event['all_day'] : 'no');
                                        $proper_time = eventon_get_unix_time($date_array, 'm/d/Y');
                                        // save required start time variables
                                        $this->create_custom_fields($post_id, 'evcal_srow', $proper_time['unix_start']);
                                        $this->create_custom_fields($post_id, 'evcal_erow', $proper_time['unix_end']);
                                        //$this->create_custom_fields($post_id, 'data', $date_format[1]);
                                    }
                                    // rest of the custom meta fields
                                    $this->save_custom_meta_fields($event, $post_id, $event_type_count, $cmd_count);
                                } else {
                                    $skipped++;
                                    $event_names_skip[] = $event['event_name'];
                                }
                            }
                        }
                        // create notices
                        if ($skipped > 0) {
                            $this->log['notice'][] = "<b>Skipped {$skipped} events (most likely due to empty title or description).</b>";
                        }
                        $exec_time = microtime(true) - $time_start;
                        $this->log['notice'][] = sprintf("<b>Imported {$imported} events in %.2f seconds.</b>", $exec_time);
                        $this->print_messages();
                        // =====
                        // Show the report on import process
                        _e('<h2>Done!</h2>', 'eventon');
                        echo "<p>Please go to <a href='" . admin_url() . "edit.php?post_type=ajde_events'>All Events</a> to further customize the events you just imported.</p>";
                        // Success report
                        if (count($event_names_imp) > 0) {
                            echo "<table id='eventon_csv_data_list' class='wp-list-table widefat'>\r\n\t\t\t\t\t\t\t\t\t<thead>\r\n\t\t\t\t\t\t\t\t\t<th>Event Name</th>\r\n\t\t\t\t\t\t\t\t\t<th>Status</th>\r\n\t\t\t\t\t\t\t\t\t</thead>";
                            foreach ($event_names_imp as $event_name) {
                                echo "<tr><td>{$event_name}</td><td>Imported</td></tr>";
                            }
                            // didnt import
                            if (count($event_names_skip) > 0) {
                                foreach ($event_names_skip as $event_name) {
                                    echo "<tr><td>{$event_name}</td><td>Not Imported</td></tr>";
                                }
                            }
                            echo "</table>";
                        }
                    }
                }
                break;
                // default step
            // default step
            default:
                ?>
				<h3><?php 
                _e('Import Events from a CSV file', 'eventon');
                ?>
</h3>
				<p>CSV Importer addon for EventON will allow you to export events from another event plugin or another event calendar, into CSV file format, and import those events into EventON Calendar.</p>
				
				<hr/>
				
				<a href='<?php 
                echo admin_url();
                ?>
admin.php?page=eventon&tab=evcal_csv&steps=uno' class='csv_import_get_start_btn evo_admin_btn btn_prime'><?php 
                _e('Get Started Now', 'eventon');
                ?>
</a>		
						
				<?php 
                $this->print_guidelines();
                break;
        }
        // end switch statement
    }
Example #12
0
<?php

require_once 'DataSource.php';
$csv = new File_CSV_DataSource('tests/data/products.csv');
$html .= '<table>';
$html .= '<tr>';
foreach ($csv->getHeaders() as $header) {
    $html .= '<th>' . $header . '</th>';
}
$html .= '</tr>';
foreach ($csv->connect() as $row) {
    $html .= '<tr>';
    foreach ($row as $key => $value) {
        $html .= '<td>' . $value . '</td>';
    }
    $html .= '</tr>';
}
$html .= '</table>';
echo $html;
Example #13
0
 /**
  * CSV Importer
  * Based on the csv-importer plugin. Thanks for teaching me something new.
  *
  * @see http://wordpress.org/extend/plugins/csv-importer/
  * @since 0.1
  * @version 1.0
  */
 public function import_csv()
 {
     // We need a file. or else...
     if (!isset($_FILES['mycred_csv']) || empty($_FILES['mycred_csv']['tmp_name'])) {
         $this->errors = __('No file selected. Please select your CSV file and try again.', 'mycred');
         return;
     }
     // Grab CSV Data Fetcher
     require_once myCRED_ADDONS_DIR . 'import/includes/File-CSV-DataSource.php';
     // Prep
     $time_start = microtime(true);
     $csv = new File_CSV_DataSource();
     $file = $_FILES['mycred_csv']['tmp_name'];
     $this->strip_BOM($file);
     // Failed to load file
     if (!$csv->load($file)) {
         $this->errors = __('Failed to load file.', 'mycred');
         return;
     }
     // Equality for all
     $csv->symmetrize();
     // Update
     $this->update_users($csv->connect());
     // Unlink
     if (file_exists($file)) {
         @unlink($file);
     }
     // Time
     $exec_time = microtime(true) - $time_start;
     // Throw an error if there were no imports just skipps
     if ($this->imports == 0 && $this->skipped != 0) {
         $this->errors = sprintf(__('Zero rows imported! Skipped %d entries. Import completed in %.2f seconds.', 'mycred'), $this->skipped, $exec_time);
         return;
     } elseif ($this->imports == 0 && $this->skipped == 0) {
         $this->errors = __('No valid records found in file. Make sure you have selected the correct way to identify users in the mycred_user column!', 'mycred');
         return;
     }
     // The joy of success
     $this->import_ok = sprintf(__('Import successfully completed. A total of %d users were effected and %d entires were skipped. Import completed in %.2f seconds.', 'mycred'), $this->imports, $this->skipped, $exec_time);
     // Clean Up
     unset($_FILES);
     unset($csv);
     // Close accordion
     unset($_POST);
 }
 /**
  * Handle POST submission
  *
  * @param array $options
  * @return void
  */
 function post($options)
 {
     if (empty($_FILES['csv_import']['tmp_name'])) {
         $this->log['error'][] = __('No file uploaded, aborting.', 'csv-importer-improved');
         $this->print_messages();
         return;
     }
     if (!current_user_can('publish_pages') || !current_user_can('publish_posts')) {
         $this->log['error'][] = __('You don\'t have the permissions to publish posts and pages. Please contact the blog\'s administrator.', 'csv-importer-improved');
         $this->print_messages();
         return;
     }
     require_once 'File_CSV_DataSource/DataSource.php';
     $time_start = microtime(true);
     $csv = new File_CSV_DataSource();
     $file = $_FILES['csv_import']['tmp_name'];
     $this->stripBOM($file);
     if (!$csv->load($file)) {
         $this->log['error'][] = __('Failed to load file, aborting.', 'csv-importer-improved');
         $this->print_messages();
         return;
     }
     // pad shorter rows with empty values
     $csv->symmetrize();
     // WordPress sets the correct timezone for date functions somewhere
     // in the bowels of wp_insert_post(). We need strtotime() to return
     // correct time before the call to wp_insert_post().
     $tz = get_option('timezone_string');
     if ($tz && function_exists('date_default_timezone_set')) {
         date_default_timezone_set($tz);
     }
     $skipped = 0;
     $imported = 0;
     $comments = 0;
     foreach ($csv->connect() as $csv_data) {
         if ($post_id = $this->create_or_update_post($csv_data, $options)) {
             $imported++;
             $comments += $this->add_comments($post_id, $csv_data);
             $this->create_custom_fields($post_id, $csv_data);
         } else {
             $skipped++;
         }
     }
     if (file_exists($file)) {
         @unlink($file);
     }
     $exec_time = microtime(true) - $time_start;
     if ($skipped) {
         $this->log['notice'][] = sprintf('<strong>' . __('Skipped %d posts (most likely due to empty title, body and excerpt).', 'csv-importer-improved') . '</strong>', $skipped);
     }
     $this->log['notice'][] = sprintf('<strong>' . __('Imported %d posts and %d comments in %.2f seconds.', 'csv-importer-improved') . '</strong>', $imported, $comments, $exec_time);
     $this->print_messages();
 }