PluginProbe
s2Member – Excellent for All Kinds of Memberships, Content Restriction Paywalls & Member Access Subscriptions / trunk
s2Member – Excellent for All Kinds of Memberships, Content Restriction Paywalls & Member Access Subscriptions vtrunk
260909 260829 260814 260805 110710 110731 110812 110815 110912 110913 110915 110926 110927 111002 111003 111011 111017 111029 111105 111206 111216 111220 120213 120219 120301 All 187 releases
s2member / src / includes / classes / files.inc.php

files.inc.php in s2Member – Excellent for All Kinds of Memberships, Content Restriction Paywalls & Member Access Subscriptions trunk, at src/includes/classes/files.inc.php

403 lines 21.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 // @codingStandardsIgnoreFile
3 /**
4 * File Download routines for s2Member.
5 *
6 * Copyright: © 2009-2011
7 * {@link http://websharks-inc.com/ WebSharks, Inc.}
8 * (coded in the USA)
9 *
10 * Released under the terms of the GNU General Public License.
11 * You should have received a copy of the GNU General Public License,
12 * along with this software. In the main directory, see: /licensing/
13 * If not, see: {@link http://www.gnu.org/licenses/}.
14 *
15 * @package s2Member\Files
16 * @since 3.5
17 */
18 if(!defined('WPINC')) // MUST have WordPress.
19 exit('Do not access this file directly.');
20
21 if(!class_exists('c_ws_plugin__s2member_files'))
22 {
23 /**
24 * File Download routines for s2Member.
25 *
26 * @package s2Member\Files
27 * @since 3.5
28 */
29 class c_ws_plugin__s2member_files
30 {
31 /**
32 * Handles Download Access permissions.
33 *
34 * @package s2Member\Files
35 * @since 110524RC
36 *
37 * @attaches-to ``add_action('init');``
38 * @also-called-by API Function {@link s2Member\API_Functions\s2member_file_download_url()}, w/ ``$create_file_download_url`` param.
39 *
40 * @param array $create_file_download_url Optional. If this function is called directly, we can pass arguments through this array.
41 * Possible array elements: `file_download` *(required)*, `file_download_key`, `file_stream`, `file_inline`, `file_storage`, `file_remote`, `file_ssl`, `file_rewrite`, `file_rewrite_base`, `skip_confirmation`, `url_to_storage_source`, `count_against_user`, `check_user`.
42 *
43 * @return null|string If called directly with ``$create_file_download_url``, returns a string with the URL, based on configuration.
44 * Else, this function may exit script execution after serving a File Download.
45 */
46 public static function check_file_download_access($create_file_download_url = NULL)
47 {
48 if(is_array($create_file_download_url) || !empty($_GET['s2member_file_download']))
49 return c_ws_plugin__s2member_files_in::check_file_download_access($create_file_download_url);
50 return NULL; // Default return value.
51 }
52
53 /**
54 * Generates a File Download URL for access to a file protected by s2Member.
55 *
56 * @package s2Member\Files
57 * @since 110926
58 *
59 * @param array $config Required. This is an array of configuration options associated with permissions being checked against the current User/Member; and also the actual URL generated by this routine.
60 * Possible ``$config`` array elements: `file_download` *(required)*, `file_download_key`, `file_stream`, `file_inline`, `file_storage`, `file_remote`, `file_ssl`, `file_rewrite`, `file_rewrite_base`, `skip_confirmation`, `url_to_storage_source`, `count_against_user`, `check_user`.
61 * @param bool $get_streamer_array Optional. Defaults to `false`. If `true`, this function will return an array with the following elements: `streamer`, `file`, `url`. For further details, please review this section in your Dashboard: `s2Member → Download Options → JW Player & RTMP Protocol Examples`.
62 *
63 * @return string A File Download URL string on success; or an array on success, with elements `streamer`, `file`, `url` when/if ``$get_streamer_array`` is true; else false on any type of failure.
64 *
65 * @see s2Member\API_Functions\s2member_file_download_url()
66 */
67 public static function create_file_download_url($config = NULL, $get_streamer_array = FALSE)
68 {
69 return c_ws_plugin__s2member_files_in::create_file_download_url($config, $get_streamer_array);
70 }
71
72 /**
73 * Auto-configures an Amazon S3 Bucket's ACLs.
74 *
75 * @package s2Member\Files
76 * @since 110926
77 *
78 * @return bool|array True on success, else array on failure.
79 * Failure array will contain a failure `code`, and a failure `message`.
80 */
81 public static function amazon_s3_auto_configure_acls()
82 {
83 return c_ws_plugin__s2member_files_in::amazon_s3_auto_configure_acls();
84 }
85
86 /**
87 * Auto-configures Amazon CloudFront distros.
88 *
89 * @package s2Member\Files
90 * @since 130209
91 *
92 * @return bool|array True on success, else array on failure.
93 * Failure array will contain a failure `code`, and a failure `message`.
94 */
95 public static function amazon_cf_auto_configure_distros()
96 {
97 return c_ws_plugin__s2member_files_in::amazon_cf_auto_configure_distros();
98 }
99
100 /**
101 * Determines the max period (in days), for Download Access.
102 *
103 * @package s2Member\Files
104 * @since 3.5
105 *
106 * @return int Number of days, where 0 means no access to files is allowed.
107 * Will not return a value > `365`, because this routine also controls the age of download logs to archives.
108 *
109 * @deprecated Deprecated in v111029. This function is no longer used by s2Member.
110 */
111 public static function max_download_period(/* No longer used by s2Member. */)
112 {
113 do_action('ws_plugin__s2member_before_max_download_period', get_defined_vars());
114
115 for($n = 0, $max = 0; $n <= $GLOBALS['WS_PLUGIN__']['s2member']['c']['levels']; $n++)
116 if(!empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed']))
117 if(!empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed_days']))
118 if(($days = $GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed_days']))
119 $max = ($max < $days) ? $days : $max;
120
121 return apply_filters('ws_plugin__s2member_max_download_period', (($max > 365) ? 365 : $max), get_defined_vars());
122 }
123
124 /**
125 * Determines the minimum Level required for File Download Access.
126 *
127 * @package s2Member\Files
128 * @since 3.5
129 *
130 * @return bool|int False if no access is allowed, else Level number (int) 0+.
131 */
132 public static function min_level_4_downloads()
133 {
134 do_action('ws_plugin__s2member_before_min_level_4_downloads', get_defined_vars());
135
136 for($n = 0, $min = FALSE; $n <= $GLOBALS['WS_PLUGIN__']['s2member']['c']['levels']; $n++)
137 if(!empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed']))
138 if(!empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed_days']))
139 if(($min = $n) >= 0) break; // Break now.
140
141 return apply_filters('ws_plugin__s2member_min_level_4_downloads', ((is_int($min)) ? $min : FALSE), get_defined_vars());
142 }
143
144 /**
145 * Creates a File Download Key.
146 *
147 * Builds a hash of: ``date('Y-m-d') . c_ws_plugin__s2member_utils_ip::current() . $_SERVER['HTTP_USER_AGENT'] . $file``.
148 *
149 * @package s2Member\Files
150 * @since 3.5
151 *
152 * @param string $file Location of your protected file, relative to the `/s2member-files/` directory.
153 * In other words, just the name of the file *(i.e., `file.zip` )*.
154 * @param string $directive Optional. One of `ip-forever|universal|cache-compatible`.
155 * `ip-forever` = a Download Key that never expires, tied only to a specific file and IP address.
156 * `universal` and/or `cache-compatible` = a Download Key which never expires, and is NOT tied to any specific User. Use at your own risk.
157 *
158 * @return string A Download Key. MD5 hash, 32 characters, URL-safe.
159 */
160 public static function file_download_key($file = NULL, $directive = NULL)
161 {
162 foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v;
163 do_action('ws_plugin__s2member_before_file_download_key', get_defined_vars());
164 unset($__refs, $__v);
165
166 $file = ($file && is_string($file) && ($file = trim($file, '/'))) ? $file : '';
167
168 if($directive === 'ip-forever' && c_ws_plugin__s2member_no_cache::no_cache_constants(TRUE))
169 $salt = $file.c_ws_plugin__s2member_utils_ip::current();
170
171 else if($directive === 'universal' || $directive === 'cache-compatible' || $directive)
172 $salt = $file; // Just the file name. This IS cacheable.
173
174 else if(c_ws_plugin__s2member_no_cache::no_cache_constants(TRUE))
175 $salt = date('Y-m-d').c_ws_plugin__s2member_utils_ip::current().$_SERVER['HTTP_USER_AGENT'].$file;
176
177 $key = (!empty($salt)) ? md5(c_ws_plugin__s2member_utils_encryption::xencrypt($salt, FALSE, FALSE)) : '';
178
179 return apply_filters('ws_plugin__s2member_file_download_key', $key, get_defined_vars());
180 }
181
182 /**
183 * Download details on a per-User basis.
184 *
185 * @package s2Member\Files
186 * @since 3.5
187 *
188 * @param object $user Optional. A `WP_User` object. Defaults to the current User's object.
189 * @param string $not_counting_this_particular_file Optional. If you want to exclude a particular file,
190 * relative to the `/s2member-files/` directory, or relative to the root of your Amazon S3 Bucket *(when applicable)*.
191 * @param array $user_log Optional. Prevents another database connection *(i.e., the User's log does not need to be pulled again)*.
192 * @param array $user_arc Optional. Prevents another database connection *(i.e., the User's archive does not need to be pulled again)*.
193 *
194 * @return array An array with the following elements... File Downloads allowed for this User: (int)`allowed`, Download Period for this User in days: (int)`allowed_days`, Files downloaded by this User in the current Period: (int)`currently`, log of all Files downloaded in the current Period, with file names/dates: (array)`log`, archive of all Files downloaded in prior Periods, with file names/dates: (array)`archive`.
195 *
196 * @note Calculations returned by this function do NOT include File Downloads that were accessed with an Advanced File Download Key.
197 *
198 * @todo Make it possible for s2Member to keep a count of files downloaded with an Advanced Download Key.
199 */
200 public static function user_downloads($user = NULL, $not_counting_this_particular_file = NULL, $user_log = NULL, $user_arc = NULL)
201 {
202 foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v;
203 do_action('ws_plugin__s2member_before_user_downloads', get_defined_vars());
204 unset($__refs, $__v);
205
206 $allowed = $allowed_days = $currently = 0; // Initialize these to zero.
207 $log = $arc = array(); // Initialize these to a default empty array value.
208
209 if((is_object($user) || is_object($user = (is_user_logged_in()) ? wp_get_current_user() : FALSE)) && !empty($user->ID) && ($user_id = $user->ID))
210 {
211 for($n = 0; $n <= $GLOBALS['WS_PLUGIN__']['s2member']['c']['levels']; $n++)
212 {
213 if($user->has_cap('access_s2member_level'.$n) /* Do they have access? */)
214 {
215 if(!empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed']) && !empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed_days']))
216 {
217 $allowed = $GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed'];
218 $allowed_days = $GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$n.'_file_downloads_allowed_days'];
219 }
220 if($user->has_cap('s2member_level'.$n) /* We can stop now, if this is their Role. */)
221 break; // Break now.
222 }
223 }
224 $log = (is_array($user_log)) ? $user_log : ((is_array($log = get_user_option('s2member_file_download_access_log', $user_id)) && $log !== array(FALSE)) ? $log : array());
225 $arc = (is_array($user_arc)) ? $user_arc : ((is_array($arc = get_user_option('s2member_file_download_access_arc', $user_id)) && $arc !== array(FALSE)) ? $arc : array());
226
227 foreach(($user_file_download_access_log = $log) as $user_file_download_access_log_entry_key => $user_file_download_access_log_entry)
228 if(isset($user_file_download_access_log_entry['date']) && strtotime($user_file_download_access_log_entry['date']) >= strtotime('-'.$allowed_days.' days'))
229 if(isset($user_file_download_access_log_entry['file']) && $user_file_download_access_log_entry['file'] !== $not_counting_this_particular_file)
230 $currently = $currently + 1;
231 }
232 return apply_filters('ws_plugin__s2member_user_downloads', array('allowed' => $allowed, 'allowed_days' => $allowed_days, 'currently' => $currently, 'log' => $log, 'archive' => $arc), get_defined_vars());
233 }
234
235 /**
236 * Total downloads of a particular file; possibly by a particular User.
237 *
238 * @package s2Member\Files
239 * @since 111026
240 *
241 * @param string $file Required. Location of the file, relative to the `/s2member-files/` directory, or relative to the root of your Amazon S3 Bucket *(when applicable)*.
242 * @param string|int $user_id Optional. If specified, s2Member will return total downloads by a particular User/Member, instead of collectively *(i.e among all Users/Members)*.
243 * @param bool $check_archives_too Optional. Defaults to true. When true, s2Member checks its File Download Archive too, instead of ONLY looking at Files downloaded in the current Period. Period is based on your Basic Download Restrictions setting of allowed days across various Levels of Membership, for each respective User/Member. Or, if ``$user_id`` is specified, based solely on a specific User's `allowed_days`, configured in your Basic Download Restrictions, at the User's current Membership Level.
244 *
245 * @return int The total for this particular ``$file``, based on configuration of function arguments.
246 *
247 * @note Calculations returned by this function do NOT include File Downloads that were accessed with an Advanced File Download Key.
248 *
249 * @todo Make it possible for s2Member to keep a count of files downloaded with an Advanced Download Key.
250 */
251 public static function total_downloads_of($file = NULL, $user_id = NULL, $check_archives_too = TRUE)
252 {
253 global $wpdb; // Global database object reference.
254 /** @var $wpdb \wpdb Reference for IDEs. */
255
256 if($file && is_string($file) /* Was ``$file`` passed in properly? */)
257 {
258 if(is_array($results = $wpdb->get_results("SELECT `meta_key`, `meta_value` FROM `".$wpdb->usermeta."` WHERE ".((is_numeric($user_id)) ? "`user_id` = '".esc_sql($user_id)."' AND " : '')."(`meta_key` = '".$wpdb->prefix."s2member_file_download_access_log'".(($check_archives_too) ? " OR `meta_key` = '".$wpdb->prefix."s2member_file_download_access_arc'" : '').") AND `meta_value` REGEXP '.*\"file\";s:[0-9]+:\"".esc_sql($file)."\".*'")))
259 {
260 foreach($results as $r /* Go through the entire array of results found in the `REGEXP` database query above. */)
261 if(is_array($la_entries = c_ws_plugin__s2member_utils_arrays::maybe_unserialize($r->meta_value)) && !empty($la_entries)) //260808 Safely unserialize the file download log entries.
262
263 foreach($la_entries as $la_entry /* Go through all of the entries in each result ``$r``; collecting `counter` values. */)
264 if(!empty($la_entry['file']) && $la_entry['file'] === $file && (!empty($la_entry['counter']) || ($la_entry['counter'] = 1)))
265 {
266 $total = (!empty($total)) ? $total + (int)$la_entry['counter'] : (int)$la_entry['counter'];
267 break; // Break now. No need to continue looping; ``$file`` found in these entries.
268 }
269 }
270 }
271 return (!empty($total)) ? $total : 0; // Else return zero by default.
272 }
273
274 /**
275 * Total unique downloads of a particular file; possibly by a particular User.
276 *
277 * @package s2Member\Files
278 * @since 111026
279 *
280 * @param string $file Required. Location of the file, relative to the `/s2member-files/` directory, or relative to the root of your Amazon S3 Bucket *(when applicable)*.
281 * @param string|int $user_id Optional. If specified, s2Member will return total downloads by a particular User/Member, instead of collectively *(i.e among all Users/Members)*.
282 * @param bool $check_archives_too Optional. Defaults to true. When true, s2Member checks its File Download Archive too, instead of ONLY looking at Files downloaded in the current Period. Period is based on your Basic Download Restrictions setting of allowed days across various Levels of Membership, for each respective User/Member. Or, if ``$user_id`` is specified, based solely on a specific User's `allowed_days`, configured in your Basic Download Restrictions, at the User's current Membership Level.
283 *
284 * @return int The total for this particular ``$file``, based on configuration of function arguments.
285 *
286 * @note Calculations returned by this function do NOT include File Downloads that were accessed with an Advanced File Download Key.
287 *
288 * @todo Make it possible for s2Member to keep a count of files downloaded with an Advanced Download Key.
289 */
290 public static function total_unique_downloads_of($file = NULL, $user_id = NULL, $check_archives_too = TRUE)
291 {
292 global $wpdb; // Global database object reference.
293 /** @var $wpdb \wpdb Reference for IDEs. */
294
295 if($file && is_string($file) /* Was ``$file`` passed in properly? */)
296 {
297 if(is_array($results = $wpdb->get_results("SELECT `meta_key`, `meta_value` FROM `".$wpdb->usermeta."` WHERE ".((is_numeric($user_id)) ? "`user_id` = '".esc_sql($user_id)."' AND " : '')."(`meta_key` = '".$wpdb->prefix."s2member_file_download_access_log'".(($check_archives_too) ? " OR `meta_key` = '".$wpdb->prefix."s2member_file_download_access_arc'" : '').") AND `meta_value` REGEXP '.*\"file\";s:[0-9]+:\"".esc_sql($file)."\".*'")))
298 {
299 foreach($results as $r /* Go through the entire array of results found in the `REGEXP` database query above. */)
300 if(is_array($la_entries = c_ws_plugin__s2member_utils_arrays::maybe_unserialize($r->meta_value)) && !empty($la_entries)) //260808 Safely unserialize the file download log entries.
301
302 foreach($la_entries as $la_entry /* Go through all of the entries in each result ``$r``; collecting `counter` values. */)
303 if(!empty($la_entry['file']) && $la_entry['file'] === $file && (!empty($la_entry['counter']) || ($la_entry['counter'] = 1)))
304 {
305 $total = (!empty($total)) ? $total + 1 : 1; // Only count `1` here (i.e., unique downloads).
306 break; // Break now. No need to continue looping; ``$file`` found in these entries.
307 }
308 }
309 }
310 return (!empty($total)) ? $total : 0; // Else return zero by default.
311 }
312
313 /**
314 * Checks for GZIP rules in root `.htaccess` file.
315 *
316 * @package s2Member\Files
317 * @since 120212
318 *
319 * @return bool True if rules exist, else false.
320 */
321 public static function no_gzip_rules_in_root_htaccess()
322 {
323 $start_line = '# BEGIN s2Member GZIP exclusions'; // Beginning line for this entry.
324 $end_line = '# END s2Member GZIP exclusions'; // Identifying end line for this entry.
325 $htaccess = ABSPATH.'.htaccess'; // Location of this `.htaccess` file.
326
327 if(file_exists($htaccess) && is_readable($htaccess) && ($htaccess_contents = file_get_contents($htaccess)) !== FALSE && is_string($htaccess_contents = trim($htaccess_contents)))
328 return preg_match('/'.preg_quote($start_line, '/').'['."\r\n".']+.*?['."\r\n".']+'.preg_quote($end_line, '/').'['."\r\n".']{0,2}/is', $htaccess_contents);
329
330 return FALSE;
331 }
332
333 /**
334 * Writes no GZIP rules into root `.htaccess` file.
335 *
336 * @package s2Member\Files
337 * @since 120212
338 *
339 * @return bool True if successfull, else false on any type of failure.
340 */
341 public static function write_no_gzip_into_root_htaccess()
342 {
343 if(defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
344 return FALSE; # No write access on this site.
345 }
346 if(c_ws_plugin__s2member_files::remove_no_gzip_from_root_htaccess())
347 {
348 $start_line = '# BEGIN s2Member GZIP exclusions'; // Beginning line for this entry.
349 $end_line = '# END s2Member GZIP exclusions'; // Identifying end line for this entry.
350 $htaccess = ABSPATH.'.htaccess'; // Location of this `.htaccess` file we need to write in.
351 $ideally_position_before = '# BEGIN WordPress'; // Ideally, we can position before this entry.
352
353 $no_gzip = $start_line."\n".trim(c_ws_plugin__s2member_utilities::evl(file_get_contents($GLOBALS['WS_PLUGIN__']['s2member']['c']['files_no_gzip_htaccess'])))."\n".$end_line;
354
355 if(file_exists($htaccess) && is_readable($htaccess) && is_writable($htaccess) && ($htaccess_contents = file_get_contents($htaccess)) !== FALSE && is_string($htaccess_contents = trim($htaccess_contents)))
356 {
357 if(stripos($htaccess_contents, $ideally_position_before) !== FALSE /* If we can position in the ideal location, that's awesome. Let's do that now. */)
358 $htaccess_contents = trim(str_ireplace($ideally_position_before, $no_gzip."\n\n".$ideally_position_before, $htaccess_contents));
359
360 else $htaccess_contents = trim($no_gzip."\n\n".$htaccess_contents); // Else, let's put it at the very top of the file by default.
361
362 return file_put_contents($htaccess, $htaccess_contents);
363 }
364 else if(!file_exists($htaccess) && is_writable(dirname($htaccess)))
365 {
366 return file_put_contents($htaccess, $no_gzip);
367 }
368 }
369 return FALSE;
370 }
371
372 /**
373 * Removes no GZIP rules in root `.htaccess` file.
374 *
375 * @package s2Member\Files
376 * @since 120212
377 *
378 * @return bool True if successful, else false on any type of failure.
379 */
380 public static function remove_no_gzip_from_root_htaccess()
381 {
382 if(defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
383 return FALSE; # No write access on this site.
384 }
385 $start_line = '# BEGIN s2Member GZIP exclusions'; // Beginning line for this entry.
386 $end_line = '# END s2Member GZIP exclusions'; // Identifying end line for this entry.
387 $htaccess = ABSPATH.'.htaccess'; // Location of this `.htaccess` file we need to write in.
388
389 if(file_exists($htaccess) && is_readable($htaccess) && is_writable($htaccess) && ($htaccess_contents = file_get_contents($htaccess)) !== FALSE && is_string($htaccess_contents = trim($htaccess_contents)))
390 {
391 $htaccess_contents = trim(preg_replace('/'.preg_quote($start_line, '/').'['."\r\n".']+.*?['."\r\n".']+'.preg_quote($end_line, '/').'['."\r\n".']{0,2}/is', '', $htaccess_contents));
392
393 return (file_put_contents($htaccess, $htaccess_contents) !== FALSE); // Check for `FALSE`, because this could return `0` if the file is now empty.
394 }
395 else if(!file_exists($htaccess))
396 {
397 return TRUE;
398 }
399 return FALSE;
400 }
401 }
402 }
403