llms.abstract.exportable.admin.table.php 7.05 KB
Newer Older
cyrille's avatar
cyrille committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
<?php
/**
 * Admin Table Export Functions
 *
 * @package LifterLMS/Abstracts/Classes
 *
 * @since 3.28.0
 * @version 4.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * Exportable admin table abstract class
 *
 * @since 3.28.0
 * @since 3.30.3 Explicitly define undefined properties.
 * @since 3.37.15 Ensure filenames of generated export files are for supported filetypes.
 * @since 4.0.0 Removed previously deprecated method `LLMS_Admin_Table::queue_export()`.
 */
abstract class LLMS_Abstract_Exportable_Admin_Table {

	/**
	 * The current page.
	 *
	 * @var int
	 */
	protected $current_page;

	/**
	 * Unique ID for the table
	 *
	 * @var string
	 */
	protected $id;

	/**
	 * Is the Table Exportable?
	 *
	 * @var boolean
	 */
	protected $is_exportable = true;

	/**
	 * Generate an export file for the current table.
	 *
	 * @since 3.28.0
	 * @since 3.28.1 Unknown.
	 * @since 3.37.15 "Sanitize" submitted filename.
	 *
	 * @param array  $args     Arguments to pass get_results().
	 * @param string $filename Filename of the existing file, if omitted creates a new file, if passed, will continue adding to existing file.
	 * @param string $type     Export file type for forward compatibility. Currently only accepts 'csv'.
	 * @return WP_Error|array
	 */
	public function generate_export_file( $args = array(), $filename = null, $type = 'csv' ) {

		// We only support CSVs and don't allow fakers.
		if ( ! empty( $filename ) && pathinfo( $filename, PATHINFO_EXTENSION ) !== $type ) {
			return false;
		}

		// Always force page 1 regardless of what is requested. Pagination is handled below.
		$args['page'] = 1;

		/**
		 * Customize the number of records per page when generating an export file.
		 *
		 * @since 3.28.0
		 *
		 * @param int $per_page Number of records per page.
		 */
		$args['per_page'] = apply_filters( 'llms_table_generate_export_file_per_page_boost', 250 );

		$filename    = $filename ? $filename : $this->get_export_file_name() . '.' . $type;
		$file_path   = LLMS_TMP_DIR . $filename;
		$option_name = 'llms_gen_export_' . basename( $filename, '.' . $type );
		$args        = get_option( $option_name, $args );

		$handle = @fopen( $file_path, 'a+' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Yea but we handle the error alright I think.
		if ( ! $handle ) {
			return new WP_Error( 'file_error', __( 'Unable to generate export file, could not open file for writing.', 'lifterlms' ) );
		}

		/**
		 * Customize the delimiter used when generating CSV export files.
		 *
		 * @since 3.28.0
		 *
		 * @param int                                  $delim Delimiter.
		 * @param LLMS_Abstract_Exportable_Admin_Table $table Instance of the table.
		 * @param array                                $args  Array of arguments.
		 */
		$delim = apply_filters( 'llms_table_generate_export_file_delimiter', ',', $this, $args );

		foreach ( $this->get_export( $args ) as $row ) {
			fputcsv( $handle, $row, $delim );
		}

		if ( ! $this->is_last_page() ) {

			$args['page'] = $this->get_current_page() + 1;
			update_option( $option_name, $args );
			$progress = round( ( $this->get_current_page() / $this->get_max_pages() ) * 100, 2 );

		} else {

			delete_option( $option_name );
			$progress = 100;

		}

		return array(
			'filename' => $filename,
			'progress' => $progress,
			'url'      => $this->get_export_file_url( $file_path ),
		);

	}

	/**
	 * Gets data prepared for an export
	 *
	 * @since 3.15.0
	 * @since 3.15.1 Unknown.
	 *
	 * @param array $args Query arguments to be passed to get_results().
	 * @return array
	 */
	public function get_export( $args = array() ) {

		$this->get_results( $args );

		$export = array();
		if ( 1 === $this->current_page ) {
			$export[] = $this->get_export_header();
		}

		foreach ( $this->get_tbody_data() as $row ) {
			$row_data = array();
			foreach ( array_keys( $this->get_columns( 'export' ) ) as $row_key ) {
				$row_data[ $row_key ] = html_entity_decode( $this->get_export_data( $row_key, $row ) );
			}
			$export[] = $row_data;
		}

		return $export;

	}

	/**
	 * Retrieve data for a cell in an export file
	 * Should be overridden in extending classes
	 *
	 * @since 3.15.0
	 *
	 * @param string $key  The column id / key.
	 * @param mixed  $data Object / array of data that the function can use to extract the data.
	 * @return mixed
	 */
	public function get_export_data( $key, $data ) {
		return trim( strip_tags( $this->get_data( $key, $data ) ) );
	}

	/**
	 * Retrieve the download URL to an export file
	 *
	 * @since 3.28.0
	 * @since 3.28.1 Unknown.
	 *
	 * @param string $file_path Full path to a download file.
	 * @return string
	 */
	protected function get_export_file_url( $file_path ) {
		return add_query_arg(
			array(
				'llms-dl-export' => basename( $file_path ),
			),
			admin_url( 'admin.php' )
		);
	}

	/**
	 * Retrieve the header row for generating an export file
	 *
	 * @since 3.15.0
	 * @since 3.17.3 Fixed SYLK warning generated when importing into Excel.
	 *
	 * @return array
	 */
	public function get_export_header() {

		$cols = wp_list_pluck( $this->get_columns( 'export' ), 'title' );

		/**
		 * If the first column is "ID" force it to lowercase
		 * to prevent Excel from attempting to interpret the .csv as SYLK
		 *
		 * @see https://github.com/gocodebox/lifterlms/issues/397
		 */
		foreach ( $cols as &$title ) {
			if ( 'id' === strtolower( $title ) ) {
				$title = strtolower( $title );
			}
			break;
		}

		/**
		 * Customize the export file header columns.
		 *
		 * The dynamic portion of this hook `$this->id` refers to the ID of the table.
		 *
		 * @since 3.15.0
		 *
		 * @param string[] $cols Array of file headers.
		 */
		return apply_filters( "llms_table_get_{$this->id}_export_header", $cols );

	}

	/**
	 * Get the file name for an export file
	 *
	 * @since 3.15.0
	 * @since 3.28.0 Unknown.
	 *
	 * @param array $args Optional arguments passed from table to csv processor.
	 * @return string
	 */
	public function get_export_file_name( $args = array() ) {

		$title = sprintf( '%1$s_export_%2$s_%3$s', sanitize_title( $this->get_export_title( $args ), 'llms-' . $this->id ), current_time( 'Y-m-d' ), wp_generate_password( 8, false, false ) );
		return apply_filters( 'llms_table_get_' . $this->id . '_export_file_name', $title );

	}

	/**
	 * Get a lock key unique to the table & user for locking the table during export generation
	 *
	 * @since 3.15.0
	 *
	 * @return string
	 */
	public function get_export_lock_key() {
		return sprintf( '%1$s:%2$d', $this->id, get_current_user_id() );
	}

	/**
	 * Allow customization of the title for export files
	 *
	 * @since 3.15.0
	 * @since 3.28.0 Unknown.
	 *
	 * @param array $args Optional arguments passed from table to csv processor.
	 * @return string
	 */
	public function get_export_title( $args = array() ) {
		return apply_filters( 'llms_table_get_' . $this->id . '_export_title', $this->get_title(), $args );
	}

	/**
	 * Determine if the table is currently locked due to export generation.
	 *
	 * @since 3.28.0
	 *
	 * @return bool
	 */
	public function is_export_locked() {
		return LLMS()->processors()->get( 'table_to_csv' )->is_table_locked( $this->get_export_lock_key() );
	}

}