| 1 |
<?php |
| 2 |
|
| 3 |
class Red_Csv_File extends Red_FileIO { |
| 4 |
public function export( array $items ) { |
| 5 |
$filename = 'redirection-'.date_i18n( get_option( 'date_format' ) ).'.csv'; |
| 6 |
|
| 7 |
header( 'Content-Type: text/csv' ); |
| 8 |
header( 'Cache-Control: no-cache, must-revalidate' ); |
| 9 |
header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' ); |
| 10 |
header( 'Content-Disposition: attachment; filename="'.$filename.'"' ); |
| 11 |
|
| 12 |
$stdout = fopen( 'php://output', 'w' ); |
| 13 |
|
| 14 |
fputcsv( $stdout, array( 'source', 'target', 'regex', 'type', 'code', 'match', 'hits', 'title' ) ); |
| 15 |
|
| 16 |
foreach ( $items as $line ) { |
| 17 |
fwrite( $stdout, $this->item_as_csv( $line ) ); |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
public function item_as_csv( $item ) { |
| 22 |
$csv = array( |
| 23 |
$item->get_url(), |
| 24 |
$item->get_action_data(), |
| 25 |
$item->is_regex() ? 1 : 0, |
| 26 |
$item->get_action_type(), |
| 27 |
$item->get_action_code(), |
| 28 |
$item->get_action_type(), |
| 29 |
$item->get_hits(), |
| 30 |
$item->get_title(), |
| 31 |
); |
| 32 |
|
| 33 |
$csv = array_map( array( $this, 'escape_csv' ), $csv ); |
| 34 |
return join( $csv, ',' ); |
| 35 |
} |
| 36 |
|
| 37 |
public function escape_csv( $item ) { |
| 38 |
return '"'.str_replace( '"', '""', $item ).'"'; |
| 39 |
} |
| 40 |
|
| 41 |
public function load( $group, $filename, $data ) { |
| 42 |
$count = 0; |
| 43 |
$file = fopen( $filename, 'r' ); |
| 44 |
|
| 45 |
if ( $file ) { |
| 46 |
while ( ( $csv = fgetcsv( $file, 1000, ',' ) ) ) { |
| 47 |
$item = $this->csv_as_item( $csv, $group ); |
| 48 |
|
| 49 |
if ( $item ) { |
| 50 |
Red_Item::create( $item ); |
| 51 |
$count++; |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
return $count; |
| 57 |
} |
| 58 |
|
| 59 |
public function csv_as_item( $csv, $group ) { |
| 60 |
if ( $csv[0] !== 'source' && $csv[1] !== 'target' && count( $csv ) > 1 ) { |
| 61 |
return array( |
| 62 |
'source' => trim( $csv[0] ), |
| 63 |
'target' => trim( $csv[1] ), |
| 64 |
'regex' => isset( $csv[2] ) ? $this->parse_regex( $csv[2] ) : $this->is_regex( $csv[0] ), |
| 65 |
'group_id' => $group, |
| 66 |
'match' => 'url', |
| 67 |
'red_action' => 'url', |
| 68 |
'action_code' => isset( $csv[3] ) ? intval( $csv[3], 10 ) : 301, |
| 69 |
); |
| 70 |
} |
| 71 |
|
| 72 |
return false; |
| 73 |
} |
| 74 |
|
| 75 |
private function parse_regex( $value ) { |
| 76 |
return intval( $value, 10 ) === 1 ? true : false; |
| 77 |
} |
| 78 |
|
| 79 |
private function is_regex( $url ) { |
| 80 |
$regex = '()[]$^*'; |
| 81 |
|
| 82 |
if ( strpbrk( $url, $regex ) === false ) { |
| 83 |
return false; |
| 84 |
} |
| 85 |
|
| 86 |
return true; |
| 87 |
} |
| 88 |
} |
| 89 |
|