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

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

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